Python 运行时错误:在应用程序上下文之外工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31444036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:00:59  来源:igfitidea点击:

RuntimeError: working outside of application context

pythonmysqlflaskwerkzeugflask-restful

提问by guri

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"  

I am importing appinto test.pyfor unit testing.On calling 'before_request' function into test.py ,it is throwing RuntimeError: working outside of application context same is happening on calling 'input_info()'

我正在将应用程序导入test.py以进行单元测试。在将“ before_request”函数调用到 test.py 时,它抛出 RuntimeError:在应用程序上下文之外工作同样发生在调用“ input_info()”时

采纳答案by brenns10

Flask has an Application Context, and it seems like you'll need to do something like:

Flask 有一个Application Context,似乎您需要执行以下操作:

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

You can probably also shove the app.app_context()call into a test setup method as well. Hope this helps.

您也可以将app.app_context()调用推送到测试设置方法中。希望这可以帮助。

回答by Paddy Alton

I followed @brenns10 's answer when I ran into a similar problem when using pytest.

当我在使用pytest.

I followed the suggestion of putting it into test setup, this works:

我遵循了将其放入测试设置的建议,这是有效的:

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>