mirror of https://github.com/tiangolo/fastapi.git
✨ Use request.state for SQLAlchemy session in tutorial (#45)
This commit is contained in:
parent
ba10838c30
commit
12e087f0b5
|
|
@ -1,5 +1,9 @@
|
|||
## Next
|
||||
|
||||
* Update SQL with SQLAlchemy tutorial at <a href="https://fastapi.tiangolo.com/tutorial/sql-databases/" target="_blank">https://fastapi.tiangolo.com/tutorial/sql-databases/</a> using the new official `request.state`.
|
||||
|
||||
* Upgrade Starlette to version `0.11.1` and add required compatibility changes. PR <a href="https://github.com/tiangolo/fastapi/pull/44" target="_blank">#44</a>.
|
||||
|
||||
## 0.5.1
|
||||
|
||||
* Add section about <a href="https://fastapi.tiangolo.com/help-fastapi/" target="_blank">helping and getting help with **FastAPI**</a>.
|
||||
|
|
|
|||
|
|
@ -55,13 +55,13 @@ app = FastAPI()
|
|||
|
||||
@app.get("/users/{user_id}")
|
||||
def read_user(request: Request, user_id: int):
|
||||
user = get_user(request._scope["db"], user_id=user_id)
|
||||
user = get_user(request.state.db, user_id=user_id)
|
||||
return user
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def close_db(request, call_next):
|
||||
request._scope["db"] = Session()
|
||||
async def close_db(request: Request, call_next):
|
||||
request.state.db = Session()
|
||||
response = await call_next(request)
|
||||
request._scope["db"].close()
|
||||
request.state.db.close()
|
||||
return response
|
||||
|
|
|
|||
|
|
@ -102,15 +102,12 @@ The middleware we will create (just a function) will create a new SQLAlchemy `Se
|
|||
{!./src/sql_databases/tutorial001.py!}
|
||||
```
|
||||
|
||||
### About `request._scope`
|
||||
### About `request.state`
|
||||
|
||||
`request._scope` is a "private property" of each request. We normally shouldn't need to use a "private property" from a Python object.
|
||||
<a href="https://www.starlette.io/requests/#other-state" target="_blank">`request.state` is a property of each Starlette `Request` object</a>, it is there to store arbitrary objects attached to the request itself, like the database session in this case.
|
||||
|
||||
But we need to attach the session to the request to be able to ensure a single session/database-connection is used through all the request, and then closed afterwards.
|
||||
For us in this case, it helps us ensuring a single session/database-connection is used through all the request, and then closed afterwards (in the middleware).
|
||||
|
||||
In the near future, Starlette <a href="https://github.com/encode/starlette/issues/379" target="_blank">will have a way to attach custom objects to each request</a>.
|
||||
|
||||
When that happens, this tutorial will be updated to use the new official way of doing it.
|
||||
|
||||
## Create a `CustomBase` model
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue