【问题标题】:Python Flask - " Check if the username exists in the MySQL database"Python Flask - “检查用户名是否存在于 MySQL 数据库中”
【发布时间】:2019-02-04 04:08:19
【问题描述】:

我正在运行一个接受用户名和密码的 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')

当我运行烧瓶应用程序时,我的网页没有返回任何内容。

【问题讨论】:

  • If request.method == ‘POST’ and request.method == ‘GET’ 永远不会为真 - request.method 一次只能取一个值。您的意思是在两个子句之间加上“或”吗?
  • 当我运行 python 应用程序时,我看到“127.0.0.1 - - [03/Feb/2019 21:23:31]”GET /?name=rick&email=rick%40gmail.com HTTP/ 1.1" 200" 。这就是“GET”属性背后的原因
  • 好的,但我认为你没有完全阅读我的评论 - 你的 if 条件总是返回 false,因为 request.method 不能同时是“POST”和“GET”。
  • 我编辑了代码以删除“get”,只将 request.method 保留为“post”。但是,我的网页仍然没有返回任何内容。

标签: python mysql flask-login


【解决方案1】:

好的,所以我不能发表评论,因为我没有足够的声誉但是要获取表单数据 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

【讨论】:

  • 我将 request.method 设置为“POST”。网页仍然没有返回任何内容。
  • 你能分享你的 HTML
  • @A.Laffir 设置它是什么意思?
猜你喜欢
  • 2021-12-15
  • 1970-01-01
  • 1970-01-01
  • 2013-12-31
  • 2021-12-28
  • 2019-06-19
  • 2021-12-27
  • 2013-08-31
相关资源
最近更新 更多