Skip to content

Commit

Permalink
Link to FastAPI docs for usage w/peewee.
Browse files Browse the repository at this point in the history
  • Loading branch information
coleifer committed May 2, 2023
1 parent e31ec00 commit 48dcf98
Showing 1 changed file with 10 additions and 22 deletions.
32 changes: 10 additions & 22 deletions docs/peewee/database.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1449,32 +1449,20 @@ response middleware `sanic middleware <http://sanic.readthedocs.io/en/latest/san
FastAPI
^^^^^^^

Similar to Flask, FastAPI provides two event based hooks which we will use to open and
close our db connection. We'll open the connection when a request is received,
then close it when the response is returned.
FastAPI is an asyncio-compatible framework. Peewee relies on thread locals
(which are also compatible with gevent) to manage the connection state across
requests. For use with asyncio, some overrides are necessary to replace the
thread-local behavior with an asyncio-compatible context-local.

.. code-block:: python
from fastapi import FastAPI
from peewee import *
For a full treatment of using Peewee with FastAPI, consult the FastAPI
documentation here:

db = SqliteDatabase('my_app.db')
app = FastAPI()
https://fastapi.tiangolo.com/advanced/sql-databases-peewee/

# This hook ensures that a connection is opened to handle any queries
# generated by the request.
@app.on_event("startup")
def startup():
db.connect()
# This hook ensures that the connection is closed when we've finished
# processing the request.
@app.on_event("shutdown")
def shutdown():
if not db.is_closed():
db.close()
The above document covers:

* Adding asyncio context-aware connection state tracking
* Per-request connection handling

Other frameworks
^^^^^^^^^^^^^^^^
Expand Down

0 comments on commit 48dcf98

Please sign in to comment.