zoukankan      html  css  js  c++  java
  • 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'
    
  • 相关阅读:
    export ,export default 和 import 区别 以及用法
    koa2 安装环境
    Webstorm在MAC下的安装方法
    Mac 下搭建vue开发环境
    Mac系统下安装Vue-cli详细步骤
    npm 安装vue 报错Failed at the chromedriver@2.34.0 install script 'node install.js'
    #001 WebStrom SVN使用技巧
    #006 dependencies和devDependencies的区别
    #001 GIT创建分支
    #003 React 组件 继承 自定义的组件
  • 原文地址:https://www.cnblogs.com/itdreamfly/p/12871598.html
Copyright © 2011-2022 走看看