admin 管理员组

文章数量: 1184232

FASTAPI

#导入库
from fastapi import FastAPI, File, Form, UploadFile
from typing import List  #上传多个文件
import shutil #删除文件夹#实例化
app = FastAPI()
@app.post("/***")  #名字自取,尽量这两个一样
async def ***(files: List[UploadFile] = File(...)): #多个文件上传try:for file in files: # 循环文件list,读取其中每一个文件res = await file.read()  # 读取with open(cache_path+file.filename, "wb") as f:  #读取文件,并写入f.write(res) # 写入...... # 自己需要的代码操作...... # 可以自己调用函数return {"filenname": [(cache_path+file.filename) for file in files]} #返回需要的信息 except Exception as e:  # 捕捉报错信息return {"message Ex": str(e)}finally:  # 不论是否出错,都删除临时文件夹shutil.rmtree(cache_path)
if __name__ == '__main__':import uvicornprint('----------')uvicorn.run(app='aaa:app', host="0.0.0.0", port=8084, reload=True, debug=True)  #aaa是.py文件名字,port本地地址,debug=TRUE可以使用调试# 上传单个文件
app = FastAPI()
@app.post("/***")
async def ***(file: UploadFile = File(...)):try:res = await file.read()with open(cache_path + file.filename, "wb") as f:f.write(res).....  # 同上.....# 返回处理后的图片img_1 = cv2.imread(cache_path_1 + file.filename)  # 先读取图片,或者处理后返回结果就是图片res, img = cv2.imencode(".png", img_1) # 转换cv2.waitKey(0)return StreamingResponse(io.BytesIO(img.tobytes()), media_type="image/png")  # 返回图片except Exception as e:return {"messgae Ex": str(e)}finally:  # 删除文件shutil.rmtree(cache_path)

临时文件夹创建
MD5方法

import timeimport hashlibtime = str(time.time())  # 获取当前时间转换为strdir_x = str(file) + time  # 文件名转换strif isinstance(dir_x, str):# 如果是unicode先转utf-8parmStr = dir_x.encode("utf-8")m = hashlib.md5()m.update(parmStr)dir_s = m.hexdigest()cache_path = "创建文件夹的路径/" + dir_s + "/"os.makedirs(cache_path)

本文标签: FASTAPI