如何修复从另一个应用程序调用本地应用程序时 FastAPI 中的“连接被拒绝”错误?

问题描述 投票:0回答:1

我有两个 FastAPI 应用程序在我的本地主机上运行。 假设 A 和 B 应用程序。

答:

uvicorn A:api --reload --port 8081

from fastapi import FastAPI
from pydantic import BaseMode


api = FastAPI()

class Data(BaseModel):
    name: str
    result: str

@api.post('/write')
def write(data: Data):
    # ... some logic
    return {'status': "OK"}

B:

uvicorn B:api --reload --port 8080

from fastapi import FastAPI, BackgroundTasks
import requests


api = FastAPI()

def process(callback:str):
    req_body = {
        "name": "name",
        "result": "result"
    }
    response = requests.post(
        url=callback, 
        json=req_body 
    )
    # response = httpx.post(url=callback, 
    #                       json=req_body)
    
@api.post('/process')
def processing(
    background_tasks: BackgroundTasks,
    callback: str,
    ):
    background_tasks.add_task(process, callback)
    return {'status': "OK"}

逻辑如下:我可以通过指定应用程序 B 完成任务时将调用的回调 URL 来调用应用程序 B。回调 URL 是应用程序 A 'http://127.0.0.1:8001/write' 的端点。 当我从任何客户端向应用程序 B 发出请求时,我收到应用程序 B 无法与应用程序 A 建立连接的错误。

requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=8001): 
Max retries exceeded with url: /write
(Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f9e3dd60490>: Failed to establish a new connection: [Errno 111] Connection refused'))

我尝试过使用内置的快速api客户端和postman来调用应用程序B: 顺便说一句,我可以单独调用应用程序 A,它工作得很好。

我真的不知道问题出在哪里,我很困惑。

python-requests network-programming fastapi
1个回答
0
投票

我也遇到同样的问题,不知道为什么 我也尝试过运行相同的调用(服务器 B 中的链接到服务器 A) 它工作正常,但是当在端点内时,我收到此错误

© www.soinside.com 2019 - 2024. All rights reserved.