[Python] Closing a session in Flask, SQLAlchemy to delete the temporaryx file

Discussão em 'Python' iniciado por Stack, Abril 24, 2025.

  1. Stack

    Stack Membro Participativo

    I know there are similar questions out there, but none answered my problem.

    I am using a basic test setup in Flask using SQLAlchemy, that is a slightly modified version of the Flask-tutorial tests. My problem is that the temporary file created by the app-fixture cannot be closed. This is the fixture:

    import os
    import tempfile

    import pytest
    from flask.testing import FlaskClient

    # custom modules: create_app is the function factory, db is flask_sqlalchemy.SQLAlchemy(model_class=Base)
    from flaskr import create_app
    from flaskr.models import db

    @pytest.fixture
    def app():
    # creates and opens a temporary file
    db_fd, db_path = tempfile.mkstemp(dir="test")

    # call the factory function, override DATABASE path so it points to the temporary
    # path instead of the instance folder
    app = create_app(
    {
    "TESTING": True,
    "SQLALCHEMY_DATABASE_URI": f"sqlite:///{db_path}",
    }
    )

    with app.test_client() as test_client:
    with app.app_context():
    db.create_all()

    yield app

    with app.test_client() as test_client:
    with app.app_context():
    db.drop_all()
    db.session.remove()

    os.close(db_fd)
    os.unlink(db_path)


    os.unlink() always fails, because the file is still used by another process. A typical usage in a test would be

    def test_example(app):
    with app.app_context():
    assert db.session.execute(stmt) ...


    I could probably just use the same file for testing the database every time, then delete it at the start of the app()-fixture, but I am worried that the cause of the unterminated session connection might also cause other problems, so I would like to understand and fix it.

    Continue reading...

Compartilhe esta Página