Reputation: 3746
In forms.py I wanna get access to sessions. this is forms.py code:
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?
Upvotes: 0
Views: 1151
Reputation: 3746
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=....
Upvotes: 0
Reputation: 26110
You should use uid = session.get('user_id')
only on request, for example:
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')
Upvotes: 3