Python
pythonimport base64
import os
import time
import traceback
import cv2
from multiprocessing import Manager, Process
import uvicorn
from fastapi.middleware.cors import CORSMiddleware
from fastapi import FastAPI, File, Form, UploadFile
import requests
model_config = {
"process_N": 1,
"port": 8099,
"FastAPIWorks": 1 # must be number 1
}
app = FastAPI(
title='FastAPI',
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=["*"],
)
updatelabel = 1
def get_db():
global updatelabel
updatelabel += 1
table = "i am table" + str(updatelabel)
return {"updatelabel": updatelabel, "table": table}
camera_info = Manager().list()
camera_info.append(get_db())
@app.get("/emq/")
def alg_analyse_bytes(a: int):
if a == 1:
camera_info[0] = get_db()
return "ok"
@app.post("/init_process/")
def init_process(process_num: int = Form(...), passwd: str = Form(...)):
if passwd == "woshimima":
if process_num <= 8:
for i in range(process_num):
Process(target=deal_picture, args=(camera_info,)).start()
return 1
def deal_picture(camera_info):
camera_info_copy = dict(camera_info[0]).copy()
while True:
try:
if camera_info_copy["updatelabel"] != camera_info[0]["updatelabel"]:
camera_info_copy = dict(camera_info[0]).copy()
print(camera_info_copy)
except:
traceback.print_exc()
def cv2_to_base64(image):
base64_str = cv2.imencode('.jpg', image)[1].tostring()
base64_str = base64.b64encode(base64_str)
return base64_str
def init_model():
time.sleep(1)
requests.post("http://0.0.0.0:" + str(model_config["port"]) + "/init_process",
data={"process_num": model_config["process_N"],
"passwd": "woshimima"})
print(f"algorithm already start ")
if __name__ == '__main__':
modulename = os.path.basename(os.path.abspath(__file__)).split(".")[0]
Process(target=init_model).start()
uvicorn.run(modulename + ':app',
host='0.0.0.0',
port=model_config["port"],
reload=False,
debug=False,
workers=model_config["FastAPIWorks"])
本文作者:Dong
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC。本作品采用《知识共享署名-非商业性使用 4.0 国际许可协议》进行许可。您可以在非商业用途下自由转载和修改,但必须注明出处并提供原作者链接。 许可协议。转载请注明出处!