Python Flask-“检查用户名是否存在于MySQL数据库中”

时间:2019-02-04 04:08:20

标签: python mysql flask-login

我正在运行一个使用用户名和密码的python Flask应用程序。我想检查用户名是否存在于Mysql数据库中。如果是这样,我想在网页上返回“用户名存在”。

下面是我的烧瓶代码:

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应用程序时,我的网页没有返回任何内容。

1 个答案:

答案 0 :(得分:0)

好的,我无法发表评论,因为我没有足够的声誉,但是要获取表单数据,request.method必须为POST,因为那是当用户单击按钮提交表单时。正如Brian Driscoll所说,request.method不能同时为POSTGET,就像说:

if bob.age == 15 and bob.age == 50 

bob不能同时具有15和50岁的年龄,以同样的方式request.method不能同时具有POSTGET。 所以你想做的是

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"

有关POSTGET和其他要求的更多信息,请参阅文章here