Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

python - 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()  """Runtime error on calling this"  

I am importing app into test.py for 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()'

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...