RuntimeError: working outside of request context Flask Session

RuntimeError: working outside of request context Flask Session

我在 RuntimeError: working out of request context 错误,而 运行 在 Flask 中进行测试。我尝试了其他线程的多个建议,但 none 对我有用。

我的一部分 views.py:

    @user_app.route('/login', methods =('GET', 'POST'))
    def login():
        form = LoginForm()
        error = None
        if form.validate_on_submit():
            user = User.objects.filter(username=form.username.data).first()
            if user:
                if bc.hashpw(form.password.data, user.password) == user.password:
                    session['username']=form.username.data
                    return 'User Logged In'
                else:
                    user = None
            if not user:
                error = 'Incorrect credentials'

        return render_template('user/login.html',form=form,error=error)

我的相关部分tests.py:

    from application import create_app as create_app_base

    def create_app(self):
        self.db_name = 'flaskbook_test'
        return create_app_base(
            MONGODB_SETTINGS={'DB':self.db_name},
            TESTING=True,
            WTF_CSRF_ENABLED=False,
            SECRET_KEY='SecretKey'
        )

    def setUp(self):
        self.app_factory = self.create_app()
        self.app = self.app_factory.test_client()
        #self.app.application.app_context().push() <-- this did not help

    def tearDown(self):
        db = _get_db()
        db.client.drop_database(db)

    def test_login_user(self):
        #create user
        self.app.post('/register', data=self.user_dict())
        #login user
        rv = self.app.post('/login',data=dict(
            username='username',
            password='password'
        ))
        #check session is set
        with self.app as c:
            rv = c.get('/')
        assert session.get('username') == self.user_dict()['username']

我已经尝试添加 app_context 和 self.app.application.app_context().push() 如上所述:

    with self.app.application.app_context():
        assert session.get('username') == self.user_dict()['username']

但是没有用。 每当我调用 session['username'] 时,我都会收到 RuntimeError: working outside of request context。

我的requirements.txt:Flask0.10.1 Flask-Script 2.0.5 flask-mongoengine 0.7.4

请帮忙

你要的是request context, not the app context.

Flask 包含一些方便的函数来为您推送请求上下文 - 查看 Flask testing docs 并且您会看到很多相关信息,包括应用程序对象上的 test_request_context 方法。

将其与 app.test_client 结合以推送请求上下文,然后模拟客户端行为,例如 POST 到您的端点。试试这个:

with self.app.test_request_context('/'), self.app.test_client() as c:
    rv = c.post('/')
    assert session.get('username') == self.user_dict()['username']