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

请求详情、转换器和可选分类

PYTHONWindows、CPython 3.12.14、Flask 3.1.3、Flask-SQLAlchemy 3.1.1、SQLAlchemy 2.1.6、SQLite 3.53.1posts.py
posts.py35 行
from flask import Blueprint, abort, render_template, request
from sqlalchemy import select

from .models import Category, Post, db

posts = Blueprint("posts", __name__)


@posts.get("/")
def listing():
    selected = request.args.get("category", "")
    statement = select(Post).where(Post.published.is_(True))
    if selected:
        statement = statement.join(Post.category).where(Category.slug == selected)
    rows = db.session.scalars(statement.order_by(Post.created_at.desc(), Post.id.desc())).all()
    categories = db.session.scalars(select(Category).order_by(Category.id)).all()
    return render_template("listing.html", posts=rows, categories=categories,
                           selected=selected, keyword=request.args.get("q", ""))


@posts.get("/article/<int:post_id>")
def detail(post_id):
    post = db.get_or_404(Post, post_id)
    if not post.published:
        abort(404)
    return render_template("detail.html", post=post)


@posts.get("/convert/number/<int:value>")
@posts.get("/convert/word/<string:value>")
@posts.get("/convert/path/<path:value>")
@posts.get("/convert/decimal/<float:value>")
def converters(value):
    return {"value": value, "type": type(value).__name__}
本例需在 Windows、CPython 3.12.14、Flask 3.1.3、Flask-SQLAlchemy 3.1.1、SQLAlchemy 2.1.6、SQLite 3.53.1 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、CPython 3.12.14、Flask 3.1.3、Flask-SQLAlchemy 3.1.1、SQLAlchemy 2.1.6、SQLite 3.53.1

入口文件:projects/flask-coast-blog/coast_blog/posts.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 posts.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、CPython 3.12.14、Flask 3.1.3、Flask-SQLAlchemy 3.1.1、SQLAlchemy 2.1.6、SQLite 3.53.1。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Flask

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

下载课程关联工程包:Flask

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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