ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

使用Python、FastAPI和Psycopg 3异步Postgres

2026/8/14 12:47:30 拓冰建站 浏览量
使用Python、FastAPI和Psycopg 3异步Postgres

原文:使用Python、FastAPI和Psycopg 3异步Postgres - 桑鸟网

在写这篇文章的时候,由于Psycopg 3是一个相当新的版本,还没有大量的示例使用,所以我想我将演示一些东西。

pip install fastapi[all]
pip install psycopg[binary,pool]
import os
from contextlib import asynccontextmanagerfrom fastapi import FastAPI, Request
from psycopg_pool import AsyncConnectionPooldef get_conn_str():return f"""dbname={os.getenv('POSTGRES_DB')}user={os.getenv('POSTGRES_USER')}password={os.getenv('POSTGRES_PASSWORD')}host={os.getenv('POSTGRES_HOST')}port={os.getenv('POSTGRES_PORT')}"""@asynccontextmanager
async def lifespan(app: FastAPI):app.async_pool = AsyncConnectionPool(conninfo=get_conn_str())yieldawait app.async_pool.close()app = FastAPI(lifespan=lifespan)@app.get("/dogs")
async def get_red_dogs(request: Request):async with request.app.async_pool.connection() as conn:async with conn.cursor() as cur:await cur.execute("""SELECT * FROM dogs""")results = await cur.fetchall()return results@app.post("/dogs")
async def insert_dog(request: Request):try:async with request.app.async_pool.connection() as conn:async with conn.cursor() as cur:await cur.execute("""INSERT INTO dogs (name,age,colour)VALUES (%s, %s, %s); """, ("bonzo", 10, "red",))await conn.commit()except Exception:await conn.rollback()

应用程序启动时,初始化连接池并将其分配给应用程序对象上名为async_pool的属性。生命周期事件是当前在FastAPI中服务器启动后执行代码的推荐方式。

这样就可以在请求过程中从连接池中获取连接,而不是初始化一个新连接,初始化新连接有时可能需要很长时间。

使用上述语法对数据库执行异步操作。

参考资料:Lifespan Events - FastAPI