在应用程序上下文Pytest之外工作

2024-09-30 16:40:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,请帮助我

在环境中运行pytest时,我得到了RuntimeError: Working outside of application context.

      Traceback (most recent call last):
      File "test_route.py", line 2, in <module>
      from application import routes
      File "C:\Users\Propellente8\Documents\Valmee\Valmee_App\application\routes.py", line 111, in <module>
        @app.errorhandler(CustomException)
        File "C:\Users\Propellente8\Documents\Valmee\Valmee_App\senv\lib\site-packages\werkzeug\local.py", line 347, in __getattr__
        return getattr(self._get_current_object(), name)
        File "C:\Users\Propellente8\Documents\Valmee\Valmee_App\senv\lib\site-packages\werkzeug\local.py", line 306, in _get_current_object
        return self.__local()
        File "C:\Users\Propellente8\Documents\Valmee\Valmee_App\senv\lib\site-packages\flask\globals.py", line 52, in _find_app
        raise RuntimeError(_app_ctx_err_msg)
        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.app_context().  See the documentation for more information.

我的应用程序的树形结构如下:

    -App
      |-application
          |-__init__.py
          |-routes.py
      |-senv
      |-config.py
      |-test_route.py
      |-wsgi.py

在application/init.py中,代码如下:

     from flask import Flask
     from flask_sqlalchemy import SQLAlchemy

     db = SQLAlchemy()

     def create_app():
"""Construct the core application."""
     app = Flask(__name__, instance_relative_config=False)

db.init_app(app)
app.config.from_object('config.Config')
with app.app_context():
    # Imports
    from . import routes

    return app

在application/routes.py中,代码如下:

    from flask import request, jsonify
    from sqlalchemy import create_engine
    from flask import current_app as app
    from werkzeug.exceptions import HTTPException

    import psycopg2
    import pandas as pds
    import datetime as dt
    import json

    # Create an engine instance
    alchemyEngine   = create_engine("postgresql+psycopg2://postgres:postgres@127.0.0.1/MyDb");

    # Connect to PostgreSQL server
    dbConnection    = alchemyEngine.connect();

    class CustomException(Exception):
status_code = 400

def __init__(self, message, status_code=None, payload=None):
    Exception.__init__(self)
    self.message = message
    if status_code is not None:
        self.status_code = status_code
    self.payload = payload

def to_dict(self):
    rv = dict(self.payload or ())
    rv['message'] = self.message
    return rv

    @app.errorhandler(CustomException)
     def handle_invalid_usage(error):
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response

    @app.route('/', methods=['GET'])
     def test():
        return "Hello"
    @app.route('/fail', methods=['GET'])
     def testFail():
      raise CustomException("raised exception")

在配置文件中

    from os import environ
    from sqlalchemy import create_engine

    # app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql+psycopg2://postgres:postgres@127.0.0.1/Valmee_Analytics'
    class Config:

        # General Config
         SECRET_KEY = environ.get('SECRET_KEY')
        FLASK_APP = environ.get('FLASK_APP')
        FLASK_ENV = environ.get('FLASK_ENV')

        # Database
        SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://postgres:postgres@127.0.0.1/Valmee_Analytics'

在test_route.py文件中,包含以下代码:

    from application import create_app
    from application import routes

    def test_base_route():
        client = create_app.test_client()
        url = '/'

        response = client.get(url)
        assert response.get_data() == b'Hello, World!'
        assert response.status_code == 200

当我在环境中运行pytest时,我得到了错误。所以请帮我修一下


Tags: infrompytestimportselfappget