FastAPI快速搭建
1 .uvicorn模块用于启动FastAPI,可以自定义端口,方便快速启动,特别适合pycharm启动。
2.@app.post('/file/')自定义定义访问路径。
3. get_keyword_position() 内是需要输入的参数,包含文件和变量。普通变量建议使用Form(“defaultvalue”)格式,后续本地端容易访问。
4. 需要注释""...""". 内容是解释api怎么用的,网页打开能查看。网址http://127.0.0.1:8082/docs
from fastapi import FastAPI, File, UploadFile, Form
# 主要用于加载和提供应用程序的服务器.
import uvicorn as uvicorn
app = FastAPI()
@app.post('/file/')
async def get_keyword_position(
picturePath: UploadFile = File(...), # UploadFile转为文件对象,可以保存文件到本地
targetWord: str = Form("Main"),
rectArea: str = Form(""),
cv2Threshold:int = Form(88),
cv2Type: int = Form(0)
):
"""
get keyword position info:
- **picturePath**: picture use to identify
- **targetWord**: keyword in picture
- **rectArea**: select rectangle. format: y1:y2,x1:x2,such as 174:1042, 369:1150
- **cv2Threshold**: 二值化阈值,默认88.字体和背景颜色差距不大,就增大。
- **cv2Type**: 二值化操作,默认1. 0:背景白色。 1:背景是深色
"""
# 保存前端上传的文件至本地服务器
# 1 读取上传到的文件
contents = await picturePath.read()
# 2 打开新文件
# 第一个参数 文件存储路径+文件名称,存储路径目录需要提前创建好,如果没有指定,则默认会保存在本文件的同级目录下
# 第二个参数 wb,表示以二进制格式打开文件,用于只写
with open("./file/" + picturePath.filename, "wb") as f:
# 3 将获取的fileb文件内容,写入到新文件中
f.write(contents)
#........
return ({
'file_name': picturePath.filename,
'notes': targetWord,
'file_content_type': picturePath.content_type
})
if __name__ == '__main__':
uvicorn.run(app=app, host="127.0.0.1", port=8082)
网页查看:
本地端测试发送
更多参数自己定义。
import requests
url = "http://127.0.0.1:8082/file/"
files= {'picturePath': open('D:\project\ocr\v2.png', 'rb')}
param={'targetWord':'Main','rectArea':'174:1042, 369:1150'}
res = requests.post(url, files=files,data=param)
print(res)
参考:
https://blog.csdn.net/lilygg/article/details/114927483
https://fastapi.tiangolo.com/zh/tutorial/request-forms-and-files/