【问题标题】:Python Flask not committing data to databasePython Flask 未将数据提交到数据库
【发布时间】:2021-03-27 19:37:40
【问题描述】:

我试图简单地向我的数据库提交一些东西,但无论出于何种原因,当我提交表单时它总是给我:

Internal Server Error 服务器遇到内部错误并且被 无法完成您的请求。服务器过载或 应用程序出现错误。

我不知道为什么会这样,我的代码看起来都很好,功能也很好。

这是我的 app.py:

from flask import Flask, render_template, session, request, url_for, g
from flask_mysqldb import MySQL

app = Flask(__name__)

#Connect to MySQL db
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = 'root'
app.config['MYSQL_DB'] = 'forum'
app.config['MYSQL_PORT'] = 8889

mysql = MySQL(app)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/signup', methods=["POST"])
def signup():
    username = str(request.form["username"])
    password = str(request.form["password"])
    cursor = mysql.cursor()
    cursor.execute("INSERT INTO users (username, password) VALUES(%s, %s",(username, password))
    mysql.commit()
    redirect(url_for("login"))

@app.route("/login")
def login():
    return render_template("login.html", )

if __name__ == '__main__':
    app.run(debug=True)

还有我的 index.html:

<h1>Simple Login Form</h1>

<form action="/signup" method="post">
    <input type="text" name="username" required/>
    <input type="password" name="password" required/>
    <input type="submit"/>
</form>

【问题讨论】:

  • 您的查询中缺少右括号

标签: python mysql flask


【解决方案1】:

cursor.execute() 函数中的括号尚未完全闭合。试试这个:

# ...

app.route('/signup', methods=["POST"])
def signup():
    # ...
    cursor.execute("INSERT INTO users (username, password) VALUES(%s, %s)",(username, password))
    mysql.commit()
    redirect(url_for("login"))
# ...

【讨论】:

  • 抱歉回复晚了,但我已经尝试过了,但我仍然收到内部服务器错误...任何线索为什么?是我的 app.config 的问题吗?
猜你喜欢
  • 2021-12-26
  • 1970-01-01
  • 2019-06-18
  • 1970-01-01
  • 1970-01-01
  • 2012-12-15
  • 2013-05-26
  • 2020-08-18
  • 2016-07-23
相关资源
最近更新 更多