路由
-
route()
裝飾器把一個(gè)函數(shù)綁定到對(duì)應(yīng)的URL上
@app.route('/)
def index():
return 'Index Page'
@app.route('/hello')
def hello():
return 'Hello World'
- 動(dòng)態(tài)路由(路由含變量),變量字段用
<username>
這種形式
@app.route('/user/<username>')
def show_user_profile(username):
return 'User %s' % username
@app.route('/post/<int:post_id>') #int指定類型唉工,接受整數(shù),也可以是float/path
def show_post(post_id):
return 'Post %d' % post_id
- 唯一url/重定向行為汹忠。
并沒(méi)有看懂
- 構(gòu)造url酵紫,
url_for()
函數(shù)可以給指定的函數(shù)構(gòu)造url告嘲,接受函數(shù)名作為第一個(gè)參數(shù)错维,也接受對(duì)應(yīng)URL規(guī)則的變量部分的命名參數(shù)(真夠繞的)奖地,未知變量部分會(huì)添加到URL末位作為查詢參數(shù)
from flask import Flask,url_for
app = Flask(__name__)
@app.route('/')
def index():pass
@app.route('/login')
def login():pass
@app.route('/user/<username>')
def profile(username):pass
with app.test_request_context():
print url_for('index')
print url_for('login')
print url_for('login',next='/')
print url_for('profile',username='Meng')
- HTTP方法,默認(rèn)情況下赋焕,路由只回應(yīng)GET請(qǐng)求参歹,但是通過(guò)route()裝飾器傳遞methods參數(shù)可以改變這個(gè)行為
@app.route('/login',methods=['GET','POST'])
def login():
if request.method == 'POST':
do_the_login()
else:
show_the_login_form()