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()
相关推荐
共享家952717 分钟前
MYSQL库及表的操作
数据库
想回家的一天2 小时前
Go1.25的源码分析-src/runtime/runtime1.go(GMP)
数据库·redis·缓存
阿里云大数据AI技术3 小时前
鹰角网络基于阿里云EMR Serverless StarRocks的实时分析工程实践
数据库·数据分析
久笙&3 小时前
对象存储解决方案:MinIO 的架构与代码实战
数据库·python·架构
码luffyliu4 小时前
MySQL:MVCC机制及其在Java秋招中的高频考点
java·数据库·mysql·事务·并发·mvcc
水涵幽树4 小时前
MySQL 时间筛选避坑指南:为什么格式化字符串比较会出错?
数据库·后端·sql·mysql·database
PythonicCC4 小时前
Django中的MVC和MVT模式
数据库·django·mvc
爱吃小白兔的猫4 小时前
【框架篇二】FastAPI路由与请求处理
fastapi
Mr. Cao code4 小时前
使用Tomcat Clustering和Redis Session Manager实现Session共享
java·linux·运维·redis·缓存·tomcat
AI 嗯啦7 小时前
SQL详细语法教程(七)核心优化
数据库·人工智能·sql