Skip to content

Commit 33d1e57

Browse files
committed
Doc note on sync fastapi endpoints
1 parent ecfc08f commit 33d1e57

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

docs/peewee/framework_integration.rst

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -364,6 +364,47 @@ starts, shut the pool down on exit).
364364
365365
.. seealso:: :ref:`pydantic`
366366

367+
Synchronous endpoints
368+
^^^^^^^^^^^^^^^^^^^^^
369+
370+
FastAPI runs a plain ``def`` endpoint in a worker thread, so synchronous
371+
peewee works unmodified. Scope the connection inside the endpoint body:
372+
373+
.. code-block:: python
374+
375+
from fastapi import FastAPI
376+
from peewee import *
377+
378+
379+
db = SqliteDatabase('app.db')
380+
381+
class User(db.Model):
382+
name = TextField()
383+
email = TextField(unique=True)
384+
385+
with db:
386+
db.create_tables([User])
387+
388+
app = FastAPI()
389+
390+
@app.get('/users')
391+
def list_users():
392+
with db:
393+
return list(User.select().dicts())
394+
395+
@app.post('/users')
396+
def create_user(name: str, email: str):
397+
with db:
398+
user = User.create(name=name, email=email)
399+
return {'id': user.id, 'name': user.name}
400+
401+
Do not manage the connection with a ``yield`` dependency or as request hook.
402+
FastAPI dispatches a sync dependency's setup, the endpoint, and the teardown as
403+
three separate threadpool calls(!), and under load they land on different
404+
threads. Peewee's connection state is thread-local, so each operation may see a
405+
different local state. By using ``with db:`` inside the endpoint body, the
406+
connection will be scoped properly.
407+
367408
.. _quart:
368409

369410
Quart

0 commit comments

Comments
 (0)