Fastapi和requests文件的下载和上传

 介绍

FastApi搭建一个简单下载和上传的服务,通过接口将文件保存在服务器上,而通过requests库子在本机中批量从服务器上传和下载文件

FastApi搭建服务

# application.py
"""
fastapi + request 上传和下载功能
"""
from fastapi import FastAPI, UploadFile
from fastapi.responses import FileResponse
import uvicorn

app = FastAPI()


@app.post("/upload", summary="上传接口")
async def upload(file: UploadFile):
    filename = file.filename
    file_size = file.size
    # 保存到服务器指定目录
    with open(filename, "wb") as f:
        for chunk in iter(lambda: file.file.read(1024), b''):
            f.write(chunk)
    print(f"文件:{filename}上传成功,大小{file_size/1024/10224}")
    return {"message": "ok"}


@app.get("/download")
async def read_file(filename: str):
    # 需要下载文件名,从服务器保存文件地址拼接
    print(filename)
    file_path = "1.txt"
    return FileResponse(file_path, filename=filename, media_type="application/octet-stream")


if __name__ == '__main__':
    uvicorn.run("application:app", port=9000)

reqeusts批量下载上传

# test.pt

import requests
import os


def upload_file(file_path):
    url = "http://127.0.0.1:9000/upload"

    with open(file_path, 'rb') as f:
        contents = f.read()

        response = requests.post(url, files={"file": (os.path.basename(file_path), contents, 'multipart/form-data')})
    return response.json()


def download_file1(file_name):
    """方式1,将整个文件下载在保存到本地"""
    url = "http://127.0.0.1:9000/download"
    response = requests.get(url, params={"filename": "1.txt"})
    print(response.text)


def download_file2(file_name):
    """方式2,通过流的方式一次写入8192字节"""
    url = "http://127.0.0.1:9000/download"
    response = requests.get(url, params={"filename": "1.txt"}, stream=True)
    with open(file_name, 'wb') as file:
        for chunk in response.iter_content(chunk_size=8192):
            file.write(chunk)


if __name__ == '__main__':
    upload_file(r"1.txt")

测试

启动fastapi服务

python application.py 

测试下载和上传的功能

python test.py 

服务响应成功,问价也能正常的下载和上传。

  • 12
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
文本格式不能很好显示,请见谅(附件里有比较齐整的excel表格统计) 大小类型 传输类型 api方法 文件大小 花费时间 速率byte/ms 速率mb/s 缓存数组 次数 备注 大文件 下载 download_file(group_name, remote_filename, localFile) 1073741824(约1G) 28343ms 37883 36.12804413 无 1 下载 download_file(group_name, remote_filename , downloadStream) 1073741824(约1G) 29195ms 36778 35.07423401 0 1 fastDFS的DownloadStream,FileOutputStream 下载 download_file(group_name, remote_filename , downloadStream) 1073741824(约1G) 24352ms 44092 42.04940796 2K 1 fastDFS的DowloadStream,BufferedOutputStream 下载 download_file(group_name, remote_filename , DownloadCallback) 1073741824(约1G) 24831ms 43241 41.23783112 2K 1 实现DownloadCallback,BufferedOutputStream 下载 download_file(group_name, remote_filename , DownloadCallback) 1073741824(约1G) 25922ms 41422 39.50309753 8K 1 实现DownloadCallback,BufferedOutputStream 普通文件 下载 download_file(group_name, remote_filename, localFile) 59113472(约56M) 382ms 154747 147.5782394 无 1 下载 download_file(group_name, remote_filename , downloadStream) 59113472(约57M) 369ms 160199 152.7776718 0 1 fastDFS的DownloadStream,FileOutputStream 下载 download_file(group_name, remote_filename , downloadStream) 59113472(约58M) 499ms 118702 113.2030487 2K 1 fastDFS的DowloadStream,BufferedOutputStream 下载 download_file(group_name, remote_filename , DownloadCallback) 59113472(约59M) 592ms 99853 95.22724152 2K 1 实现DownloadCallback,BufferedOutputStream 下载建议:100M内数据使用fastDFS提供的DownloadStream;大于1G的数据,使用BufferedOutputStream和DowloadStream
`requests.receive()` is a method in FastAPI's WebSocket class. It is used to receive incoming messages from the client in real time. When a WebSocket connection is established between the client and the server, the client can send messages to the server at any time. To receive these messages, the server can call the `requests.receive()` method. This method blocks until a message is received from the client. Here is an example of using `requests.receive()` in a FastAPI WebSocket endpoint: ```python from fastapi import FastAPI, WebSocket app = FastAPI() class ConnectionManager: def __init__(self): self.active_connections = [] async def connect(self, websocket: WebSocket): await websocket.accept() self.active_connections.append(websocket) def disconnect(self, websocket: WebSocket): self.active_connections.remove(websocket) async def broadcast(self, message: str): for connection in self.active_connections: await connection.send_text(message) manager = ConnectionManager() @app.websocket("/ws") async def websocket_endpoint(websocket: WebSocket): await manager.connect(websocket) try: while True: message = await websocket.receive_text() await manager.broadcast(message) except WebSocketDisconnect: manager.disconnect(websocket) await manager.broadcast(f"Client #{websocket} left the chat") ``` In this example, the `requests.receive()` method is used in a loop to continuously receive messages from the client. The `WebSocketDisconnect` exception is caught to gracefully handle disconnection from the client.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

平时不搬砖

创造不易,请动动你发财的小手

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值