from fastapi import FastAPI, BackgroundTasks
from fastapi.responses import PlainTextResponse
from pydantic import BaseModel
import uvicorn
import sys
import requests
import os
current_path = os.path.abspath(__file__)
project_path = os.path.dirname(os.path.dirname(current_path))
sys.path.append(project_path)
from cv_feature_process.one_run_whole_jpg_emb_similar_minio import get_similar
from cv_feature_process.get_data_minio import client
app = FastAPI()
class InputData(BaseModel):
picPath: str
picId: str
class ExcelPathResponse(BaseModel):
picId: str
status: str
resultPath: str
class ResponseMessage(BaseModel):
result: int
def excel_path_response_to_dict(response):
return {
"picId": response.picId,
"status": response.status,
"resultPath": response.resultPath
}
async def get_similar_excel(data: InputData):
url = 'http:'
try:
csv_path, bucket_name, object_name = get_similar(data.picPath)
object_name = object_name + '.csv'
# 使用 put_object 上传文件
client.fput_object(bucket_name, object_name, csv_path)
# 发起HTTP POST请求到另一个接口
request_param_success = ExcelPathResponse(picId = data.picId, status = "0", resultPath = bucket_name + '/' +object_name)
response = requests.post(url, json=excel_path_response_to_dict(request_param_success))
print(response)
response_data = response.json()
except Exception as e:
request_param_error = ExcelPathResponse(picId = data.picId, status = "1", resultPath = "")
response = requests.post(url, json=excel_path_response_to_dict(request_param_error))
response_data = response.json()
if response_data.get("result") == 0:
print("接收结果成功")
else:
print("接收结果失败")
print(response_data.get("reason"))
@app.post('/image/asynAnalysis', response_model=ResponseMessage, response_model_exclude_unset=True)
async def get_similar_api(data: InputData, background_tasks: BackgroundTasks):
try:
if data.picPath != '' and data.picPath != None:
background_tasks.add_task(get_similar_excel, data) # 执行任务,任务完成后再回调,防止远程服务过长等待
return ResponseMessage(result=0)
else:
return ResponseMessage(result=1)
except Exception as e:
return ResponseMessage(result=1)
if __name__ == '__main__':
uvicorn.run(app, host="192.168.10.11", port=2023)
fastapi案例
于 2024-01-25 17:16:50 首次发布