Skip to content
The Chat Archive
gpt-4o-2024-08-06· OpenAI WildChat-4.8M (AI2)

python代码 requests调用post调用fastapi

  1. User

    python代码 requests调用post调用fastapi

  2. Assistant

    为了使用 requests 库发送 POST 请求以调用 FastAPI 应用程序,你可以按照以下步骤进行操作。以下是一个简单的示例,包括 FastAPI 服务器端代码以及客户端如何使用 requests 发送 POST 请求:

    FastAPI 服务器端代码

    首先,创建一个简单的 FastAPI 应用程序,它能够接收 POST 请求。

    from fastapi import FastAPI
    from pydantic import BaseModel
    
    app = FastAPI()
    
    class Item(BaseModel):
        name: str
        price: float
        is_offer: bool = None
    
    @app.post("/items/")
    async def create_item(item: Item):
        return {"name": item.name, "price": item.price, "is_offer": item.is_offer}
    

    将上面的代码保存为 main.py。

    运行 FastAPI 应用程序时,你需要使用 Uvicorn。可以通过命令行终端运行以下命令:

    uvicorn main:app --reload
    

    这将启动一个在 http://127.0.0.1:8000 上运行的服务器。

    Python 客户端代码

    接下来,使用 requests 库发送 POST 请求到 FastAPI 应用程序。

    import requests
    
    url = "http://127.0.0.1:8000/items/"
    data = {
        "name": "Sample Item",
        "price": 9.99,
        "is_offer": True
    }
    
    response = requests.post(url, json=data)
    
    print("Status Code:", response.status_code)
    print("Response JSON:", response.json())
    

    确保你的 FastAPI 服务器正在运行,然后运行上述客户端代码。这将发送一个 POST 请求到 /items/ 端点,其中包含名称为 "Sample Item" 的商品信息。响应将是服务器返回的 JSON 数据。

    重要的注意事项

    1. 运行服务器:确保在发送请求之前,FastAPI 应用程序服务器正在运行。
    2. 依赖安装:
      • 你需要安装 fastapi 和 uvicorn 来运行 FastAPI 服务器。在终端运行:
        pip install fastapi uvicorn
        
      • 你还需要安装 requests 库来发送 HTTP 请求:
        pip install requests
        
    3. JSON 数据传递:在发送请求时,使用 json=data 而不是 data=data,确保请求体被正确解析为 JSON 格式。

    通过这些步骤,你应该能够成功通过 Python 的 requests 库向 FastAPI 应用程序发送 POST 请求并接收响应。

  3. User

    class Data(BaseModel): file_base64: str file_name: str @router.post("/watermark_add", description="加水印") async def watermark_add(req: Request, data: Data = Body(None, description=""), type: str = Body(None), ):

    如何使用requests库调用上边fastapi url

  4. Assistant

    为了使用 requests 库调用上面的 FastAPI 端点,你需要构造一个 POST 请求,将请求体以 JSON 格式发送。你的 FastAPI 端点需要接受一个包含 file_base64 和 file_name 字段的 JSON 对象,以及一个单独的 type 字段。以下是如何进行这个调用的一个示例:

    FastAPI 端点

    你已经定义了以下端点:

    from fastapi import FastAPI, Request, Body, APIRouter
    from pydantic import BaseModel
    
    app = FastAPI()
    router = APIRouter()
    
    class Data(BaseModel):
        file_base64: str
        file_name: str
    
    @router.post("/watermark_add", description="加水印")
    async def watermark_add(
        req: Request,
        data: Data = Body(None, description=""),
        type: str = Body(None),
    ):
        return {
            "file_base64": data.file_base64,
            "file_name": data.file_name,
            "type": type
        }
    
    app.include_router(router)
    

    使用 requests 发送 POST 请求

    请确保你的 FastAPI 应用正在运行(例如,通过 uvicorn 命令)。下面是使用 requests 库向 /watermark_add 端点发送请求的示例:

    import requests
    import json
    
    # FastAPI 服务器的URL
    url = "http://127.0.0.1:8000/watermark_add"
    
    # 请求体数据
    payload = {
        "data": {
            "file_base64": "your_base64_encoded_file_string",
            "file_name": "example.jpg"
        },
        "type": "your_type_value"
    }
    
    # 发送POST请求
    response = requests.post(url, json=payload)
    
    # 输出返回的状态码和JSON响应
    print("Status Code:", response.status_code)
    print("Response JSON:", response.json())
    

    注意事项

    1. URL:确保 url 变量中指定的 URL 与运行的 FastAPI 服务器的地址和端点路径匹配。

    2. 数据格式:payload 字典中,会包含两个键:data 和 type。data 是一个包含 file_base64 和 file_name 的字典,这是根据 FastAPI 端点的输入参数构造的。

    3. Body结构匹配:在 FastAPI 中,你使用 Body 关键字参数来接受请求体中的数据。当在 requests.post 中设置 json=payload 时,确保你所构造的 payload 字典的结构与 FastAPI 端点期望的请求体结构匹配。

    4. 确保依赖已安装:在Python环境中,使用以下命令安装必要的依赖包:

      pip install requests
      

    通过这些步骤,你应该可以成功地从客户端向 FastAPI 应用程序发送 POST 请求。

  5. User

    如何使用requests 模拟上传文件

  6. Assistant

    使用 requests 库上传文件到服务器可以通过发送一个包含文件数据的 POST 请求来实现。FastAPI 支持文件上传,你可以在请求体中使用 files 参数来上传文件。以下是如何使用 requests 库模拟上传文件的一个示例:

    FastAPI 服务器代码示例

    假设你有一个 FastAPI 服务器,它有一个接受文件上传的端点:

    from fastapi import FastAPI, File, UploadFile
    
    app = FastAPI()
    
    @app.post("/uploadfile/")
    async def create_upload_file(file: UploadFile = File(...)):
        return {"filename": file.filename}
    

    使用 requests 上传文件

    下面是使用 requests 库向上述 FastAPI 端点上传一个文件的示例:

    import requests
    
    # FastAPI服务器的URL
    url = "http://127.0.0.1:8000/uploadfile/"
    
    # 需要上传的文件
    file_path = "path_to_your_file.txt"
    
    # 使用'open'函数以二进制模式读取文件
    with open(file_path, "rb") as file_to_send:
        # 构造文件上传请求,参数以字典的形式传递,键为端点中定义的字段名
        files = {"file": (file_path, file_to_send)}
        
        # 发送POST请求
        response = requests.post(url, files=files)
    
        # 输出返回的状态码和JSON响应
        print("Status Code:", response.status_code)
        print("Response JSON:", response.json())
    

    注意事项

    1. FastAPI端点设置:确保你的 FastAPI 应用程序正确地处理文件上传,如上面的 UploadFile 示例中所示。

    2. URL地址:在 url 变量中指定的 URL 必须匹配你的 FastAPI 服务器中相应的文件上传端点。

    3. 文件处理:

      • files 参数是一个字典,键为服务器端接收文件的参数名,值为一个包含文件名和文件对象的元组。
      • 文件通过 open(file_path, "rb") 以二进制模式打开,然后传入 requests.post 的 files 参数。
    4. 依赖安装:确保已经安装 requests 库。可以通过以下命令进行安装:

      pip install requests
      

    通过这些步骤,你可以成功地使用 requests 库模拟上传文件到 FastAPI 服务器或者其他支持文件上传的 HTTP 服务器。

  7. User

    可以又传递body的json参数又包含UploadFile?

  8. Assistant

    在使用 requests 库向 FastAPI 端点发送请求时,可以同时传递 JSON 参数和上传文件。这通常通过将 JSON 数据放在 data 或 json 参数中,同时将文件放在 files 参数中进行实现。在服务器端你需要以适当的方式解析这些数据。

    FastAPI 服务器代码示例

    假设你有一个 FastAPI 端点,可以处理 JSON 数据和文件上传:

    from fastapi import FastAPI, File, UploadFile, Form
    from pydantic import BaseModel
    from typing import Optional
    
    app = FastAPI()
    
    class Item(BaseModel):
        description: str
        type: Optional[str] = None
    
    @app.post("/uploadfile/")
    async def create_upload_file(
        file: UploadFile = File(...),
        description: str = Form(...),
        type: str = Form(None)
    ):
        return {"filename": file.filename, "description": description, "type": type}
    

    注意,为了同时上传文件和接收其他表单数据,你需要使用 Form 来捕获额外的字符数据。

    使用 requests 上传文件和 JSON

    下面是如何使用 requests 库来向上述 FastAPI 端点同时发送文件和 JSON 数据:

    import requests
    
    # FastAPI服务器的URL
    url = "http://127.0.0.1:8000/uploadfile/"
    
    # 需要上传的文件
    file_path = "path_to_your_file.txt"
    
    # 其他表单数据
    data = {
        "description": "This is a test file",
        "type": "example_type"
    }
    
    # 使用'open'函数以二进制模式读取文件
    with open(file_path, "rb") as file_to_send:
        # 构造文件上传请求,参数以字典的形式传递,键为端点中定义的字段名
        files = {"file": (file_path, file_to_send)}
        
        # 发送POST请求
        response = requests.post(url, data=data, files=files)
    
        # 输出返回的状态码和JSON响应
        print("Status Code:", response.status_code)
        print("Response JSON:", response.json())
    

    关键点说明

    1. Form 数据:FastAPI 默认情况下将 Form 数据与文件上传数据混合在一个请求中,因此需要用 Form 来处理非文件的表单数据,而不是 Body。

    2. 请求构造:

      • data 用于传递非文件表单字段。
      • files 用于以字典形式上传文件,其中字典的键是接收文件的参数名,值是包含文件名和文件对象的元组。
    3. 服务器解析:

      • 在 FastAPI 中,使用 File 和 Form 来处理文件和其他表单数据。这可以实现同时处理文件和普通表单数据的功能。

    通过上面的步骤和注意事项,你可以成功地向 FastAPI 服务器发送包含文件和 JSON 数据的 POST 请求。