Fastapi 之redis

持續創作,加速成長!這是我參與「掘金日新計劃 · 6 月更文挑戰」的第21天,點擊查看活動詳情

asyncio (3156) Redis 客戶端庫。該庫旨在爲基於 asyncio 的 Redis 提供簡單明瞭的接口。

前言:

今天來介紹一款非常適用於Fastapi的連接redis的客戶端攻擊,因爲fastapi的優秀異步能力,不得不給他也配一個支持異步的連接redis工具,那麼,aioredis 他來了。

本文章主要介紹aioredis的快速簡單用法。意於拋磚引玉,不會對於具體api進行詳細的說明,需要一定的使用redis-py的經驗。

基礎環境:

首先準備如下基礎環境:

  • aioredis (version>=2.0)
  • python環境爲3.9

要注意一下 在2.0版本已經不需要用捨棄了create_redis_pool的連接方式,整個核心和公共API已經經過重構,完美擁抱redis-py,所以此文章不在講述低於2.0版本的功能和用法。

連接方式:

import asyncio
import aioredis


async def main():
    # Redis client bound to single connection (no auto reconnection).
    redis = aioredis.from_url(
        redis://127.0.0.1", port=44117, password='qwaszx', db=2, encoding="utf-8", decode_responses=True
    )
    
    async with redis.client() as conn:
        await conn.set("my-key", "value")
        val = await conn.get("my-key")
        print(val)
        
        async def redis_pool():
            # Redis client bound to pool of connections (auto-reconnecting).
            redis = aioredis.from_url(
                "redis://localhost", encoding="utf-8", decode_responses=True
            )
            await redis.set("my-key", "value")
            val = await redis.get("my-key")
            print(val)
            
            if __name__ == "__main__":
                asyncio.run(main())
    asyncio.run(redis_pool())
複製代碼

在Fastapi中使用實例:

在項目創建時將redis掛載到app上

from fastapi import FastAPI

def register_redis(app: FastAPI):
    async def redis_pool():
        redis = await aioredis.from_url(
        url="redis://127.0.0.1", port=44117, password='qwaszx', db=2, encoding="utf-8", decode_responses=True
    )
        return redis
        
    @app.on_event("startup")
    async def srartup_event():
        app.state.redis = await redis_pool()
        
 from fastapi import FastAPI

app = FastAPI()
# 進行掛載
register_redis(app)


@app.get("/test")
async def test(q: str):
    key = time.time()
    await app.state.redis.set(key=key, value=q)
    # 添加數據,5秒後自動清除
    await app.state.redis.setex(key="vvv", seconds=5, value="臨時存在")
    value = await app.state.redis.get(key=key)
    return {key: value}
複製代碼

子路由中使用:

  • 添加參數request: Request
  • 通過request.app.state.redis獲取Redis實例
  • 通過獲取到的實例,進行操作Redis
router = APIRouter()

@router.get("/api/test")
async def test(request: Request, value: str):
    api_time = f"api-{time.time()}"
    await request.app.state.redis.setex(key=api_time, seconds=5.5, value=value)
    value = await request.app.state.redis.get(key=api_time)
    return {api_time: value}

app.include_router(router)

作者:rational
鏈接:https://juejin.cn/post/7109815559730462727
來源:稀土掘金
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章