gpt4 book ai didi

python - 运行时错误 : working outside of application context

转载 作者:IT老高 更新时间:2023-10-28 21:49:20 24 4
gpt4 key购买 nike

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:在应用程序上下文之外工作调用 'input_info()'

时也会发生同样的情况

最佳答案

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

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

您也可以将 app.app_context() 调用插入测试设置方法。希望这会有所帮助。

关于python - 运行时错误 : working outside of application context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31444036/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com