Closed mkdir700 closed 7 months ago
Fixed in #49 / #47 , will require a small change in the code however:
import uvicorn
from fastapi import FastAPI
from fastapi_sqlalchemy import DBSessionMiddleware, db
from sqlalchemy import text
app = FastAPI()
app.add_middleware(DBSessionMiddleware, db_url="sqlite:///db.db", commit_on_exit=True)
# Error
@app.get("/")
def main():
db.session.execute(
text("CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(255))")
)
return {"Hello": "World"}
# Ok
@app.get("/async")
async def async_main():
db.session.execute(
text("CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(255))")
)
return {"Hello": "World"}
if __name__ == "__main__":
uvicorn.run(app, host="127.0.0.1", port=8000)
Exception
I am developing an embedded program based on SQLite and have encountered the following exception:
Reproduce
Reason
By ChatGPT.
https://github.com/mfreeborn/fastapi-sqlalchemy/blob/3d182f202cb673a09c52b07fd2d52cb57ce382c5/fastapi_sqlalchemy/middleware.py#L43-L45
When calling
with db()
in the main thread, and since the path operation function is a normal function, it will be called and executed in a sub-thread. The same SQLite object appears in different threads, resulting in the above exception being thrown.The ultimate reason is that fastapi-sqlalchemy does not support synchronous path operation functions, so will this feature be considered for implementation?