2024-09-01
Python
00

目录

FastAPI 服务
requests 测试
requests 单一文件上传
requests 多个文件上传

FastAPI 服务

下面是代码,

@app.post("/files/") 路由让我们可以传文件。

@app.post("/uploadfiles/")路由让我们可以传多个文件。

需要保证:

(1) uvicorn.run中写的是文件名:app名,确保自己的文件名。

(2)# python 3.8 pip install fastapi uvicorn python-multipart

python
# -*- coding:utf-8 -*- import traceback from typing import List, Optional, Union import uvicorn from fastapi.middleware.cors import CORSMiddleware from fastapi import FastAPI, File, Form, UploadFile import cv2 import numpy as np app = FastAPI( title='FastAPI Tutorial', description='FastAPI教程', version='1.0.0', docs_url='/docs', redoc_url='/redocs', ) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.post("/files/") async def alg_file( fileb: UploadFile = File(...), token: str = Form(...) ): try: img = cv2.imdecode(np.fromstring(fileb.file.read(), np.uint8), cv2.IMREAD_COLOR) return { "token": token, "filename": fileb.filename, "content_type": fileb.content_type, "size": img.shape } except: traceback.print_exc() return -1 @app.post("/uploadfiles/") async def create_upload_files(files: List[UploadFile] = File(...)): return {"filenames": [file.filename for file in files]} @app.post("/filesper/") def filesper( file: Optional[bytes] = File(None), fileb: Optional[UploadFile] = File(None), filepath: Optional[str] = Form(None), ): try: if file: img = cv2.imdecode(np.frombuffer(file, dtype=np.uint8), cv2.IMREAD_COLOR) return { "size": img.shape, "style": "bytes" } if fileb: img = cv2.imdecode(np.fromstring(fileb.file.read(), np.uint8), cv2.IMREAD_COLOR) return { "filename": fileb.filename, "content_type": fileb.content_type, "size": img.shape, "style": "UploadFile" } if filepath: return { "str": filepath, "style": "str" } except: traceback.print_exc() return -1 if __name__ == '__main__': uvicorn.run('yolo5fastapi:app', host='0.0.0.0', port=8001, reload=False, debug=False, workers=1)

requests 测试

requests 单一文件上传

测试上传一个图片文件:

python
import requests url = "http://0.0.0.0:8001/files/" with open("/home/kevin_xie/yifeinfs/pycharm_k/yolov5_v2/kevin/picture/realcamera.jpg", "rb") as f: res = requests.post(url=url, data={"token": "sdas"}, files={"fileb": f}, timeout=None) print(res.json())

返回:

python
{'token': 'sdas', 'filename': 'realcamera.jpg', 'content_type': '', 'size': [720, 1280, 3]}

requests 多个文件上传

注意给文件参数的方式,元组和列表均可,可自由尝试。

python
import requests url = "http://0.0.0.0:8001/uploadfiles/" with open("/home/kevin_xie/yifeinfs/pycharm_k/yolov5_v2/kevin/picture/realcamera.jpg", "rb") as f: res = requests.post(url=url, files=[("files", f), ("files", f), ("files", f)], timeout=None) print(res.json())
如果对你有用的话,可以打赏哦
打赏
ali pay
wechat pay

本文作者:Dong

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC。本作品采用《知识共享署名-非商业性使用 4.0 国际许可协议》进行许可。您可以在非商业用途下自由转载和修改,但必须注明出处并提供原作者链接。 许可协议。转载请注明出处!