avatar

AngYi

Aim for the stars, and beyond.

  • 首页
  • 分类
  • 标签
  • 归档
  • 相册
  • 关于我
Home 【Flask开发】 2. 路由与蓝图
文章

【Flask开发】 2. 路由与蓝图

Posted 2021-12-12 Updated 2023-10- 17
By AngYi
6~8 min read

路由与蓝图

查询所有路由

  1. 命令行方式,前提是export FLASK_APP=app

    flask routes
    
  2. print(app.url_map)

  3. 迭代url.map

@app.route('/')
def index():
    data = {}
    for rule in app.url_map.iter_rules():
        data[rule.endpoint] = rule.rule
    return jsonify(data)

蓝图

Flask蓝图提供了模块化管理程序路由的功能,使程序结构清晰、简单易懂。下面分析蓝图的使用方法:

image-20211212201947126

蓝图是独立的,比如一个博客可以将首页,文章详情页,用户页面都独立为单个蓝图,蓝图的创建代码为:

from flask import Blueprint, render_template, request
from apps.article.model import Article


index_bp = Blueprint('index', __name__)


@index_bp.route("/welcome")
def welcome():
    return render_template("welcome.html")


@index_bp.route('/')
@index_bp.route('/<int:page>', methods=['GET'])
def index(page=None):
    # user = request.
    if not page:
        page=1
    article = Article.query.order_by(Article.pdatetime.desc()).paginate(page=page, per_page=4)

    return render_template('index.html', article=article.items, pagination=article)

创建好蓝图之后将蓝图注册在主app中:

from exts import db, bootstrap, md
from apps.user.model import *
from apps.article.model import Article
from apps.categories.model import Categories


def create_app():
    app = Flask(__name__, template_folder='../templates/', static_folder='../static/')
    app.config.from_object(Config) 
    bootstrap.init_app(app=app)  # bootstrap
    m = Moment(app)
    md.init_app(app=app)
    db.init_app(app)  # 数据库
    app.register_blueprint(index_bp)
    app.register_blueprint(user_bp)
    app.register_blueprint(article_bp)


    print(app.url_map)
    return app

开发学习
License:  CC BY 4.0
Share

Further Reading

Dec 11, 2024

我有自己的摄影网站啦

利用周末的时间,搞了一个网站,用来展示一些我的摄影作品。 点击博客左侧的[相册](AngYi’s Gallery)链接就是啦~ github 代码仓库的地址: https://github.com/Flionay/Dash_Photo_Gallery 项目简介 **Dash Photo Galler

Oct 23, 2024

Dash 进阶技巧

使用外部图标 费老的feffery-antd-components方法 20230619-在dash应用中使用fontawesome外部图标 第一步:在 https://fontawesome.com/download 中选择“free for web”资源进行下载 第二步:解压下载内容后,将其中的

May 16, 2022

利用FastAPI和Docker部署机器学习应用

Pexels 上的 Tom Fisk 拍摄的图片作为一名数据科学家,训练您的机器学习模型只是为客户提供解决方案的一部分。 除了生成和清理数据、选择和调整算法之外,您还需要交付和部署结果,以便在生产中使用。 这本身就是一个庞大的领域,具有不断发展的工具和标准。 在这篇文章中,我的目标是提供一份实用指南

OLDER

【Flask开发】1. 安装与配置

NEWER

Python 装饰器

Recently Updated

  • DeepSeek 创始人梁文峰采访:创新、人才与中国 AI 发展
  • 福州-厦门之行
  • 我有自己的摄影网站啦
  • 借助Ollama一键本地部署CodeGeex,让AI帮你打工
  • Dash 进阶技巧

Trending Tags

ssh linux matlab 感悟 读书 blog git python flask ML

Contents

©2025 AngYi. Some rights reserved.

Using the Halo theme Chirpy