From e0ca3c57075f7bea83dd8a528acf4203c61bc073 Mon Sep 17 00:00:00 2001 From: BuxianChen <541205605@qq.com> Date: Thu, 14 Mar 2024 18:54:23 +0800 Subject: [PATCH] add file upload for fastapi --- _drafts/2024-02-18-pydantic.md | 38 ++++++++++++++++++++++++++++++---- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/_drafts/2024-02-18-pydantic.md b/_drafts/2024-02-18-pydantic.md index fd57547..76dfe6e 100644 --- a/_drafts/2024-02-18-pydantic.md +++ b/_drafts/2024-02-18-pydantic.md @@ -293,13 +293,17 @@ print(mod.code) ```python # server.py -from typing import Union, Annotated -from fastapi import FastAPI, Query, Path -import uvicorn -from pydantic import BaseModel, Field +from fastapi import FastAPI +from fastapi import File, UploadFile # +from fastapi import Form # 表单 +from fastapi import Path, Query, Body # 分别对应 HTTP 协议的路径, 请求参数, 请求体 +from pydantic import Field +from typing import List, Annotated, Union app = FastAPI() + +# 1. path parameter and query parameter # http://:/items/a/b/?q=asd # p 是路径参数 (path parameter), q 是查询参数 (query parameter) # {"p": 123, "q": "asd"}, 注意这里限制了 p 是整数, 因此会自动进行校验并转换 @@ -312,6 +316,30 @@ async def read_items( "p": p, "desc": desc, } + +# 2.1 单文件上传 +@app.post("/upload/") +async def create_upload_file( + file: UploadFile = File(...), + a: str = Form(...), +): + name = file.filename + file_content = await file.read() + sha256_hash = hashlib.sha256(file_content).hexdigest() + return {"hash": sha256_hash, "name": name} + +# 2. 多文件上传 +@app.post("/uploads/") +async def create_upload_file( + file: List[UploadFile] = File(...), + a: str = Form(...), +): + file = file[0] + name = file.filename + file_content = await file.read() + sha256_hash = hashlib.sha256(file_content).hexdigest() + return {"hash": sha256_hash, "name": name} + uvicorn.run(app, host="127.0.0.1", port=8000) ``` @@ -319,4 +347,6 @@ uvicorn.run(app, host="127.0.0.1", port=8000) # client.py import requests requests.get("http://localhost/items/123?desc=hello") +requests.post("http://localhost/upload/", files=[('file', open(filename, 'rb'))], data={"a": "abc"}) +requests.post("http://localhost/uploads/", files=[('file', open(filename, 'rb'))], data={"a": "abc"}) ``` \ No newline at end of file