FastAPI 用Python:使用FastAPI和requests发送和接收文件

FastAPI 用Python:使用FastAPI和requests发送和接收文件

在本文中,我们将介绍如何使用Python的FastAPI框架和requests库发送和接收文件。FastAPI是一个开源的现代化Web框架,具有高性能和简洁的API设计。requests是一个流行的Python库,用于发送HTTP请求。

阅读更多:FastAPI 教程

准备工作

在开始之前,我们需要确保已经安装了FastAPI和requests库。可以使用以下命令来安装它们:

pip install fastapi
pip install requests

接下来,我们将创建一个FastAPI应用程序,并编写了两个路由函数来演示发送和接收文件的操作。

from fastapi import FastAPI, UploadFile, File

app = FastAPI()

@app.post("/upload")
async def upload_file(file: UploadFile = File(...)):
    contents = await file.read()
    return {"filename": file.filename}

@app.get("/download")
async def download_file():
    url = "http://example.com/file.pdf"
    response = requests.get(url)
    with open("file.pdf", "wb") as file:
        file.write(response.content)
    return {"message": "File downloaded"}

在上面的代码中,我们使用了FastAPI的UploadFileFile模型来定义接收文件的参数类型。UploadFile是FastAPI内置的模型,用于获取上传的文件对象。File用于指定文件的类型。

发送文件

要在FastAPI应用程序中发送文件,我们可以使用UploadFile模型作为路由函数的参数类型,并使用File标记进行声明。在下面的例子中,我们可以演示如何从客户端发送文件到FastAPI服务器。

import requests

def send_file():
    url = "http://localhost:8000/upload"  # 你的FastAPI服务器地址
    file = open("example.txt", "rb")
    response = requests.post(url, files={"file": file})
    print(response.json())

send_file()

在上面的示例中,我们打开了名为example.txt的文件,并使用requests.post方法将文件发送到FastAPI服务器的/upload路由。我们将文件作为files参数的一部分传递。服务器将返回一个带有文件名的JSON响应。

接收文件

要在FastAPI应用程序中接收文件,我们需要使用UploadFile模型作为路由函数的参数类型,并通过调用read()方法来读取文件的内容。在下面的示例中,我们将展示如何从FastAPI服务器接收文件并将其保存到本地文件系统。

import requests

def receive_file():
    url = "http://localhost:8000/download"  # 你的FastAPI服务器地址
    response = requests.get(url)
    with open("downloaded_file.pdf", "wb") as file:
        file.write(response.content)
    print("File downloaded")

receive_file()

在上面的示例中,我们使用requests.get方法从FastAPI服务器的/download路由下载文件。请注意,我们将文件保存为downloaded_file.pdf

总结

在本文中,我们了解了如何使用FastAPI和requests库发送和接收文件。使用FastAPI的UploadFileFile模型,我们可以处理上传的文件。通过调用read()方法和response.content属性,我们可以接收和处理从服务器发送的文件。这些功能使得FastAPI成为处理文件上传和下载的理想选择。

FastAPI和requests库都是功能强大的工具,可以帮助我们构建强大且高效的Web应用程序,快速处理文件传输和其他HTTP请求。通过使用这些库,我们可以更轻松地处理文件的发送和接收,为我们的应用程序增加更多的功能和灵活性。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程