【问题标题】:How to call an api from another api in fastapi?如何从fastapi中的另一个api调用一个api?
【发布时间】:2020-12-08 12:02:42
【问题描述】:

我能够从另一个 API 获得响应,但无法将其存储在某处(在返回响应之前的文件或其他内容中) response=RedirectResponse(url="/apiname/")(我想访问一个带有header和body的post请求)

我想存储这个响应内容而不返回它。

是的,如果我返回函数,我会得到结果,但是当我打印它时,我找不到结果。 另外,如果我发出 post 请求,则会收到错误 Entity not found。

我阅读了 starlette 和 fastapi 文档,但找不到解决方法。回调也没有帮助。

【问题讨论】:

    标签: python python-3.x callback fastapi starlette


    【解决方案1】:

    如果不直接使用 fastapi/starlette 返回,我并没有完全获得存储响应的方法。但我找到了完成此任务的解决方法。

    • 对于尝试实现相同功能的人,请考虑这一点 方式。
    import requests
    
    def test_function(request: Request, path_parameter: path_param):
    
        request_example = {"test" : "in"}
        host = request.client.host
        data_source_id = path_parameter.id
    
        get_test_url= f"http://{host}/test/{id}/"
        get_inp_url = f"http://{host}/test/{id}/inp"
    
        test_get_response = requests.get(get_test_url)
        inp_post_response = requests.post(get_inp_url , json=request_example)
        if inp_post_response .status_code == 200:
            print(json.loads(test_get_response.content.decode('utf-8')))
    

    如果有更好的方法,请告诉我。

    【讨论】:

    【解决方案2】:

    我有同样的问题&我需要用 async 方式调用第三方 API 所以我尝试了很多方法,我用requests-async library解决了 它对我有用。

    import http3
    
    client = http3.AsyncClient()
    
    async def call_api(url: str):
    
        r = await client.get(url)
        return r.text
    
    @app.get("/")
    async def root():
        ...
        result_1 = await call_api('url_1')
        result_2 = await call_api('url_2')
        ...
    

    httpx 你也可以使用 this video他正在使用httpx

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-19
      • 1970-01-01
      • 1970-01-01
      • 2016-12-01
      • 1970-01-01
      • 2017-07-21
      • 2020-09-10
      • 2018-03-15
      相关资源
      最近更新 更多