簡體   English   中英

Python Flask-“檢查用戶名是否存在於MySQL數據庫中”

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

我正在運行一個使用用戶名和密碼的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應用程序時,我的網頁沒有返回任何內容。

好的,所以我不能發表評論,因為我沒有足夠的聲譽來獲取表單數據, 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和其他請求的更多信息,請參閱此處的文章

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM