【问题标题】:URL with trailing slash in Google App EngineGoogle App Engine 中带有斜杠的 URL
【发布时间】:2010-07-27 12:26:22
【问题描述】:

这是我的 app.yaml:

- url: /about|/about/.*
  script: about.py

这是我的`about.py':

application = webapp.WSGIApplication([(r'^/about$', AboutPage),
                                      (r'^/about/$', Redirect),
                                      (r'.*', ErrorPage)],
                                        debug = True)

我想将/about/ 的所有请求重定向到/about。我希望将所有其他请求发送到错误页面。

它在本地主机上的开发服务器中工作,但在我将应用程序部署到 GAE 后,我无法访问 /about/ - 它只是显示一个空白页面。

我调整了 app.yaml 中 URL 模式的顺序。 它现在可以在 GAE 上运行。

【问题讨论】:

  • 可能问题出在重定向而不是 URL 模式。
  • Redirect 所做的是 self.redirect('/about'),它在我自己的机器上运行良好

标签: google-app-engine url-rewriting


【解决方案1】:

如果您不希望应用程序中任何地方的 GET 请求的尾部斜杠,您可以在 app.yaml 的顶部实现全局重定向。请注意,POST 请求不会重定向,但这没关系(无论如何对我来说),因为用户通常不会手写 POST URL。

app.yaml

application: whatever
version: 1
api_version: 1
runtime: python

handlers:
- url: .+/ 
  script: slashmurderer.py

slashmurderer.py

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class SlashMurdererApp(webapp.RequestHandler):
   def get(self, url):
      self.redirect(url)

application = webapp.WSGIApplication(
   [('(.*)/$', SlashMurdererApp)]
)

def main():
   run_wsgi_app(application)

【讨论】:

    【解决方案2】:

    我看到这个问题已经得到解答,但我遇到了同样的问题,想看看是否有“更懒惰”的解决方案。

    如果您使用的是 Python 2.7 运行时,那么 webapp2 库是可用的,我相信以下内容会起作用:

    import webapp2
    from webapp2_extras.routes import Redirect Route
    
    class MainHandler(webapp2.RequestHandler):
        def get(self):
            self.response.out.write("This is my first StackOverflow post")
    
    app = webapp2.WSGIApplication([
        RedirectRoute('/', MainHandler, name='main', strict_slash=True),
        ('/someurl', OtherHandler),
    ])
    

    strict_slash=True 表示如果客户端不提供斜杠,它将被重定向到带有斜杠的 url(以匹配第一个参数)。

    您可以将 webapp2_extras 中的特殊 Route 类与正常的 (regex, handler) 元组结合起来,如上所示。 RedirectRoute 的构造函数需要“name”参数。更多细节在这里:webapp2_extras documentation for RedirectRoute

    【讨论】:

      猜你喜欢
      • 2011-10-09
      • 1970-01-01
      • 1970-01-01
      • 2011-09-13
      • 2016-11-29
      • 1970-01-01
      • 2021-05-21
      • 2014-12-28
      相关资源
      最近更新 更多