Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()'

like image 261
guri Avatar asked Jul 16 '15 01:07

guri


People also ask

How do I fix RuntimeError working outside of request context?

You should also be able to fix the following error: RuntimeError: Working outside of application context. This typically means that you attempted to use functionality that needed to interface with the current application object in some way. To solve this, set up an application context with app.

What is application context in Flask?

The application context is a good place to store common data during a request or CLI command. Flask provides the g object for this purpose. It is a simple namespace object that has the same lifetime as an application context.

How can a request context be created in Flask Python?

Flask automatically pushes a request context when handling a request. View functions, error handlers, and other functions that run during a request will have access to the request proxy, which points to the request object for the current request.

What does Flask G do?

g is an object provided by Flask. It is a global namespace for holding any data you want during a single app context. For example, a before_request handler could set g. user, which will be accessible to the route and other functions.


2 Answers

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.

like image 139
brenns10 Avatar answered Oct 18 '22 02:10

brenns10


I followed the answer from @brenns10 when I ran into a similar problem when using 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>
like image 5
Paddy Alton Avatar answered Oct 18 '22 01:10

Paddy Alton