RuntimeError: Working outside of application context.
That's the error I'm currently getting. I tried looking at previous threads about it but they confused me. Here's the relevant python code:
class Quiz(FlaskForm):
submit = SubmitField()
questions = get_questions()
for question in questions:
vars()[question["skill"]] = RadioField(u"{}".format(question["question"]),
choices=[("0", "Strongly disagree"), ("0", "Disagree"),
("1", "Neither agree nor disagree"), ("2", "Agree"),
("3", "Strongly agree")])
def get_questions():
questions = get_db().execute(
'SELECT skill, question FROM questions'
).fetchall()
return questions
I'm using vars() to dynamically add attributes to the class at creation. If I replace questions = get_questions() with questions = [{"skill":"skill","question":"question"},{"skill":"skill1","question":"question1"}] for example then it works perfectly. get_questions() simply accesses the questions table and grabs the question and corresponding skill from each row. The problem arises when questions calls get_db() and then specifically on the line if 'db' not in g.
def get_db():
if 'db' not in g:
g.db = sqlite3.connect(
current_app.config['DATABASE'],
detect_types=sqlite3.PARSE_DECLTYPES
)
g.db.row_factory = sqlite3.Row
return g.db
Here's the lines leading up to the error:
class Quiz(FlaskForm):
questions = get_questions()
questions = get_db().execute(
if 'db' not in g:
that's where I get the error RuntimeError: Working outside of application context.
I'm not sure why it's happening. It happens no matter which webpage I load. Could it be that classes can't access the database, only functions?
Edit:
File "x", line 39, in reraise
raise value
File "x", line 83, in find_best_app
app = call_factory(script_info, app_factory)
File "x", line 119, in call_factory
return app_factory()
from . import website
File "x", line 135, in <module>
class Quiz(FlaskForm):
File "x", line 144, in Quiz
questions = get_questions()
File "x", line 130, in get_questions
questions = get_db().execute(
File "x", line 9, in get_db
if 'db' not in g:
File "x", line 379, in <lambda>
__contains__ = lambda x, i: i in x._get_current_object()
File "x", line 306, in _get_current_object
return self.__local()
File "x", line 45, in _lookup_app_object
raise RuntimeError(_app_ctx_err_msg)
RuntimeError: Working outside of application context.
question from:
https://stackoverflow.com/questions/65948673/runtimeerror-working-outside-of-application-context-occurs-when-my-form-class