FastAPI使用异步Redis

  1. 安装依赖
bash 复制代码
pip install fastapi redis uvicorn
  1. 主要代码
python 复制代码
#!/usr/bin/env python
import os
import sys
from contextlib import AbstractAsyncContextManager, asynccontextmanager
from datetime import timedelta
from pathlib import Path

from fastapi import FastAPI, Request
from pydantic import BaseModel
from redis import asyncio as aioredis


class RegisterRedis(AbstractAsyncContextManager):
    def __init__(self, app: FastAPI, *args, **kw) -> None:
        app.state.redis = self._redis = aioredis.Redis(*args, **kw)

    async def __aenter__(self) -> "RegisterRedis":
        await self._redis.ping()
        return self

    async def __aexit__(self, *args, **kw):
        await self._redis.aclose()

    @staticmethod
    def get_client(request: Request) -> aioredis.Redis:
        return request.app.state.redis


@asynccontextmanager
async def lifespan(app: FastAPI):
    async with RegisterRedis(app):
        yield


app = FastAPI(lifespan=lifespan)


@app.get("/")
async def get_all_redis_keys(request: Request) -> list[str]:
    redis = RegisterRedis.get_client(request)
    return await redis.keys()


class Item(BaseModel):
    key: str
    value: str | int | float | bytes
    expire: int | timedelta | None = None


@app.post("/")
async def set_key_value(request: Request, item: Item) -> dict[str, str]:
    redis = RegisterRedis.get_client(request)
    await redis.set(item.key, item.value, item.expire or None)
    value = await redis.get(item.key)
    return {item.key: value.decode()}


def runserver() -> None:
    """This is for debug mode to start server. For prod, use supervisor+gunicorn instead."""
    import uvicorn  # type:ignore

    root_app = Path(__file__).stem + ":app"
    auto_reload = "PYCHARM_HOSTED" not in os.environ
    host = "0.0.0.0"
    port = 8000
    if sys.argv[1:]:
        port = int(sys.argv[1])
    if sys.platform == "darwin" or sys.platform.lower().startswith("win"):
        tool = "open" if Path("/usr/bin/open").exists() else "explorer"
        os.system(f"{tool} http://127.0.0.1:{port}")  # Auto open browser
    uvicorn.run(root_app, host=host, port=port, reload=auto_reload)


if __name__ == "__main__":
    runserver()
相关推荐
Li_7695329 分钟前
Redis进阶(二)—— Redis 事务
数据库·redis·缓存
少云清10 分钟前
【接口测试】2_PyMySQL模块 _数据库操作步骤及事务
数据库·pymysql·代码实现
AI题库17 分钟前
PostgreSQL 18 从新手到大师:实战指南 - 1.3 Docker环境搭建
数据库·docker·postgresql
少云清26 分钟前
【接口测试】3_PyMySQL模块 _连接数据库
数据库·pymysql·代码实现
lkbhua莱克瓦2431 分钟前
基础-SQL-DML
开发语言·数据库·笔记·sql·mysql
CodeAmaz1 小时前
Redis大Key与热点Key问题解决方案
redis·大key·热点key
herinspace1 小时前
管家婆网店ERP如何录入成本调价单
服务器·数据库·oracle·智能手机·电脑
短剑重铸之日1 小时前
7天读懂MySQL|Day 1: MySQL 架构全景
数据库·mysql·架构
醉风塘1 小时前
MongoDB高级查询全攻略:使用MongoTemplate实现分组、排序、分页与连表查询
数据库·mongodb
TG:@yunlaoda360 云老大1 小时前
如何确保华为云国际站代理商的服务可用性?
数据库·人工智能·华为云