简体   繁体   English

访问flask_wtf中的会话

[英]Access to session in flask_wtf

In forms.py I wanna get access to sessions. 在forms.py中,我想访问会话。 this is forms.py code: 这是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')

But when I add this code : 但是当我添加以下代码时:

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

It shows me this error: 它显示了此错误:

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

So how can I solve it? 那么我该如何解决呢?

You should use uid = session.get('user_id') only on request, for example: 您仅应在请求时使用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)

If this code calling not from request (another process, another thread, celery, unit test and etc), then you should create request context manually or avoid use context stack variables: 如果此代码不是从请求(另一个进程,另一个线程,芹菜,单元测试等)中调用的,那么您应该手动创建请求上下文或避免使用上下文堆栈变量:

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

Ok , I find how to solve that problem. 好的,我找到了解决该问题的方法。

I think one of the best way is to use session in the route file. 我认为最好的方法之一是在路由文件中使用会话。

This is my form code: 这是我的表单代码:

from flask_wtf import Form
from wtforms import SelectField

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

So I have an app with "our" name, I have access to session in this app: 因此,我有一个名称为“我们的”的应用,可以访问此应用中的会话:

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'))

Now I changed my form field data via app. 现在,我通过应用程序更改了表单字段数据。 form.name.choices=.... form.name.choices = ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM