【问题标题】:How to have an alias of URL on Python Flask?如何在 Python Flask 上拥有 URL 的别名?
【发布时间】:2012-06-13 12:28:13
【问题描述】:

我正在使用 Flask 0.8。

如何拥有这样的 URL 别名:

@app.route('/')
def index():
    # I want to display as http://localhost/index, BUT, I DON'T WANT TO REDIRECT.
    # KEEP URL with only '/'

@app.route('/index')
def index():
    # Real processing to display /index view

那么,为什么我希望使用别名,因为处理 /index 的 DRY

有人知道解决方案吗?

感谢胡椒粉。

【问题讨论】:

    标签: python flask jinja2 werkzeug


    【解决方案1】:

    我不知道 Flask 是否有办法将多个 URL 分配给一个视图函数,但您当然可以像这样链接它们:

    @app.route('/')
    def root():
        return index()
    
    @app.route('/index')
    def index():
        # Real processing to display /index view
    

    【讨论】:

      【解决方案2】:

      这应该可行。但是为什么要让两个 URL 显示相同的内容呢?

      @app.route('/')
      @app.route('/index')
      def index():
          ...
      

      【讨论】:

      • 潜在用途:API 重命名,旧名称部分弃用​​。
      【解决方案3】:

      正如URL registry doc of Flask 中所写:

      您还可以为同一个函数定义多个规则。他们必须 但是要独一无二。

      @app.route('/users/', defaults={'page': 1})
      @app.route('/users/page/<int:page>')
      def show_users(page):
          pass
      

      【讨论】:

        猜你喜欢
        • 2016-01-17
        • 2019-11-18
        • 2014-01-21
        • 2018-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-14
        • 1970-01-01
        相关资源
        最近更新 更多