怪奇物语

怪奇物语

首页 新随笔 联系 管理

原文地址 blog.csdn.net

需求:上传一个图片,保存到服务器,然后返回一个 URL

设置静态资源文件夹

image-20221108190951383

# main.py
#!/usr/bin/env python3.8
import hashlib
from aiopathlib import AsyncPath  # pip install aiopathlib
from pathlib import Path
from fastapi import Request, File, FastAPI
from fastapi.staticfiles import StaticFiles

BASE_DIR = Path(__file__).resolve().parent
LIMIT_SIZE = 5 * 1024 * 1024  # 5M
MEDIA_ROOT = BASE_DIR / 'media'
if not MEDIA_ROOT.exists():
	MEDIA_ROOT.mkdir()
app = FastAPI()
app.mount("/media", StaticFiles(directory=MEDIA_ROOT.name), )

def get_host(req) -> str:
    return getattr(req, "headers", {}).get("host") or "http://127.0.0.1:8000"

@app.post("/put-cert")
async def put_cert(request: Request, file: bytes = File(...)):
    """单文件上传(不能大于5M)"""
    if len(file) > LIMIT_SIZE:
        raise HTTPException(status_code=400, detail="每个文件都不能大于5M")
        
    name = hashlib.md5(file).hexdigest() + ".png"  # 使用md5作为文件名,以免同一个文件多次写入
    subpath = "media/uploads"
    
    if not (folder := BASE_DIR / subpath).exists():
        await AsyncPath(folder).mkdir(parents=True)
    if not (fpath := folder / name).exists():
        await AsyncPath(fpath).write_bytes(file)
    host = get_host(request)
    return f"{host}/{subpath}/{name}"

使用:

# pip install aiopathlib fastapi uvicorn python-multipart
uvicorn main:app

请求示例:

curl localhost:8000/put-cert -F "file=@/path/to/file"
posted on 2022-11-10 14:01  超级无敌美少男战士  阅读(662)  评论(0)    收藏  举报