本文共435个字,预计阅读时间需要2分钟。
FastAPI 是一个高性能 Web 框架,也是一个Python包,用于构建 API,适合利用极少的代码搭建服务器后端,实现前后端分离。
下面给出了一个任务:利用FastAPI搭建文件上传服务器,给出上传接口,并保存到服务器指定位置。
需要使用的Python包:fastapi和uvicorn。
服务器代码
其中with open(file.filename, “wb”)是将客户上传的文件保存起来,上传的url地址为host:port/file_upload,可以自定义端口和host。
注意如果在前端配置的时候出现跨域问题需要添加FastAPI跨域规则。
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)
客户端代码示例
此客户端的需要上传的文件在path中,url即为文件上传的API。
import requests
url = "http://127.0.0.1:8000/file_upload"
path = "C:\\Users\\omegaxyz\\Desktop\\pic.jpeg"
files = {'file': open(path, 'rb')}
r = requests.post(url, files=files)
print(r.url)
print(r.text)
更多内容访问 omegaxyz.com
网站所有代码采用Apache 2.0授权
网站文章采用知识共享许可协议BY-NC-SA4.0授权
© 2020 • OmegaXYZ-版权所有 转载请注明出处
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)