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

相关推荐
默_笙8 小时前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
qq_426003969 小时前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫9 小时前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技9 小时前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读9 小时前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时10 小时前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
奇思妙想聪明勤奋的小羊11 小时前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd12311 小时前
2026年第38周GitHub趋势周报
python·科技·github
IZero0711 小时前
Jev 与 Laya
python·语言模型