diff --git a/supysonic/cli.py b/supysonic/cli.py index a586057..c2cf58d 100644 --- a/supysonic/cli.py +++ b/supysonic/cli.py @@ -1,7 +1,7 @@ # This file is part of Supysonic. # Supysonic is a Python implementation of the Subsonic server API. # -# Copyright (C) 2013-2022 Alban 'spl0k' Féron +# Copyright (C) 2013-2023 Alban 'spl0k' Féron # # Distributed under terms of the GNU AGPLv3 license. @@ -364,8 +364,10 @@ def user_rename(name, newname): def main(): config = IniConfig.from_common_locations() init_database(config.BASE["database_uri"]) - cli.main(obj=config) - release_database() + try: + cli.main(obj=config) + finally: + release_database() if __name__ == "__main__": diff --git a/supysonic/db.py b/supysonic/db.py index 4ab3a45..babe976 100644 --- a/supysonic/db.py +++ b/supysonic/db.py @@ -679,3 +679,11 @@ def init_database(database_uri): def release_database(): db.close() db.initialize(None) + + +def open_connection(): + db.connect() + + +def close_connection(): + db.close() diff --git a/supysonic/web.py b/supysonic/web.py index 6d203d9..c617ad1 100644 --- a/supysonic/web.py +++ b/supysonic/web.py @@ -1,7 +1,7 @@ # This file is part of Supysonic. # Supysonic is a Python implementation of the Subsonic server API. # -# Copyright (C) 2013-2022 Alban 'spl0k' Féron +# Copyright (C) 2013-2023 Alban 'spl0k' Féron # 2018-2019 Carey 'pR0Ps' Metcalfe # 2017 Óscar García Amor # @@ -16,7 +16,7 @@ from os import makedirs, path from .config import IniConfig from .cache import Cache -from .db import init_database +from .db import init_database, open_connection, close_connection from .utils import get_secret_key logger = logging.getLogger(__package__) @@ -50,6 +50,9 @@ def create_application(config=None): # Initialize database init_database(app.config["BASE"]["database_uri"]) + if not app.testing: + app.before_request(open_connection) + app.teardown_request(lambda exc: close_connection()) # Insert unknown mimetypes for k, v in app.config["MIMETYPES"].items(): @@ -83,4 +86,7 @@ def create_application(config=None): app.register_blueprint(api, url_prefix="/rest") + if not app.testing: + close_connection() + return app