flask中路由处理

我们都知道现在的web系统的URL都是可以自定义的,也就是我们可以指定url和具体的业务控制器相关联,而这些就是通过路由来实现的。

flask中集成了路由处理模块,我们只需要简单地使用route装饰器就可以实现路由匹配。

 

@app.route('/')
def index():
    return 'Index Page'

@app.route('/hello')
def hello():
    return 'Hello, World'

上面的例子中,我们访问浏览器的时候,比如输入http://127.0.0.1/ 就会返回'index page',当输入http://127.0.0.1/hello 就会返回‘Hello World’,这就是路由的基本使用。

 

@app.route('/user/<username>')
def show_user(username):
    return username

@app.route('/post/<int:post_id>')
def show_post(post_id):
    return 'Post %d' % post_id

@app.route('/path/<path:subpath>')
def show_subpath(subpath):
    # show the subpath after /path/
    return 'Subpath %s' % escape(subpath)

从上面的例子我们可以看出,flask的路由还可以进行参数匹配,比如我们可以通过<>来对参数进行获取,可以获取到文章的id,获取到用户名等参数信息。

关于url中斜线(/)的处理

  • 当我们在路由中定义了斜线,那么当我们访问没有斜线的url的时候,它会自动添加斜线
  • 当我们在路由中没有定义斜线的时候,那么我们访问有斜线的时候,会提示404

 

@app.route('/test/')
#当我们访问http://127.0.0.1/test的时候,会重定向到http://127.0.0.1/test/
def test():
     return 'test'

@app.route('slashes')
#当我们访问http://127.0.0.1/slashes/的时候,会提示404,无法匹配到路由
def slashes():
    return 'slashes'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值