利用Python开发一个上传文件的服务

准备工作:

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、结果:

相关推荐
金銀銅鐵4 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup119 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi0011 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵13 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf14 小时前
Agent 流程编排
后端·python·agent
copyer_xyf14 小时前
Agent RAG
后端·python·agent
copyer_xyf14 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf15 小时前
Agent 记忆管理
后端·python·agent
星云穿梭1 天前
用Python写一个带图形界面的学生管理系统——完整教程
python