FastAPI 是一个高性能 Web 框架,也是一个Python包,用于构建 API,适合利用极少的代码搭建服务器后端,实现前后端分离。
下面给出了一个任务:利用FastAPI搭建文件上传服务器,给出上传接口,并保存到服务器指定位置。
需要使用的Python包:fastapi和uvicorn。
服务器代码
其中with open(file.filename, “wb”)是将客户上传的文件保存起来,上传的url地址为host:port/file_upload,可以自定义端口和host。
注意如果在前端配置的时候出现跨域问题需要添加FastAPI跨域规则。
Python
import time
import uvicorn
from fastapi import FastAPI, File, UploadFile
app = FastAPI()
@app.post("/file_upload")
async def file_upload(file: UploadFile = File(...)):
start = time.time()
try:
res = await file.read()
with open(file.filename, "wb") as f:
f.write(res)
return {"message": "success", 'time': time.time() - start, 'filename': file.filename}
except Exception as e:
return {"message": str(e), 'time': time.time() - start, 'filename': file.filename}
if __name__ == '__main__':
uvicorn.run(app=app, host="127.0.0.1", port=8000, workers=1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
importtime
importuvicorn
fromfastapiimportFastAPI,File,UploadFile
app=FastAPI()
@app.post("/file_upload")
asyncdeffile_upload(file:UploadFile=File(...)):
start=time.time()
try:
res=awaitfile.read()
withopen(file.filename,"wb")asf:
f.write(res)
return{"message":"success",'time':time.time()-start,'filename':file.filename}
exceptExceptionase:
return{"message":str(e),'time':time.time()-start,'filename':file.filename}
if__name__=='__main__':
uvicorn.run(app=app,host="127.0.0.1",port=8000,workers=1)
客户端代码示例
此客户端的需要上传的文件在path中,url即为文件上传的API。
Python
import requests
url = "http://127.0.0.1:8000/file_upload"
path = "C:\\Users\\me\\Desktop\\pic.jpeg"
files = {'file': open(path, 'rb')}
r = requests.post(url, files=files)
print(r.url)
print(r.text)
1
2
3
4
5
6
7
importrequests
url="http://127.0.0.1:8000/file_upload"
path="C:\\Users\\me\\Desktop\\pic.jpeg"
files={'file':open(path,'rb')}
r=requests.post(url,files=files)
print(r.url)
print(r.text)
PS:除了Python客户端外,还可以采用在JS中编写post请求(服务器端代码无需修改),实现在浏览器中上传文件到服务器。