1、使用 render_template 实现模板渲染
(1)代码编写:application.py
from flask import Flask
from flask import render_template
app = Flask(__name__)
# 一个函数可以通过多个 route() 装饰器绑定到多个 URL 上
@app.route("/hello")
@app.route("/hello/<name>")
def hello_flask(name=None):
return render_template('hello.html', name=name)
if __name__ == "__main__":
# 将一直运行,不要在后面写任何代码
app.run()
(2)模板文件的编写
模板文件的存放位置
/application.py
/templates/hello.html
模板文件的代码:
<!doctype html>
<title>hello from Flask</title>
{% if name %}
<h1> hello {{ name }} </h1>
{% else %}
<h1>hello world</h1>
{% endif %}
此时,可以访问 http://127.0.0.1:5000/hello/python 和 http://127.0.0.1:5000/hello 查看效果。
2、使用 Markup 转换变量中的特殊字符
Flask 允许程序员自己控制 Jinja2 是否需要解释这些特殊字符。
我们写一段代码来比较一下就可以知道如何控制了。
from flask import Flask
from flask import render_template
from markupsafe import Markup
app = Flask(__name__)
# 一个函数可以通过多个 route() 装饰器绑定到多个 URL 上
@app.route("/hello")
@app.route("/hello/<name>")
def hello_flask(name=None):
text = Markup("<strong>Hi %s!</strong>" % "<blink>David</blink>")
return render_template('hello.html', name=name, text=text)
if __name__ == "__main__":
# 将一直运行,不要在后面写任何代码
app.run()
hello.html 文件的代码:
<!doctype html>
<title>hello from Flask</title>
{{ text }}
{% if name %}
<h1> hello {{ name }} </h1>
{% else %}
<h1>hello world</h1>
{% endif %}
试着访问:
http://127.0.0.1:5000/hello/python
然后去掉代码中的 Markup 对比即可。
3、重定向和错误处理
代码编写:
from flask import Flask
from flask import abort
from flask import redirect
from flask import render_template
app = Flask(__name__)
@app.route("/")
def index():
return redirect("/check")
@app.route("/check")
def f_check():
# 立即向客户端返回 401 错误
abort(401)
@app.errorhandler(401)
def bad_request(error):
print("错误处理函数正在处理")
return render_template("bad_request.html")
if __name__ == "__main__":
# 将一直运行,不要在后面写任何代码
app.run()
bad_request.html 页面的代码:
<h1>这是一个错误的请求。状态码:400。</h1>