准备工作:
1、安装uvicorn,利用其来作为web服务器
2、安装Starlette,利用其来作为web开发框架
3、安装python-multipart,让其支持form表达形式的文件上传
4、postman:文件上传的发起者,这样我们就不用写前端界面了
代码:
python
import uvicorn
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.datastructures import UploadFile
from starlette.routing import Route
import asyncio
async def semanticTextualDeduplication(request):
lineSize = 0
try:
form: UploadFile = await request.form()
file = form["file"]
contents = await file.read()
content_str = contents.decode('utf-8')
lines = content_str.splitlines()
lineSize = len(lines)
for line in lines:
print(line.strip())
except Exception as e:
# 处理其他异常
print("发生了异常:", e)
return JSONResponse({"lineSize": lineSize})
app = Starlette(
routes=[
Route("/api/semanticTextualDeduplication.do", semanticTextualDeduplication, methods=["POST"]),
],
)
@app.on_event("startup")
async def startup_event():
q = asyncio.Queue()
app.model_queue = q
if __name__ == "__main__":
uvicorn.run("message_receive:app", host="0.0.0.0", port=8080, access_log=False)
测试:
1、打开postman:
1.1、注意第一个文件参数,需要在输入key以后选择 key的类型为file
2、结果: