4 篇文章带有标签 “File”

FastAPI : Request File and Form(BaseModel)

from pydantic import BaseModel, Json, ValidationError
from fastapi import APIRouter, File, UploadFile, HTTPException, Form, Depends

class Box(BaseModel):
    x: int
    y: int
    w: int
    h: int

router = APIRouter()

@router.post("/test")
async def test(file: UploadFile = File(...), 
               mask: Json = Form(default=None), 
               n: int = Form(default=0)) -> str:
// ...

使用 wrk 对 FastAPI 上传和下载文件的基准测试

服务器 CPU 40核,内存 256G,操作系统 Ubuntu 20.04,Python3.9

wrk 的 lua 脚本:postfile_formdata.lua

wrk.method = "POST"
local f = io.open("postdata", "rb")
wrk.body   = f:read("*all")
wrk.headers["Content-Type"] = "multipart/form-data; boundary=gouchicao0123456789"

wrk 的 lua 脚本:postfile_json.lua

wrk.method = "POST"
local f = io.open("postdata.json", "rb")
wrk.body   = f:read("*all")
wrk.headers["Content-Type"] = "application/json"

/file_benchmarking/upload/binary/chunk/async_func/async_rw wrk -c100

FastAPI 上传和下载文件的基准测试

使用 FastAPI 实现了文件的上传和下载,部署服务使用了 uvicorn 和 gunicorn+uvicorn 两种方法。

基准测试工具使用的是 wrk

服务器 CPU 40核,内存 256G,操作系统 Ubuntu 20.04,Python3.9

stream 异步读取上传的文件,同步写入 tempfile.NamedTemporaryFile() 生成的文件。 http://172.16.33.159:8000/files/upload/stream/async_read_and_memory_write stream 异步读取上传的文件,同步写入磁盘文件。 http://172.16.33.159:8000/files/upload/stream/async_read_and_disk_write stream 异步读取上传的文件,异步写入磁盘文件。 http://172.16.33.159:8000/files/upload/stream/async_read_and_async_write 异步全量读取上传的文件,异步写入磁盘文件。 http://172.16.33.159:8000/files/upload/single 异步全量读取上传的文件,异步写入磁盘文件。(API 函数定义时没有使用 async) http://172.16.33.

Python文件、目录、路径操作

  • 方法2
def touch(path):
    with open(path, 'a'):
        os.utime(path, None)
  • 方法3

OS X需要root特权

os.mknod(filename)
  • 多级目录
>>> os.makedirs('dirs/sub_dir')
  • 列出文件和目录
>>> os.listdir('/home/python')
['app', 'config', 'main.py', 'test']
  • 多级目录
>>> shutil.rmtree('/home/python')