本篇主要記錄和實踐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