RuntimeError:在应用程序上下文之外工作

问题描述 投票:0回答:4

app.py

from flask import Flask, render_template, request,jsonify,json,g
import mysql.connector

app = Flask(__name__)

class TestMySQL():
    @app.before_request
    def before_request():
        try:
            g.db = mysql.connector.connect(user='root', password='root', database='mysql')
        except mysql.connector.errors.Error as err:
           resp = jsonify({'status': 500, 'error': "Error:{}".format(err)})
           resp.status_code = 500
           return resp

    @app.route('/')
    def input_info(self):
        try:     
            cursor = g.db.cursor()
            cursor.execute ('CREATE TABLE IF NOT EXISTS testmysql (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(40) NOT NULL, \
                     email VARCHAR(40) NOT NULL UNIQUE)')
            cursor.close()

test.py

from app import *
class Test(unittest.TestCase):         
    def test_connection1(self):  
        with patch('__main__.mysql.connector.connect') as mock_mysql_connector_connect:
            object = TestMySQL()
            object.before_request()  # Runtime error on calling this

我正在将 app 导入 test.py 进行单元测试。在将 'before_request' 函数调用到 test.py 时,它会抛出一个 RuntimeError:

working outside of application context
,调用 'input_info()'

时也会发生同样的情况
python mysql flask werkzeug flask-restful
4个回答
119
投票

Flask 有一个 Application Context,看起来你需要做类似的事情:

def test_connection(self):
    with app.app_context():
        #test code

您也可以将

app.app_context()
调用也推入测试设置方法中。


7
投票
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///todo.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

app.app_context().push()

Run in terminal
    >python
    >>>from app import app
    >>>from app import db
    >>>db.create_all()

Now it should work

5
投票

我按照@brenns10的回答,当时我在使用

pytest
时遇到了类似的问题。

我听从了将其放入测试设置的建议,这有效:

import pytest
from src.app import app


@pytest.fixture
def app_context():
    with app.app_context():
        yield


def some_test(app_context):
    # <test code that needs the app context>

0
投票

我正在使用 python3.8 并且不得不对已经发布的答案使用一个小的变化。我在 pytests 中包含了以下内容,并且不必更改测试文件其余部分的任何其他内容。

from flask import Flask

@pytest.fixture(autouse=True)
def app_context():
    app = Flask(__name__)
    with app.app_context():
        yield

这也可以与上下文管理器一起使用。 这里要注意的主要区别是 Flask 应用程序是在测试文件中创建的,而不是从主应用程序文件中导入的。

© www.soinside.com 2019 - 2024. All rights reserved.