Google App Engine and 404 error

前端 未结 9 1147
一生所求
一生所求 2020-12-02 06:46

I\'ve setup a static website on GAE using hints found elsewhere, but can\'t figure out how to return a 404 error. My app.yaml file looks like

- url: (.*)/
           


        
相关标签:
9条回答
  • 2020-12-02 07:13

    You can create a function to handle your errors for any of the status codes. You're case being 404, define a function like this:

    def Handle404(request, response, exception):
         response.out.write("Your error message") 
         response.set_status(404)`
    

    You can pass anything - HTML / plain-text / templates in the response.out.write function. Now, add the following declaration after your app declaration.

    app.error_handlers[404] = Handle404

    This worked for me.

    0 讨论(0)
  • 2020-12-02 07:17

    You need to register a catch-all script handler. Append this at the end of your app.yaml:

    - url: /.*
      script: main.py
    

    In main.py you will need to put this code:

    from google.appengine.ext import webapp
    from google.appengine.ext.webapp.util import run_wsgi_app
    
    class NotFoundPageHandler(webapp.RequestHandler):
        def get(self):
            self.error(404)
            self.response.out.write('<Your 404 error html page>')
    
    application = webapp.WSGIApplication([('/.*', NotFoundPageHandler)],
                                         debug=True)
    
    def main():
        run_wsgi_app(application)
    
    if __name__ == "__main__":
        main()
    

    Replace <Your 404 error html page> with something meaningful. Or better use a template, you can read how to do that here.

    Please let me know if you have problems setting this up.

    0 讨论(0)
  • 2020-12-02 07:19

    google app engine now has Custom Error Responses

    so you can now add an error_handlers section to your app.yaml, as in this example:

    error_handlers:
    
    - file: default_error.html
    
    - error_code: over_quota
        file: over_quota.html
    
    0 讨论(0)
提交回复
热议问题