蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

单文件、表单与有界临时保存

PYTHONCPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0upload_lab.py
upload_lab.py75 行
from hashlib import sha256
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import Annotated

from fastapi import APIRouter, File, Form, HTTPException, UploadFile


routes = APIRouter(tags=["uploads"])
CHUNK = 8
LIMIT = 64


@routes.post("/upload/meta", operation_id="upload_metadata")
async def metadata(file: UploadFile):
    return {"filename":file.filename, "content_type":file.content_type, "size":file.size,
            "prefix_hex":(await file.read(3)).hex(), "file_type":type(file.file).__name__,
            "rolled":file.file._rolled}  # CPython teaching probe, not a public storage API.


@routes.post("/upload/bytes")
async def raw(data: Annotated[bytes, File()]):
    return {"count":len(data),"sha256":sha256(data).hexdigest()}


@routes.post("/upload/optional")
async def optional(file: UploadFile | None = None):
    return {"filename":None if file is None else file.filename}


@routes.post("/upload/many")
async def many(files: list[UploadFile]):
    return {"filenames":[f.filename for f in files]}


@routes.post("/upload/card")
async def card(title: Annotated[str, Form()], description: Annotated[str | None, Form()] = None,
               file: UploadFile | None = None):
    return {"title":title, "description":description,
            "filename":None if file is None else file.filename}


@routes.post("/upload/methods")
async def methods(file: UploadFile):
    first=await file.read(2)
    await file.seek(0)
    write_result=await file.write(b"OK")
    await file.seek(0)
    updated=await file.read()
    await file.close()
    return {"first":first.hex(), "write_result":write_result, "updated":updated.hex(), "closed":file.file.closed}


@routes.post("/upload/save")
async def save(file: UploadFile):
    if file.content_type != "text/plain":
        raise HTTPException(415,"only text/plain accepted in this lab")
    digest = sha256()
    size = 0
    with TemporaryDirectory(prefix="mbsky-upload-") as folder:
        destination = Path(folder)/"submission.txt"
        with destination.open("xb") as stream:
            while block := await file.read(CHUNK):
                size += len(block)
                if size > LIMIT:
                    raise HTTPException(413,"lab file exceeds 64 bytes")
                if b"\x00" in block:
                    raise HTTPException(422,"NUL not allowed in this lab")
                digest.update(block)
                stream.write(block)
        saved = destination.read_bytes()  # At most LIMIT bytes in the teaching fixture.
        assert sha256(saved).digest() == digest.digest()
    return {"stored_as":destination.name, "bytes_written":size, "sha256":digest.hexdigest(),
            "temporary_file_removed":not destination.exists()}
本例需在 CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0

入口文件:projects/fastapi-response-upload-lab/upload_lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 upload_lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:FastAPI

课程关联工程包(登记关联3章) · 含当前章节或实例 · mbskycom202611a508.zip

下载课程关联工程包:FastAPI

课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a182.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习