RuntimeError: working outside of application context

7 浏览
0 Comments

RuntimeError: working outside of application context

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()  # 运行此处会引发运行时错误

我将app导入到test.py中进行单元测试。在test.py中调用'before_request'函数时,它会引发一个RuntimeError: working outside of application context,调用'input_info()'时也会发生相同情况。

0