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

变量规则

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

@app.route('/user/<username>')
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
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>404 Not Found</title>
<h1>Not Found</h1>
<p>The requested URL was not found on the server.  If you entered the URL manually please check your spelling and try again.</p>
(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 -

转载于:https://www.cnblogs.com/itflycat/p/4435694.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值