首页 > 其他分享 >simpread-(127 条消息) FastAPI 图片上传接口_waketzheng 的博客 - CSDN 博客_fastapi 上传接口

simpread-(127 条消息) FastAPI 图片上传接口_waketzheng 的博客 - CSDN 博客_fastapi 上传接口

时间:2022-11-10 14:14:10浏览次数:78  
标签:name fastapi 博客 host 接口 file import 上传

本文由 简悦 SimpRead 转码, 原文地址 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"

标签:name,fastapi,博客,host,接口,file,import,上传
From: https://www.cnblogs.com/zhuoss/p/16876834.html

相关文章