在我的 routes.py 中,我在表單驗證陳述句之后為從 SQLAlchemy 元組生成的轉換字典設定了一個變數。
在控制臺中輸入from routes import *
dict(Book.query.with_entities(Book.username, Book.choice).all())時,我會根據需要得到正確的字典{'user1': 'choice1', 'user2': 'choice2'}
如果我鍵入分配給該字典的變數dict_of_users的名稱,我會得到: NameError: name 'dict_of_users' is not defined
為什么它不能識別該變數,因為它在代碼中?
我想要實作的背后邏輯:
如果用戶從串列中選擇一個選項,則該用戶及其選項將作為鍵和值添加到字典中,否則字典為空。
我的路線.py:
@app.route("/booking", methods=['POST', 'GET'])
def booking():
session.permanent = True
app.permanent_session_lifetime = timedelta(seconds=5)
form = BookingForm()
if form.validate_on_submit():
book = Book(username=current_user.username, choice=form.book.data)
db.session.add(book)
db.session.commit()
flash('Your choice is registered', 'success')
dict_of_users = dict(Book.query.with_entities(Book.username, Book.choice).all())
return render_template('booking.html', title='Booking', form=form, dict_of_users=dict_of_users)
uj5u.com熱心網友回復:
如果它僅在函式內部,則無法在函式外部訪問它。由于該變數僅在函式中定義,因此您會收到NameError訊息。解決方法是在全域范圍內定義變數。
編輯:
作為對您評論的回應:
如果要訪問dict_of_users變數,請在函式外部宣告它。然后變數將包含它在全域范圍內的最新使用值,因此可以在函式外部訪問。
這樣的事情應該可以解決問題:
dict_of_users = None
@app.route("/booking", methods=['POST', 'GET'])
def booking():
session.permanent = True
app.permanent_session_lifetime = timedelta(seconds=5)
form = BookingForm()
if form.validate_on_submit():
book = Book(username=current_user.username, choice=form.book.data)
db.session.add(book)
db.session.commit()
flash('Your choice is registered', 'success')
dict_of_users = dict(Book.query.with_entities(Book.username, Book.choice).all())
return render_template('booking.html', title='Booking', form=form, dict_of_users=dict_of_users)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/478373.html
標籤:Python 烧瓶 sqlalchemy
上一篇:將變數傳遞給燒瓶中的表
