Integrating Peewee ORM with aiohttp for Asynchronous Database Access

Feb 22, 2024 ยท 2 min read

The aiohttp library provides powerful tools for building asynchronous Python web applications. On the data access side, Peewee is a simple yet powerful ORM that makes working with SQL databases easy.

Combining these two libraries allows building high-performance async web apps with an expressive and Pythonic object-relational mapper for the database access. Here's how to integrate them:

Basic Setup

First install the libraries:

pip install aiohttp peewee

Then create the Peewee database instance and point it to your database:

import peewee

db = peewee.PostgresqlDatabase('my_app')

Next, define Peewee models as usual:

class User(peewee.Model):
    username = peewee.CharField()
    
    class Meta:
        database = db

Async Database Access

To avoid blocking the event loop, we need to use the peewee_async library to make the Peewee calls asynchronous:

pip install peewee-async

Then we can access the database in async routes:

import peewee_async

async def register_user(request):
    user = User(username=request.username)
    await user.async_save() 
    # Other ORM calls like create, get, delete also work!
    return web.Response(text='User created successfully!')

app.router.add_post('/users', register_user)

The async_ methods allow non-blocking database access.

Transaction Support

For transactions that span multiple statements, use database.atomic_async() :

async with db.atomic_async():
   await transfer_funds(from_user, to_user, amount)

This ensures the transaction is committed or rolled back atomically.

By integrating Peewee with aiohttp, we get the best of both worlds - a clean and expressive ORM with non-blocking asynchronous I/O! Let me know in the comments if you have any other questions.

Browse by tags:

Browse by language:

The easiest way to do Web Scraping

Get HTML from any page with a simple API call. We handle proxy rotation, browser identities, automatic retries, CAPTCHAs, JavaScript rendering, etc automatically for you


Try ProxiesAPI for free

curl "http://api.proxiesapi.com/?key=API_KEY&url=https://example.com"

<!doctype html>
<html>
<head>
    <title>Example Domain</title>
    <meta charset="utf-8" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
...

X

Don't leave just yet!

Enter your email below to claim your free API key: