Search code examples
pythongoogle-app-enginewebapp2

Responding with 404 as status code in Webapp2


My app is dynamically generating pages by reading the URL. For example, it will handle all URLs formatted like this:

[url]/word

If /word is a valid URL then the app will generate a page and return it back. When the app can't find anything useful it should return a 404 page.

How can I do that? More specifically how do I set the status code to 404?


Solution

  • From within your RequestHandler, you can simply call self.abort(404) or webapp2.abort(404) to set the error status code.

    References:

    • webapp2.RequestHandler.abort():

      Raises an HTTPException.

      This stops code execution, leaving the HTTP exception to be handled by an exception handler.

      Parameters:

      code – HTTP status code (e.g., 404).
      args – Positional arguments to be passed to the exception class.
      kwargs – Keyword arguments to be passed to the exception class.
      
    • webapp2.abort():

      Raises an HTTPException.

      Parameters:

      code – An integer that represents a valid HTTP status code.
      args – Positional arguments to instantiate the exception.
      kwargs – Keyword arguments to instantiate the exception.