简体   繁体   English

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

[英]Python Flask - “ Check if the username exists in the MySQL database”

I am running a python Flask application which takes a username and password. 我正在运行一个使用用户名和密码的python Flask应用程序。 I wanted to check if the username exists on the Mysql database. 我想检查用户名是否存在于Mysql数据库中。 If it does, I wanted to return " username exists" on the web page. 如果是这样,我想在网页上返回“用户名存在”。

below is my flask code: 下面是我的烧瓶代码:

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')

when i run the flask application, my web page doesnt return anything. 当我运行flask应用程序时,我的网页没有返回任何内容。

ok so i cant comment since i dont have enough reputation however to fetch the form data the request.method needs to be POST since that is when a user clicks on a button to submit the form. 好的,所以我不能发表评论,因为我没有足够的声誉来获取表单数据, request.method必须是POST因为那是当用户单击按钮提交表单时。 As Brian Driscoll stated, request.method can not be both POST and GET simultaneously, its like saying: 正如Brian Driscoll所说, request.method不能同时是POSTGET ,就像这样说:

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

bob cant be both 15 AND 50 years old at the same time, in the same way request.method cant be POST AND GET at the same time. bob不能同时使用15和50岁,也不能使用request.method方式同时进行POSTGET so what you want to do is 所以你要做的是

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"

For more info about POST , GET and other requests you can refer to the article here 有关POSTGET和其他请求的更多信息,请参阅此处的文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM