假设我们有两个最小的 Fast API 端点:
from urllib.parse import urlencode
import httpx
from fastapi import APIRouter
router = APIRouter()
@router.post("/api/endpoint_1")
async def endpoint_1(attributes):
# process the attributes
return attributes
@router.get("/api/endpoint_2")
async def endpoint_2():
# here I need to receive the attributes from POST
attributes = get_attributes_from_somewhere()
url = f"http://some_external_service_url.com/api/{urlencode(attributes, doseq=True)}"
async with httpx.AsyncClient() as client:
response = await client.get(url)
return response.json().get("items")
现在想象一些客户POST
对endpoint_1
一些attributes
. 我需要获取这些属性并在内部使用它们endpoint_2
来向某些外部服务发出一些进一步的请求。然后返回的数据endpoint_2
将由我的前端检索并呈现给用户。
在 Fast API中发送数据endpoint_1
的最佳推荐方式是什么?endpoint_2
我想过以下几点:
将数据保存在某个本地数据库中
endpoint_1
,然后在endpoint_2
. 检索数据后,从数据库中删除属性。这似乎有很多开销只保留一张真正将有一条记录的表。使用一些缓存机制(Redis / Memcached)保存数据,但话又说回来,配置它只是为了保持它似乎也很奇怪。
为了更全面地了解这一点,我在后端使用 Fast API + Python 3.9 来创建 REST 服务,以及httpx
向外部服务发出异步请求的库。另一方面,对于前端,我使用的是 React 和 Typescript。前端只会调用endpoint_2
来显示items
. endpoint_1
只会被某些客户端服务调用。