View Functions — Rendering the Article List and Detail Pages
In this chapter you will learn to use view functions to query data from the database, render the home and detail pages, and split routes with Blueprint.
Responsibilities of View Functions
The responsibilities of Flask view functions are the same as Django's: receive request → query data → render template.
Example
File path: app.py
from
flask
import
Flask
,
render_template
from
models
import
Post
,
Category
@
app.
route
(
"/"
)
def
index
(
)
:
"""Blog homepage: display all articles"""
posts
=
Post.
query
.
order_by
(
Post.
created_at
.
desc
(
)
)
.
all
(
)
categories
=
Category.
query
.
all
(
)
return
render_template
(
'index.html'
,
posts
=
posts
,
categories
=
categories
)
Path Parameters and Query Parameters
| Parameter type | URL example | How the View Retrieves It |
|---|---|---|
| Path parameters | /post/3 | In the route |
| Query Parameters | /?category=python | request.args.get('key') |
Flask routes support several type converters:(integer),(default, does not include /),(includes /), , etc.
Article Detail Page
Example
File path: append to app.py
from
flask
import
abort
@
app.
route
(
"/post/int:post_id"
)
def
post_detail
(
post_id
)
:
"""Article detail page"""
get_or_404 is equivalent to: Post.query.get(post_id) or abort(404)
post
=
Post.
query
.
get_or_404
(
post_id
,
description
=
f
'Article #{post_id} does not exist'
)
return
render_template
(
'post_detail.html'
,
post
=
post
)
Custom 404 Error Page
Example
@
app.
errorhandler
(
404
)
def
not_found
(
error
)
:
return
render_template
(
'404.html'
)
,
404
Category filtering
Example
File path: refactor the index view in app.py
from
flask
import
request
@
app.
route
(
"/"
)
def
index
(
)
:
category_slug
=
request.
args
.
get
(
'category'
,
''
)
keyword
=
request.
args
.
get
(
'q'
,
''
)
Search keyword (implemented in Chapter 6)
posts_query
=
Post.
query
.
order_by
(
Post.
created_at
.
desc
(
)
)
Filter by category
if
category_slug:
posts_query
=
posts_query.
join
(
Category
)
.
filter
(
Category.
slug
==
category_slug
)
posts
=
posts_query.
all
(
)
categories
=
Category.
query
.
all
(
)
return
render_template
(
'index.html'
,
posts
=
posts
,
categories
=
categories
,
category_slug
=
category_slug
,
keyword
=
keyword
)
request.argsis an immutable MultiDict used to read URL query parameters. Use.get('key', '默认值')to get values safely; if the parameter does not exist, return a default value instead of an error.
Blueprint — Splitting Routes
As view functions increase, piling them all in app.py becomes unmanageable.
Blueprint is Flask's route-grouping solution: split views by functional module and register them via app.register_blueprint().
app/
├── blueprints/
│ ├── __init__.py
│ ├── main.py # 首页、关于、搜索
│ └── posts.py # 文章列表、详情
├── templates/
├── models.py
└── __init__.py
Example
File path: app/blueprints/main.py
from
flask
import
Blueprint
,
render_template
,
request
from
app.
models
import
Post
,
Category
Blueprint('blueprint_name', name, url_prefix='/')
main_bp
=
Blueprint
(
'main'
,
name
)
@
main_bp.
route
(
"/"
)
def
index
(
)
:
"""Blog homepage"""
category_slug
=
request.
args
.
get
(
'category'
,
''
)
posts_query
=
Post.
query
.
order_by
(
Post.
created_at
.
desc
(
)
)
if
category_slug:
posts_query
=
posts_query.
join
(
Category
)
.
filter
(
Category.
slug
==
category_slug
)
return
render_template
(
'index.html'
,
posts
=
posts_query.
all
(
)
,
categories
=
Category.
query
.
all
(
)
,
category_slug
=
category_slug
)
Example
File path: app/blueprints/posts.py
from
flask
import
Blueprint
,
render_template
,
abort
from
app.
models
import
Post
posts_bp
=
Blueprint
(
'posts'
,
name
)
@
posts_bp.
route
(
"/post/int:post_id"
)
def
post_detail
(
post_id
)
:
post
=
Post.
query
.
get_or_404
(
post_id
)
return
render_template
(
'post_detail.html'
,
post
=
post
)
Register the Blueprint at the application entry point:
Example
File path: app.py
from
flask
import
Flask
from
app.
blueprints
.
main
import
main_bp
from
app.
blueprints
.
posts
import
posts_bp
app
=
Flask
(
name
)
Registering a blueprint: all blueprint view functions are merged into the same application
app.
register_blueprint
(
main_bp
)
app.
register_blueprint
(
posts_bp
)
A Blueprint can specify a
url_prefix(such asurl_prefix='/blog'), then all routes within the blueprint automatically get this prefix. A Blueprint can also have its own templates and static files directory.
Create the homepage and detail page templates
index.html
Example
{% extends 'base.html' %}
{% block title %}RUNOOB Blog - Home{% endblock %}
{% block content %}
Latest Articles
{% if posts %}
{% for post in posts %}
{{ post.category.name }}
{{ post.title }}
{{ post.summary|truncate(80) }}
{{ post.created_at.strftime('%Y-%m-%d') }}
{% endfor %}
{% else %}
No articles in this category yet.
{% endif %}
{% endblock %}
When using a Blueprint view in url_for(), the format is
url_for('蓝图名.函数名'), such asurl_for('posts.post_detail', post_id=3). Note the contrast with Django's{% url %}tag: Flask uses{{ url_for() }}, which can be nested in Python expressions for greater flexibility.
Chapter Summary
In this chapter you mastered Flask views and route organization: Post.query for querying data, path parameters int:post_id and query parameters via request.args, get_or_404 for safe queries, abort(404) and custom error pages, and Blueprint for splitting routes by module.
The blog now has three complete pages: homepage article list, category filtering, and detail page.