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

点开列表中的文章并切换至 JSON

PYTHONCPython 3.12、FastAPI 0.162.2、Uvicorn 0.54.0、pytest 9.2.0views.py
views.py56 行
from pathlib import Path
from typing import Annotated

from fastapi import APIRouter, Query, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy import select

from api import DB, find
from models import Category
from schemas import CategoryResponse
from search import lookup


pages = APIRouter(tags=["pages"])
categories_api = APIRouter(prefix="/api/categories", tags=["categories"])
templates = Jinja2Templates(directory=Path(__file__).with_name("templates"))


@categories_api.get("", response_model=list[CategoryResponse])
def list_categories(db: DB):
    return db.scalars(select(Category).order_by(Category.slug)).all()


@pages.get("/", name="home", response_class=HTMLResponse)
def home(request: Request, db: DB,
         category: Annotated[str | None, Query(max_length=60)] = None,
         q: Annotated[str | None, Query(max_length=80)] = None,
         page: Annotated[int, Query(ge=1, le=100000)] = 1,
         size: Annotated[int, Query(gt=0, lt=51)] = 6):
    keyword = (q or "").strip()
    result = lookup(db, category, keyword, page, size)
    categories = list_categories(db)

    def home_link(number, slug):
        params = {"page": number, "size": size}
        if slug:
            params["category"] = slug
        if keyword:
            params["q"] = keyword
        return request.url_for("home").include_query_params(**params)

    return templates.TemplateResponse(request=request, name="index.html", context={
        "result": result, "category": category or "", "keyword": keyword,
        "categories": [(row, home_link(1, row.slug)) for row in categories],
        "all_link": home_link(1, None),
        "prev_link": home_link(page - 1, category) if page > 1 else None,
        "next_link": home_link(page + 1, category) if page < result.pages else None,
    })


@pages.get("/post/{post_id}", name="post_detail", response_class=HTMLResponse)
def detail(request: Request, post_id: int, db: DB):
    post = find(db, post_id)
    return templates.TemplateResponse(request=request, name="detail.html", context={"post": post})
本例需在 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-blog-query-migration/views.py

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

下载课程关联工程包:FastAPI

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

下载课程关联工程包:FastAPI

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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