flask 快速入门-03 之 `变量规则`

变量规则

在URL部分添加变量使用<variable_name>就可以了。

@app.route('/user/')
def show_user_profile(username):
# show the user profile for that user
return 'User %s' % username

@app.route('/post/int:post_id')
def show_post(post_id):
# show the post with the given id, the id is an integer
return 'Post %d' % post_id

第一个例子,只要在url后输入什么数据都可以。

$curl http://127.0.0.1/user/abc
User abc(site)

第二个例子,因为绑定了转换器规则,所以当不符合转换器指定的类型时,将会报错。

$curl http://127.0.0.1/post/12345
Post 12345(site)

$curl http://127.0.0.1/post/abc

404 Not Found

Not Found


The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.


(site)

int:接收参数必须是整数
float:接收参数必须是浮点型
path:接受参数必须是string型,可以接受"/"线。

关于这个path,其实就是支持字符串的参数。
我测试了一下。

加path的情况日志访问的记录

"GET /user/abc HTTP/1.1" 200 -
"GET /user/abc/bcd/ HTTP/1.1" 200 -
"GET /user/abc/bcd HTTP/1.1" 200 -
"GET /user/abc/bcd/123 HTTP/1.1" 200 -

未加path的记录

"GET /user/abc/1234/ HTTP/1.1" 404 -
"GET /user/abc HTTP/1.1" 200 -
"GET /user/abc/1234/ HTTP/1.1" 404 -
"GET /user/abc/123 HTTP/1.1" 404 -

posted @ 2015-04-17 18:23  小米飞猫  阅读(440)  评论(0)    收藏  举报