2013-11-27 56 views
0

在forms.py我想訪問會話。 這是forms.py代碼:訪問flask_wtf中的會話

from flask_wtf import Form 
from wtforms import SelectField,FileField,TextAreaField,TextField,validators 
. 
. 
. 
class Send(Form): 
    group = SelectField('Group',[validators.Required('you must select a group')],coerce=int,choices=c) 
    title = TextField('Title',[validators.Required('you must enter a title')]) 
    content = TextAreaField('Content',[validators.Required('you must enter a content')]) 
    attachment = FileField('Attachment') 

但當我添加以下代碼:

from flask import session 
uid = session.get('user_id') 

它表明我這個錯誤:

raise RuntimeError('working outside of request context') 
RuntimeError: working outside of request context 

所以,我怎麼能解決呢?

+0

你對用戶ID有什麼期待?請記住,用戶ID將從請求變爲請求,因此在表單中聲明一次沒有任何意義。 –

+0

@MarkHildreth我需要用於從數據庫中獲取用戶記錄的用戶標識符,並以表單(selectField)顯示它們。所以我在會話中保存了用戶標識,我需要在表單中使用它。那麼你有什麼想法讓它變得更好嗎? – Mortezaipo

回答

0

好吧,我找到了如何解決這個問題。

我認爲最好的方法之一是在路徑文件中使用會話。

這是我的表單代碼:

from flask_wtf import Form 
from wtforms import SelectField 

class Test(Form): 
    name = SelectField('Name') 

所以我與「我們」的名字,我需要訪問會話在此應用程序的應用程序:

from flask import Blueprint,session,render_template 
from form import Test 
our = Blueprint('our',__name__) 
@our.route('/') 
def index(): 
    form = Test() 
    #session['name'] = 'hedi' 
    if session.get('name').lower() == "morteza": 
     form.name.choices = ((1,'mori'),(2,'hedi')) 
    else: 
     form.name.choices = ((1,'you')) 
    return render_template('index.html',form=form) 
    #return str(session.get('name')) 

現在我改變了我的表單字段通過應用的數據。 form.name.choices = ....

3

你應該只要求使用uid = session.get('user_id'),例如:

app = Flask(__name__) 

@app.route('/') 
def home(): 
    '''dispatcher functions works with request context''' 
    uid = session.get('user_id') 
    return str(uid) 

如果這個代碼請求(另一個進程,另一個線程,芹菜,單元測試和等)調用沒有,那麼你應該創建請求上下文手動或避免使用上下文堆棧變量:

with app.test_request_context(): 
    uid = session.get('user_id') 
+0

感謝您的重放,關於app.test_request_context()我有問題,有時我使用Blueprint代替,並且出現錯誤,因爲Blueprint沒有test_request_context(),那麼我該如何解決?謝謝 – Mortezaipo

+0

你必須得到應用程序並調用'test_request_context()',可能'current_app'不適合你的情況。但看起來你想爲這種情況建立不好的解決方案。更好地描述你想要做什麼? – tbicr

+0

好的,我有3個應用程序有不同的工作,所以在所有的應用程序中,我想檢查身份驗證並通過會話獲取用戶ID以提供某些功能。那麼最好的解決方案是什麼,或者你的想法是什麼? – Mortezaipo