繁体   English   中英

FastApi 与其他 Api 通信

[英]FastApi communication with other Api

我最近正在使用 fastapi,作为练习,我想将我的 fastapi api 与其他服务器上的验证服务连接起来......但我不知道该怎么做,我还没有在官方文档中找到对我有帮助的东西.. 我必须使用 python 代码吗? 或者有什么办法吗?

FastApi 文档

谢谢你的帮助,原谅我的英语。

您需要使用 Python 对其进行编码。

如果您使用异步,则应使用也是异步的 HTTP 客户端,例如aiohttp

import aiohttp

@app.get("/")
async def slow_route():
    async with aiohttp.ClientSession() as session:
        async with session.get("http://validation_service.com") as resp:
            data = await resp.text()
            # do something with data

接受的答案当然有效,但它不是一个有效的解决方案。 每次请求时, ClientSession都会关闭,因此我们失去了ClientSession的优势 [0]:连接池、keepalives 等。

我们可以使用 FastAPI 中的startupshutdown事件 [1],分别在服务器启动和关闭时触发。 在这些事件中,可以创建一个ClientSession实例并在整个应用程序的运行时使用它(从而充分利用其潜力)。

ClientSession实例存储在应用程序 state 中。 [2]

在这里,我在 aiohttp 服务器的上下文中回答了一个非常相似的问题: https://stackoverflow.com/a/60850857/752142

from __future__ import annotations

import asyncio
from typing import Final

from aiohttp import ClientSession
from fastapi import Depends, FastAPI
from starlette.requests import Request

app: Final = FastAPI()


@app.on_event("startup")
async def startup_event():
    setattr(app.state, "client_session", ClientSession(raise_for_status=True))


@app.on_event("shutdown")
async def shutdown_event():
    await asyncio.wait((app.state.client_session.close()), timeout=5.0)


def client_session_dep(request: Request) -> ClientSession:
    return request.app.state.client_session


@app.get("/")
async def root(
    client_session: ClientSession = Depends(client_session_dep),
) -> str:
    async with client_session.get(
        "https://example.com/", raise_for_status=True
    ) as the_response:
        return await the_response.text()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM