User Registration Function with Flask Session
本问题已经有最佳答案,请猛点这里访问。
我正在尝试检查数据库中是否已有用户名,然后注册新用户。但是,无论我输入的用户名是否已经注册,它都会在URL中使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | @app.route('/register', methods=['GET', 'POST']) def register(): if request.method == 'POST': reg_username = request.form.get['username'] reg_password = request.form.get['password'] # Check if username exists in database query ="SELECT username FROM users WHERE username = :username" if db.execute(query, {'username': reg_username}).first(): flash('Username already exists') return render_template('register.html') else: new_user = User(reg_username, reg_password) db.session.add(new_user) db.session.commit() session['username']=reg_username return redirect(url_for('login')) return render_template('register.html') |
您的代码(if语句块)需要一个
将代码更改为下面的代码,并确保将HTML模板中的表单方法更改为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | @app.route('/register', methods=['GET', 'POST']) def register(): if request.method == 'POST': reg_username = request.form['username'] reg_password = request.form['password'] # Check if username exists in database query ="SELECT username FROM users WHERE username = :username" if db.execute(query, {'username': reg_username}).first(): flash('Username already exists') return render_template('register.html') else: new_user = User(reg_username, reg_password) db.session.add(new_user) db.session.commit() session['username']=reg_username return redirect(url_for('login')) return render_template('register.html') |
HTML表单的外观示例
1 2 3 | <form action="{{url_for('register')}}" method="POST"> <!––some input--> </form> |