Skip to content

Commit

Permalink
add file upload for fastapi
Browse files Browse the repository at this point in the history
  • Loading branch information
BuxianChen committed Mar 14, 2024
1 parent b647763 commit e0ca3c5
Showing 1 changed file with 34 additions and 4 deletions.
38 changes: 34 additions & 4 deletions _drafts/2024-02-18-pydantic.md
Original file line number Diff line number Diff line change
Expand Up @@ -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://<host>:<port>/items/a/b/?q=asd
# p 是路径参数 (path parameter), q 是查询参数 (query parameter)
# {"p": 123, "q": "asd"}, 注意这里限制了 p 是整数, 因此会自动进行校验并转换
Expand All @@ -312,11 +316,37 @@ 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)
```

```python
# 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"})
```

0 comments on commit e0ca3c5

Please sign in to comment.