以Webapp2中的状态码404作为响应 [英] Responding with 404 as status code in Webapp2

查看:174
本文介绍了以Webapp2中的状态码404作为响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序通过读取网址动态生成网页。例如,它会处理所有格式如下的URL:

  [url] / word 

如果 / word 是一个有效的URL,那么应用程序将生成一个页面并返回它背部。当应用程序找不到有用的东西时,它应该返回一个404页面。



我该怎么做?更具体地说,我该如何设置状态码为404?

解决方案

在RequestHandler中,您可以简单地调用 self.abort(404) webapp2.abort(404)来设置错误状态代码。



参考文献:


  • webapp2.RequestHandler.abort()


    引发 HTTPException



    这会停止代码执行,使得HTTP异常由
    处理为异常处理程序。



    参数:

     代码 -  HTTP状态代码(例如404)。 
    args - 要传递给异常类的位置参数。
    kwargs - 要传递给异常类的关键字参数。



  • webapp2.abort() : / p>


    引发 HTTPException




    $ b

      code  - 一个表示有效HTTP状态码的整数。 
    args - 实例化异常的位置参数。
    kwargs - 实例化异常的关键字参数。




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?

解决方案

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.
    

这篇关于以Webapp2中的状态码404作为响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆