'How can I split Flask app.py's decorated functions into another file?
I want to keep my Flask app.py small by pushing the decorated functions into another file.
I couldn't find a Pythonic way of doing it, but is there a Flask way?
This currently works:
import os
from config import Config
from context_processors.url_processors import prefixed_url_for
from flask import Flask
from greetings.views import greetings
from services.relational_database import db_session, init_db
app = Flask(__name__)
app.config.from_object(Config())
app.register_blueprint(greetings, url_prefix='/greetings/')
init_db()
### can these decorated functions be moved to another file? ###
@app.context_processor
def processors():
return dict(
prefixed_url_for=prefixed_url_for,
)
@app.teardown_appcontext
def shutdown_session(exception=None):
db_session.remove()
###:end can these decorated functions be moved to another file? ###
if __name__ == "__main__":
app.run(
host='0.0.0.0',
port=os.environ['WEB_PORT'],
debug=(os.environ['FLASK_ENV'] == 'development'),
ssl_context=context,
)
Is there a way to do something like this instead?:
...
from .anotherfile import processors
@app.context_processor
processors
# or even just:
from .anotherfile import decorated_functions
# replacing @app.teardown_appcontext altogether
...
There were ways of importing a decorator from another file, but the decorator is already provided by Flask so that's not what I want in this case.
This post (Flask context processors functions) shows an example of using context_processor, but I've already got that part working. Rather, I want to refactor it to a separate file.
So, these 2 lines:
@thingy.context_processor
def utility_processor():
would be in separate files or in a different file than app.py or views.py.
Thank you for your help 🙏
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
