我正在运行一个 python Flask 应用程序,它需要用户名和密码。我想检查Mysql数据库中是否存在该用户名。如果是的话,我想在网页上返回“用户名存在”。
下面是我的 flask 代码:
from flask import Flask,render_template,request,redirect
from flask_mysqldb import MySQL
import yaml
app = Flask(__name__)
db = yaml.load(open('db.yaml'))
app.config['MYSQL_HOST'] = db['mysql_host']
app.config['MYSQL_USER'] = db['mysql_user']
app.config['MYSQL_PASSWORD'] = db['mysql_password']
app.config['MYSQL_DB'] = db['mysql_db']
mysql =MySQL(app)
@app.route('/', methods=['GET','POST'])
def index():
if request.method == 'POST' and request.method=='GET':
#fetch form data
userdetails = request.form
name = userdetails['name']
email = userdetails['email']
cur = mysql.connection.cursor()
new_value= cur.execute("SELECT (name,email) FROM users where name = %s and email=%s",'name','email')
if new_value> 0:
return "the username exists"
else:
return "SUCCESS!,Successfully entered into the Database"
return render_template('index.html')
<小时/>
当我运行 Flask 应用程序时,我的网页不返回任何内容。
最佳答案
好吧,所以我无法发表评论,因为我没有足够的声誉,但是要获取表单数据,request.method
需要是POST
,因为这是用户点击的时候提交表单的按钮。正如 Brian Driscoll 所说,request.method
不能同时是 POST
和 GET
,就像说:
if bob.age == 15 and bob.age == 50
bob 不能同时是 15 岁和 50 岁,同样,request.method
不能是 POST
和 GET
同时。
所以你想做的是
if request.method == 'POST':
userdetails = request.form
name = userdetails['name']
email = userdetails['email']
cur = mysql.connection.cursor()
new_value= cur.execute("SELECT (name,email) FROM users where name = %s and email=%s",'name','email')
if new_value> 0:
return "the username exists"
else:
return "SUCCESS!,Successfully entered into the Database"
有关POST
、GET
和其他请求的更多信息,您可以引用文章here
关于Python flask - "Check if the username exists in the MySQL database",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54510027/