1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Flask out of application context

Discussão em 'Python' iniciado por Stack, Outubro 25, 2024 às 11:52.

  1. Stack

    Stack Membro Participativo

    I have an issue with app factories in Flask.

    This is my tree:

    .
    ├── Pipfile
    ├── app
    │ ├── Dockerfile
    │ ├── __init__.py
    │ ├── blueprints
    │ │ ├── __init__.py
    │ │ ├── auth
    │ │ │ └── __init__.py
    │ │ └── accounts
    │ │ ├── __init__.py
    │ │ ├── models.py
    │ ├── config.py
    │ ├── enums.py
    │ ├── extensions.py
    │ ├── helpers
    │ │ ├── __init__.py
    │ │ ├── auth.py
    │ ├── repositories
    │ │ ├── __init__.py
    │ │ ├── accounts.py
    ├── client_secrets.json
    ├── instance
    │ ├── app.db
    ├── requirements.txt
    └── run.py


    in app.py/__init__.py I have this:

    from flask import Flask
    from .config import Config
    from .blueprints import register_blueprints
    from .extensions import register_extensions
    import app.config

    def create_app(config_object=config.ProdConfig):
    app = Flask(__name__)
    app.config.from_object(config_object)
    with app.app_context():
    register_extensions(app)
    register_blueprints(app)
    return app



    Inside my accounts blueprint I imported a Class called AccountRepository (an interface ontop of the accounts model, to make CRUD operations), like so:

    from app.repositories.accounts import AccountRepository


    So when people access the create endpoint for e.g, I do

    AccountRepository.create_account(x,y,z)


    However, I get an out of context error, because some values are coming from the config as defaults:

    def create_account(name, max_plays=current_app.config["DEFAULT_MAX_PLAY"]):
    RuntimeError: Working outside of application context.

    This typically means that you attempted to use functionality that needed
    the current application. To solve this, set up an application context
    with app.app_context(). See the documentation for more information.


    Just to make things clear: the error happens when I try accessing the config from the repository file..

    App factory registers the accounts BP -> Account BP imports the account repo -> account repo tries reading from app config (ERROR)

    Why does it happen? I'm registering BPs using app context and I'm referencing it using current_app..

    Thx!

    Continue reading...

Compartilhe esta Página