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 uvicornapp = 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 requestsurl = "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/