本篇主要记录和实践flask模块中的render_template,url_for,redirect函数。这三个函数都用于返回给客户端。
1. render_template使用
通过render_template
函数进行模板的渲染
在app.py
同级目录下,创建templates
目录,用于存放需要flask渲染的模板
from flask import Flask, render_template
app = Flask(__name__)
app.config['DEBUG'] = True
@app.route('/')
def index():
#return "hello,world"
return render_template('index.html')
@app.route('/user/<name>')
def user(name):
return f"hello,{name}"
if __name__ == "__main__":
app.run()
templates/index.html
内容:
<h1>
hello,world
</h1>
访问:http://127.0.0.1:5000/ 获取到模板index.html
的内容
2. redirect使用
通过redirect
函数进行重定向
from flask import Flask, render_template, redirect
app = Flask(__name__)
app.config['DEBUG'] = True
@app.route('/')
def index():
return render_template('index.html')
@app.route('/index')
def newindex():
return redirect('/')
@app.route('/user/<name>')
def user(name):
return f"hello,{name}"
if __name__ == "__main__":
app.run()
3. url_for使用
url_for一般使用在2个场景中。redirect函数参数为(location,code,response),url_for函数就是来代替location的
- 在视图函数中,通过url_for指定url的别名
- 在模板中,通过url_for来加载静态资源,以及替代action的url