You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/database/queries.md
+153Lines changed: 153 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -189,3 +189,156 @@ class State(rx.State):
189
189
with rx.session() as session:
190
190
return [list(row) for row in session.execute("SELECT * FROM user").all()]
191
191
```
192
+
193
+
## Async Database Operations
194
+
195
+
Reflex provides an async version of the session function called `rx.asession` for asynchronous database operations. This is useful when you need to perform database operations in an async context, such as within async event handlers.
196
+
197
+
The `rx.asession` function returns an async SQLAlchemy session that must be used with an async context manager. Most operations against the `asession` must be awaited.
198
+
199
+
```python
200
+
import sqlalchemy.ext.asyncio
201
+
import sqlalchemy
202
+
203
+
import reflex as rx
204
+
205
+
206
+
classAsyncUserState(rx.State):
207
+
users: list[User] = []
208
+
209
+
@rx.event(background=True)
210
+
asyncdefget_users_async(self):
211
+
asyncwith rx.asession() as asession:
212
+
result =await asession.execute(User.select())
213
+
asyncwithself:
214
+
self.users = (await result.all())
215
+
```
216
+
217
+
### Async Select
218
+
219
+
The following example shows how to query the database asynchronously:
0 commit comments