目录

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()
本文是转载文章,点击查看原文
如有侵权,请联系 xyy@jishuzhan.net 删除
相关推荐
blueboySalvat19 分钟前
Redis分布式锁的两种实现方式(Redis+定时任务/Redisson)
redis
betazhou27 分钟前
基于Oracle ADG通过dblink创建物化视图同步数据到目标库
数据库·oracle·view·视图·物化视图·materialized
Gauss松鼠会29 分钟前
openGauss新特性 | 自动参数化执行计划缓存
java·数据库·spring·缓存·性能优化·database
eqwaak033 分钟前
MySQL 超详细安装教程与常见问题解决方案
数据库·python·mysql·adb·语言模型
born-stubborn42 分钟前
MySQL安装实战分享
数据库·mysql·adb
有什么东东1 小时前
山东大学软件学院创新项目实训开发日志(12)之将对话记录保存到数据库中
java·数据库·vue·springboot
new一个奶黄包1 小时前
MySql入门
c语言·数据库·c++·mysql·adb
计算机毕设定制辅导-无忧学长1 小时前
TDengine 可靠性保障:数据持久化与容灾备份(二)
数据库·oracle·tdengine
hac13221 小时前
redis大key排查指南
数据库·redis
Agome991 小时前
MySQL行列转换
数据库·mysql