Create the app outside of the global context of app.py to avoid any interference

This commit is contained in:
Gregoo 2025-01-21 11:26:42 +01:00
parent 1b823b158b
commit a6ab53efa7
3 changed files with 34 additions and 18 deletions

28
app.py
View File

@ -11,6 +11,10 @@ from bricktracker.socket import BrickSocket # noqa: E402
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
# Create the app
# Using 'app' globally interferse with the teardown handlers of Flask
def create_app(main: bool = False, /) -> Flask | BrickSocket:
# Create the Flask app # Create the Flask app
app = Flask(__name__) app = Flask(__name__)
@ -23,16 +27,28 @@ s = BrickSocket(
threaded=not app.config['NO_THREADED_SOCKET'], threaded=not app.config['NO_THREADED_SOCKET'],
) )
if main:
return s
else:
return app
if __name__ == '__main__': if __name__ == '__main__':
s = create_app(True)
# This never happens, but makes the linter happy
if isinstance(s, Flask):
logger.critical('Cannot run locally with a Flask object, needs a BrickSocket. Use create_app(True) to return a BrickSocket') # noqa: E501
exit(1)
# Run the application # Run the application
logger.info('Starting BrickTracker on {host}:{port}'.format( logger.info('Starting BrickTracker on {host}:{port}'.format(
host=app.config['HOST'], host=s.app.config['HOST'],
port=app.config['PORT'], port=s.app.config['PORT'],
)) ))
s.socket.run( s.socket.run(
app, s.app,
host=app.config['HOST'], host=s.app.config['HOST'],
debug=app.config['DEBUG'], debug=s.app.config['DEBUG'],
port=app.config['PORT'], port=s.app.config['PORT'],
) )

View File

@ -96,6 +96,6 @@ def setup_app(app: Flask) -> None:
g.version = __version__ g.version = __version__
# Make sure all connections are closed at the end # Make sure all connections are closed at the end
@app.teardown_appcontext @app.teardown_request
def close_connections(exception, /) -> None: def teardown_request(_: BaseException | None) -> None:
close() close()

View File

@ -13,4 +13,4 @@ then
fi fi
# Execute the WSGI server # Execute the WSGI server
gunicorn --bind "${BK_SERVER}:${BK_PORT}" "app:app" --worker-class "eventlet" "$@" gunicorn --bind "${BK_SERVER}:${BK_PORT}" "app:create_app()" --worker-class "eventlet" "$@"