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'
posted @ 2020-02-26 10:18  梦回丶故里  阅读(358)  评论(0编辑  收藏  举报