我是一個嘗試創建簡單應用的Flask新手。我目前卡在用戶註冊,我試圖將數據保存在數據庫中,但沒有發生。但是,我正在做的日誌記錄表明該操作是成功的。有人能告訴我我做錯了什麼嗎?無法寫入MySQL數據庫
下面是部分代碼的那會幫助你理解我想要做的事:
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
from flask.ext.mysqldb import MySQL
# Configuration
MYSQL_HOST = 'localhost'
MYSQL_USER = 'root'
MYSQL_PASSWORD = 'root'
MYSQL_DB = 'up2date'
DEBUG = True
SECRET_KEY =
'\xc6)\x0f\\\xc5\x86*\xd7[\x92\x89[\x95\xcfD\xfd\xc1\x18\x8e\xf1P\xf7_\r'
# Create the flask app
app = Flask(__name__)
app.config.from_object(__name__)
# Create instance for working with MySQL
mysql = MySQL(app)
# Function to connect to DB
def connect_db():
return mysql.connection.cursor()
# define functions that will make DB available automatically on each request
@app.before_request
def before_request():
g.db = connect_db()
@app.teardown_request
def teardown_request(exception):
g.db.close()
最後,執行用戶註冊代碼:
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
email = request.form['email']
password = request.form['password']
result = g.db.execute('INSERT INTO users (email, password) VALUES (%s, %s)', [email, password])
print(email, password)
print(result, " rows affected")
flash('Registration successful! You may log in now.')
return redirect(url_for('show_home'))
兩個print
語句確認電子郵件地址和密碼被正確捕獲,並且result
變量包含1
,表示1行受到影響。但數據庫中仍然沒有一行。我先前認爲這有事可做犯有,但g.db.commit()
拋出錯誤:AttributeError的:「光標」對象有沒有屬性「提交」
你能否提供'commit'的錯誤。 – ipinak
@ipinak添加到我的文章的結尾! – dotslash