Urgent.News

What's breaking now, across thousands of outlets.

Tech

Python PostgreSQL with asyncpg: Async Database Operations

Python PostgreSQL with asyncpg: Async Database Operations asyncpg is the fastest PostgreSQL driver for Python — pure asyncio, no thread overhead, and up to 3× faster than psycopg2 on typical workloads. It is the go-to choice for any async Python backend. Installation pip install asyncpg # PostgreSQL server must already be running Connect and Create a Pool import asyncio import asyncpg from…

Python PostgreSQL with asyncpg: Async Database Operations

asyncpg is the fastest PostgreSQL driver for Python, boasting pure asyncio implementation without thread overhead. It attains up to 3× speed improvement over psycopg2 on typical workloads, becoming the go-to choice for any async Python backend.

To utilize asyncpg, one first installs it via pip install asyncpg. Ensure the PostgreSQL server is running prior to installation.

The initialization code includes importing necessary modules such as asyncio, asyncpg, and datetime. A DATABASE_URL variable is defined with the PostgreSQL connection details.

A create_pool function is defined to create an asyncpg connection pool using the provided DATABASE_URL. The pool is configured with a minimum of 2 and a maximum of 10 connections. Each connection has a command timeout of 30 seconds. Additionally, the application_name server setting is set to 'myapp'. A confirmation message is printed upon successful pool creation, and the pool object is returned.

Schema setup is handled by CREATE_TABLES, which includes defining users and posts tables with appropriate columns and constraints. Indexes are also created for efficient querying. The async setup_schema function takes an asyncpg Pool object as input and executes the CREATE_TABLES statement to create the required tables. A confirmation message is printed after schema setup.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in Tech

More from Saturday 29 August →