input
output
的文件夹,然后将其转换为JSON并返回给用户。该API将在网站中使用,该网站将来会被许多用户使用。
到目前为止,这是我编写的代码,我知道这不是一个好练习,例如,如果100个用户想同时使用此功能怎么办?AI模型是
main.py
文件中的脚本。
from fastapi import FastAPI, File, UploadFile
import pandas as pd
import csv
import json
IMAGEDIR = "inputs/"
app = FastAPI()
@app.post("/upload_image/")
async def upload_image(img: UploadFile = File(...)):
img.filename = f"new.jpg"
contents = await img.read()
with open(f"{IMAGEDIR}{img.filename}", "wb") as f:
f.write(contents)
result = {}
try:
import main
result = csv_to_json('outputs/Results/Results_1.csv')
return result
except:
raise('Server Error')
result = {'error': 'server error'}
def csv_to_json(csvFilePath):
jsonArray = []
#read csv file
with open(csvFilePath, encoding='utf-8') as csvf:
#load csv file data using csv library's dictionary reader
csvReader = csv.DictReader(csvf)
#convert each csv row into python dict
for row in csvReader:
#add this python dict to json array
jsonArray.append(row)
return jsonArray
解决此问题的正确方法是什么?
您在An and内使用
blocking operations
,这会导致事件循环(由FastApi创建)被阻止并且无法处理更多请求。使用诸如aiofile
之类的库可能会提高性能;尽管我不确定您能得到多少改进,但由于磁盘I/O操作可能是瓶颈。