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

运行采样接口、请求校验和响应模型

PYTHONCPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0,本机 HTTPapp.py
app.py60 行
"""Small Blue Sky ASGI practice application."""
import asyncio
from pathlib import Path
from typing import Annotated

from fastapi import FastAPI, Query, WebSocket
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field


class Sample(BaseModel):
    value: int = Field(ge=0, le=100)


class Summary(BaseModel):
    station_id: int
    label: str
    value: int


vendor = Path(__file__).with_name("vendor")
offline_docs = (vendor / "swagger-ui-bundle.js").is_file() and (vendor / "swagger-ui.css").is_file()
app = FastAPI(title="蓝色天空网采样 API", docs_url=None if offline_docs else "/docs")

if offline_docs:
    app.mount("/docs-assets", StaticFiles(directory=vendor), name="docs-assets")

    @app.get("/docs", include_in_schema=False)
    async def docs():
        return get_swagger_ui_html(
            openapi_url="/openapi.json",
            title="蓝色天空网采样 API",
            swagger_js_url="/docs-assets/swagger-ui-bundle.js",
            swagger_css_url="/docs-assets/swagger-ui.css",
            swagger_favicon_url="data:,",
            swagger_ui_parameters={"validatorUrl": None},
        )


@app.get("/", operation_id="station_status")
async def status():
    await asyncio.sleep(0)
    return {"service": "station", "ready": True}


@app.post("/samples/{station_id}", response_model=Summary, status_code=201)
def classify(station_id: int, sample: Sample,
             threshold: Annotated[int, Query(ge=0, le=100)] = 50):
    return {"station_id": station_id, "value": sample.value,
            "label": "high" if sample.value >= threshold else "low",
            "internal_rule": "demo-threshold-v1"}


@app.websocket("/events")
async def events(socket: WebSocket):
    await socket.accept()
    await socket.send_json({"received": await socket.receive_text()})
    await socket.close()
本例需在 CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0,本机 HTTP 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:CPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0,本机 HTTP

入口文件:projects/fastapi-intro-lab/app.py

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

下载课程关联工程包:FastAPI

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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