【问题标题】:Python - Flask Default Route possible?Python - 烧瓶默认路由可能吗?
【发布时间】:2012-11-20 15:10:33
【问题描述】:

在 Cherrypy 中可以这样做:

@cherrypy.expose
def default(self, url, *suburl, **kwarg):
    pass

有没有等效的烧瓶?

【问题讨论】:

    标签: python flask cherrypy


    【解决方案1】:

    Flask 的网站上有一个关于 Flask 的“包罗万象”路线的 sn-p。 You can find it here.

    基本上,装饰器通过链接两个 URL 过滤器来工作。页面上的例子是:

    @app.route('/', defaults={'path': ''})
    @app.route('/<path:path>')
    def catch_all(path):
        return 'You want path: %s' % path
    

    这会给你:

    % curl 127.0.0.1:5000          # Matches the first rule
    You want path:  
    % curl 127.0.0.1:5000/foo/bar  # Matches the second rule
    You want path: foo/bar
    

    【讨论】:

    • 由于某种原因它对我不起作用。它适用于/,但是当我尝试其他方法时它返回 404
    【解决方案2】:
    @app.errorhandler(404)
    def handle_404(e):
        # handle all other routes here
        return 'Not Found, but we HANDLED IT
    

    【讨论】:

    • 添加一些解释会提高你的回答质量。
    【解决方案3】:

    如果您的单页应用程序具有嵌套路由(例如 www.myapp.com/tabs/tab1 - 典型的 Ionic/Angular 路由),您可以像这样扩展相同的逻辑:

    @app.route('/', defaults={'path1': '', 'path2': ''})
    @app.route('/<path:path1>', defaults={'path2': ''})
    @app.route('/<path:path1>/<path:path2>')
    def catch_all(path1, path2):
        return app.send_static_file('index.html')
    

    【讨论】:

      【解决方案4】:

      试试这个

      @app.route('/')
      def entry():
          return redirect('/defaultroute')
      

      【讨论】:

        猜你喜欢
        • 2016-02-29
        • 2015-02-16
        • 1970-01-01
        • 1970-01-01
        • 2019-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-22
        相关资源
        最近更新 更多