在forms.py中,我想访问会话。 这是forms.py代码:
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 :(得分: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')
答案 1 :(得分:0)
好的,我找到了解决这个问题的方法。
我认为最好的方法之一是在路径文件中使用session。
这是我的表单代码:
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'))
现在我通过app更改了表单字段数据。的 form.name.choices = .... 强>