【问题标题】:Simple static website in GAE with custom 404 error pageGAE 中带有自定义 404 错误页面的简单静态网站
【发布时间】:2013-05-07 19:40:17
【问题描述】:

我将 GAE 用于一个只有 html/htm 页面、图片等的简单静态网站。我也在使用 Python 2.7。

所以我使用了直接的 app.yaml 和 main.py,这样就可以了。但是,当访问一个不存在的页面时,它会显示一个标准的 404 页面。我想将其更改为自定义错误页面,并在下面尝试了此操作,但它不起作用。

这是我的 app.yaml 和 main.py 文件:

application: xxxx
version: 11
runtime: python27
api_version: 1
threadsafe: true

default_expiration: "7d"

inbound_services:
- warmup

handlers:
- url: /
  static_files: index.html
  upload: index.html

- url: /(.*)
  static_files: \1
  upload: (.*)

- url: /.*
  script: main.app

main.py:

import webapp2

class BaseHandler(webapp2.RequestHandler):
  def handle_exception(self, exception, debug):
    # Set a custom message.
    self.response.write('An error occurred.')

    # If the exception is a HTTPException, use its error code.
    # Otherwise use a generic 500 error code.
    if isinstance(exception, webapp2.HTTPException):
      self.response.set_status(exception.code)
    else:
      self.response.set_status(500)

class MissingPage(BaseHandler):
  def get(self):
    self.response.set_status(404)
    self.response.write('Page has moved. Pls look at http://www.yyyyyy.yy to find the new location.')

class IndexHandler(webapp2.RequestHandler):
    def get(self):
        if self.request.url.endswith('/'):
            path = '%sindex.html'%self.request.url
        else:
            path = '%s/index.html'%self.request.url

        self.redirect(path)

    def post(self):
        self.get()

app = webapp2.WSGIApplication(
   [  (r'/', IndexHandler),
      (r'/.*', MissingPage)
      ],
   debug=True)

什么不正确??我找到了很多条目,但没有一个能准确解释如何使用 Python 2.7 为一个简单的网站执行此操作,

让我知道,非常感谢,迈克尔

【问题讨论】:

  • 省略 .yaml 文件中的第二个处理程序,您将在 main.app 中看到处理程序的结果。第二个处理程序应该做什么 - static_files: \1 ?
  • 谢谢 RGil,这是一个很好的线索,我试图取出第二个处理程序,但我确实得到了 404 自定义错误页面。但现在它只有 index.html 页面,而没有其他 (105) 页面、图像、样式表等。我使用第二个处理程序来服务所有其他页面。那么有没有办法让我仍然可以将所有 105 个文件作为静态文件提供并获取自定义错误页面。

标签: google-app-engine static web http-status-code-404 webapp2


【解决方案1】:

除了 404 页面之外,您的网站似乎不需要任何动态部分。 有一个error_handlers可以直接使用。

https://developers.google.com/appengine/docs/python/config/appconfig#Custom_Error_Responses

application: xxxx
version: 11
runtime: python27
api_version: 1
threadsafe: true

default_expiration: "7d"

inbound_services:
- warmup

handlers:
- url: /
  static_files: index.html
  upload: index.html

- url: /(.*)
  static_files: \1
  upload: (.*)

error_handlers:
- file: default_error.html

【讨论】:

    猜你喜欢
    • 2013-07-25
    • 2013-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    • 1970-01-01
    • 2016-04-25
    • 2013-09-16
    相关资源
    最近更新 更多