亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

帶有 aiocache 和 Redis 的 FastAPI 無法設置 databases.

帶有 aiocache 和 Redis 的 FastAPI 無法設置 databases.

繁花如伊 2023-05-23 15:28:42
我正在嘗試使用 aiocache 庫在我的端點上實施 Redis。我對 aiocache 進行的第一個測試我使用了@cache,但沒有指示任何其他服務并且一切正常。但是當我嘗試使用 Redis 時,我看到了這個錯誤(端點仍然返回請求)ERROR:    Couldn't set [<databases.backends.postgres.Record object at 0x7fb9f01d86a0>, <databases.backends.postgres.Record object at 0x7fb9f01d88b0>, <databases.backends.postgres.Record object at 0x7fb9f01d8a60>] in key app.api.authorget_authors()[], unexpected errorTraceback (most recent call last):  File "/usr/local/lib/python3.8/site-packages/aiocache/decorators.py", line 144, in set_in_cache    await self.cache.set(key, value, ttl=self.ttl)  File "/usr/local/lib/python3.8/site-packages/aiocache/base.py", line 61, in _enabled    return await func(*args, **kwargs)  File "/usr/local/lib/python3.8/site-packages/aiocache/base.py", line 45, in _timeout    return await asyncio.wait_for(func(self, *args, **kwargs), timeout)  File "/usr/local/lib/python3.8/asyncio/tasks.py", line 483, in wait_for    return fut.result()  File "/us/local/lib/python3.8/site-packages/aiocache/base.py", line 75, in _plugins    ret = await func(self, *args, **kwargs)  File "/usr/local/lib/python3.8/site-packages/aiocache/base.py", line 265, in set    ns_key, dumps(value), ttl=self._get_ttl(ttl), _cas_token=_cas_token, _conn=_conn  File "/usr/local/lib/python3.8/site-packages/aiocache/serializers/serializers.py", line 140, in dumps    return json.dumps(value)TypeError: <databases.backends.postgres.Record object at 0x7fb9f01d8a60> is not JSON serializable整個環境基于docker,2個容器,1個FastApi,1個PostgreSQL和1個Redis。很明顯端點返回的對象有問題,所以我問你如何將這么復雜的對象傳遞給Redis?按照 aiochace 文檔,我嘗試了所有存在的序列化程序,但沒有成功。
查看完整描述

2 回答

?
回首憶惘然

TA貢獻1847條經驗 獲得超11個贊

錯誤說明了一切

TypeError:?<databases.backends.postgres.Record?object?at?0x7fb9f01d8a60>?is?not?JSON?serializable

錯誤在于您正在序列化 JSON 中的對象以緩存它,而這在 JSON 中是不可序列化的。

我曾經遇到過類似的問題,但是發現fastAPI的編碼器支持該Record對象,而其他的則不支持。您可以返回通過此類編碼器序列化的對象,也可以在 redis 緩存參數中將其設置為編碼器。

我沒有測試以下代碼,但它應該足以說明我的意思。

from fastapi.encoders import jsonable_encoder


@authors.get("/", response_model=List[AuthorOut])? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??

@cached(? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??

? ? ?ttl=100,? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??

? ? ?cache=Cache.REDIS,

? ? ?endpoint="X.X.X.X", #my local ip

? ? ?serializer=JsonSerializer(),

? ? ?port=6379,

? ? ?namespace="main",

? ? ?#key="key",

?)

async def get_authors():

? ?return jsonable_encoder(await db_manager.get_all_authors())


查看完整回答
反對 回復 2023-05-23
?
斯蒂芬大帝

TA貢獻1827條經驗 獲得超8個贊

您可以使用 redis_cache 來訪問 RedisDB


connection.py


from typing import Optional


from aioredis import Redis, create_redis_pool


#Create a RedisCache instance

class RedisCache:

    

    def __init__(self):

        self.redis_cache: Optional[Redis] = None

        

    async def init_cache(self):

        self.redis_cache = await create_redis_pool("redis://localhost:6379/0?encoding=utf-8") #Connecting to database


    async def keys(self, pattern):

        return await self.redis_cache.keys(pattern)


    async def set(self, key, value):

        return await self.redis_cache.set(key, value)

    

    async def get(self, key):

        return await self.redis_cache.get(key)


    

    async def close(self):

        self.redis_cache.close()

        await self.redis_cache.wait_closed()



redis_cache = RedisCache()

main.py


from fastapi import FastAPI, applications

from uvicorn import run

from fastapi import FastAPI, Request, Response

from connection import redis_cache




app = FastAPI(title="FastAPI with Redis")



async def get_all():

    return await redis_cache.keys('*')



@app.on_event('startup')

async def starup_event():

    await redis_cache.init_cache()



@app.on_event('shutdown')

async def shutdown_event():

    redis_cache.close()

    await redis_cache.wait_closed()


#root

@app.get("/")

def read_root():

    return {"Redis": "FastAPI"}


#root > Get all keys from the redis DB

@app.get('/RedisKeys')

async def redis_keys():

    return await get_all()


if __name__ == '__main__':

    run("main:app", port=3000, reload=True)

我正在使用 uvicorn 訪問:


uvicorn main:app --reload


查看完整回答
反對 回復 2023-05-23
  • 2 回答
  • 0 關注
  • 350 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號