学习 Flask Web Development 2nd Edition
Posted 加载Python技能
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了学习 Flask Web Development 2nd Edition 相关的知识,希望对你有一定的参考价值。
学习思想:学习可以看作一个 输入-方法-输出 过程,敲几遍是 Learn by Doing 的实践,是一种有效的方式目标:学习 Flask Web Development 2nd Edition环境:Python 3.6.4, Flask
第三章 模版 (Templates)
Jinja2 模版新建文件夹 templates, 在里面新建文件 index.html, user.html
# templates/index.html
<h1>Hello World!</h1>
# templates/user.html
<h1>Hello, {{ name }}!</h1>
渲染模版
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/user/<name>')
def user(name):
return render_template('user.html', name=name)
左边的 name 是模版里面的参数名 (argument name),右边的 name 是当前文件中的变量 (variable),赋值给左边参数变量多种变量类型示例
<p>A value from a dictionary: {{ mydict['key'] }}.</p>
<p>A value from a list: {{ mylist[3] }}.</p>
<p>A value from a list, with a variable index: {{ mylist[myintvar] }}.</p>
<p>A value from an object's method: {{ myobj.somemethod() }}.</p>
变量可被过滤器 (filters) 更改,比如
Hello, {{ name|capitalize }}
Jinja2 常用的变量过滤器
safe | Renders the value without applying escaping |
---|---|
capitalize | Converts the first character of the value to uppercase and the rest to lowercase |
lower | Converts the value to lowercase characters |
upper | Converts the value to uppercase characters |
title | Capitalizes each word in the value |
trim | Removes leading and trailing whitespace from the value |
striptags | Removes any HTML tags from the value before rendering |
控制结构 (Control Structures)分支控制示例
{% if user %}
Hello, {{ user }}!
{% else %}
Hello, Stranger!
{% endif %}
循环控制示例
<ul>
{% for comment in comments %}
<li>{{ comment }}</li>
{% endfor %}
</ul>
宏指令,类似于函数
{% macro render_comment(comment) %}
<li>{{ comment }}</li>
{% endmacro %}
<ul>
{% for comment in comments %}
{{ render_comment(comment) }}
{% endfor %}
</ul>
为了增加宏的可读性,单独放到一个文件
{% import 'macros.html' as macros %}
<ul>
{% for comment in comments %}
{{ macros.render_comment(comment) }}
{% endfor %}
</ul>
用 include
复用代码
{% include 'common.html' %}
模版继承 (template inheritance)
# base.html
<html>
<head>
{% block head %}
<title>{% block title %}{% endblock %} - My Application</title>
{% endblock %}
</head>
<body>
{% block body %}
{% endblock %}
</body>
</html>
{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block head %}
{{ super() }}
<style>
</style>
{% endblock %}
{% block body %}
<h1>Hello, World!</h1>
{% endblock %}
集成 Bootstrap安装 Flask-Bootstrap
$pipenv install flask-bootstrap
# hello.py
from flask_bootstrap import Bootstrap
# ...
bootstrap = Bootstrap(app)
在模版中使用 Flask-Bootstrap
# templates/user.html
{% extends "bootstrap/base.html" %}
{% block title %}Flasky{% endblock %}
{% block navbar %}
<div class="navbar navbar-inverse" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle"
data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">Flasky</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="/">Home</a></li>
</ul>
</div>
</div>
</div>
{% endblock %}
{% block content %}
<div class="container">
<div class="page-header">
<h1>Hello, {{ name }}!</h1>
</div>
</div>
{% endblock %}
在浏览器打开 http://127.0.0.1:5000/user/sam表格 Flask-Bootstrap's base template blocks
Block name | Description |
---|---|
doc | The entire HTML document |
html_attribs | Attributes inside the html tag |
html | The contents of the html tag |
head | The contents of the head tag |
title | The contents of the title tag |
metas | The list of meta tags |
styles | Cascading stylesheet definitions |
body_attribs | Attributes inside the body tag |
body | The contents of the body tag |
navbar | User-defined navigation bar |
content | User-defined page content |
scripts | javascript declarations at the bottom of the document |
scripts
区块示列
{% block scripts %}
{{ super() }}
<script type="text/javascript" src="my-script.js"></script>
{% endblock %}
定制错误页面
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_server_error(e):
return render_template('500.html'), 500
创建 base template
{% extends "bootstrap/base.html" %}
{% block title %}Flasky{% endblock %}
{% block navbar %}
<div class="navbar navbar-inverse" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle"
data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">Flasky</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="/">Home</a></li>
</ul>
</div>
</div>
</div>
{% endblock %}
{% block content %}
<div class="container">
{% block page_content %}{% endblock %}
</div>
{% endblock %}
新建 template 404
# templates/404.html
{% extends "base.html" %}
{% block title %}Flasky - Page Not Found{% endblock %}
{% block page_content %}
<div class="page-header">
<h1>Not Found</h1>
</div>
{% endblock %}
新建 template 500
# templates/500.html
{% extends "base.html" %}
{% block title %}Flasky - Internal Server Error{% endblock %}
{% block page_content %}
<div class="page-header">
<h1>Internal Server Error</h1>
</div>
{% endblock %}
重构 template index
# templates/index.html
{% extends "base.html" %}
{% block title %}Flasky{% endblock %}
{% block page_content %}
<div class="page-header">
<h1>Hello World!</h1>
</div>
{% endblock %}
重构 template user
# templates/user.html
{% extends "base.html" %}
{% block title %}Flasky{% endblock %}
{% block page_content %}
<div class="page-header">
<h1>Hello, {{ name }}!</h1>
</div>
{% endblock %}
链接Flask 有一个 helper 方法 url_for
生成 URL.比如调用 url_for('index')
返回 /
, 调用 url_for('index', _external=True)
返回绝对 URL http://localhost:5000/
, 调用url_for('user', name='sam', _external=True)
返回http://localhost:5000/user/sam
, 调用 url_for('user', name='sam', page=2, version=1)
返回 /user/sam?page=2&version=1
, 调用 url_for('static', filename='css/styles.css', _external=True)
返回http://localhost:5000/static/css/styles.css
.
静态文件 (static files)使用 favicon.ico 示例
# templates/base.html
{% block head %}
{{ super() }}
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}"
type="image/x-icon">
<link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}"
type="image/x-icon">
{% endblock %}
用 Flask-Moment 本地化日期和时间安装 flask-moment
$pipenv install flask-moment
初始化 Flask-Moment
from flask_moment import Moment
moment = Moment(app)
在 base template 应用 moment
# templates/base.html
{% block scripts %}
{{ super() }}
{{ moment.include_moment() }}
{% endblock %}
在 index 页面显示当地时间
# hello.py
from datetime import datetime
@app.route('/')
def index():
return render_template('index.html',
current_time=datetime.utcnow())
# templates/index.html
<p>The local date and time is {{ moment(current_time).format('LLL') }}.</p>
<p>That was {{ moment(current_time).fromNow(refresh=True) }}</p>
用浏览器打开 http://localhost:5000/Flask_Moment 可执行 format()
, fromNow()
, fromTime()
,calendar()
, valueOf()
, unix()
等方法本地化语言示例
{% block scripts %}
{{ super() }}
{{ moment.include_moment() }}
{{ moment.locale('fr') }}
{% endblock %}
以上是关于学习 Flask Web Development 2nd Edition 的主要内容,如果未能解决你的问题,请参考以下文章
Flask Web Development —— 数据库(上)