美文网首页
Requests02.响应状态码

Requests02.响应状态码

作者: 意爹闯天涯 | 来源:发表于2019-09-29 15:57 被阅读0次

    一、 HTTP状态码

    当requests发出请求时,此被请求url所在的服务器会返回一个包含HTTP状态码的信息头用以响应我们的请求。
    HTTP状态码通常由3位十进制数组成,根据行为划分,基本可以分为以下5类:

    分类 描述
    1** 信息,服务器收到请求,需要请求者继续执行操作
    2** 成功,操作被成功接收并处理
    3** 重定向,需要进一步的操作以完成请求
    4** 客户端错误,请求包含语法错误或无法完成请求
    5** 服务器错误,服务器在处理请求的过程中发生了错误

    一般使用中经常见到的状态码:

    • 200 : 请求成功
    • 301 : 重定向到其它URL
    • 401 :未授权
    • 404 - 请求的Url不存在
    • 500 - 内部服务器错误,如服务器端代码异常。
      关于HTTP状态码更多详细信息,请参见:菜鸟教程-HTTP状态码

    二、获取响应的状态码

    在使用requests时,如果需要获取响应状态码,可通过Response对象的status_code属性查看。

    import requests
    
    
    if __name__ == '__main__':
        r = requests.get("https://www.baidu.com")
        # 打印状态码
        print(r.status_code)
    

    代码执行后,将打印出所请求URL的状态码:


    状态码

    为方便使用,requests库内置了一个状态码查询对象,将大多数状态码封装起来:
    status_codes.py:

    # -*- coding: utf-8 -*-
    
    r"""
    The ``codes`` object defines a mapping from common names for HTTP statuses
    to their numerical codes, accessible either as attributes or as dictionary
    items.
    
    >>> requests.codes['temporary_redirect']
    307
    >>> requests.codes.teapot
    418
    >>> requests.codes['\o/']
    200
    
    Some codes have multiple names, and both upper- and lower-case versions of
    the names are allowed. For example, ``codes.ok``, ``codes.OK``, and
    ``codes.okay`` all correspond to the HTTP status code 200.
    """
    
    from .structures import LookupDict
    
    _codes = {
    
        # Informational.
        100: ('continue',),
        101: ('switching_protocols',),
        102: ('processing',),
        103: ('checkpoint',),
        122: ('uri_too_long', 'request_uri_too_long'),
        200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/', '✓'),
        201: ('created',),
        202: ('accepted',),
        203: ('non_authoritative_info', 'non_authoritative_information'),
        204: ('no_content',),
        205: ('reset_content', 'reset'),
        206: ('partial_content', 'partial'),
        207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),
        208: ('already_reported',),
        226: ('im_used',),
    
        # Redirection.
        300: ('multiple_choices',),
        301: ('moved_permanently', 'moved', '\\o-'),
        302: ('found',),
        303: ('see_other', 'other'),
        304: ('not_modified',),
        305: ('use_proxy',),
        306: ('switch_proxy',),
        307: ('temporary_redirect', 'temporary_moved', 'temporary'),
        308: ('permanent_redirect',
              'resume_incomplete', 'resume',),  # These 2 to be removed in 3.0
    
        # Client Error.
        400: ('bad_request', 'bad'),
        401: ('unauthorized',),
        402: ('payment_required', 'payment'),
        403: ('forbidden',),
        404: ('not_found', '-o-'),
        405: ('method_not_allowed', 'not_allowed'),
        406: ('not_acceptable',),
        407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'),
        408: ('request_timeout', 'timeout'),
        409: ('conflict',),
        410: ('gone',),
        411: ('length_required',),
        412: ('precondition_failed', 'precondition'),
        413: ('request_entity_too_large',),
        414: ('request_uri_too_large',),
        415: ('unsupported_media_type', 'unsupported_media', 'media_type'),
        416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),
        417: ('expectation_failed',),
        418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'),
        421: ('misdirected_request',),
        422: ('unprocessable_entity', 'unprocessable'),
        423: ('locked',),
        424: ('failed_dependency', 'dependency'),
        425: ('unordered_collection', 'unordered'),
        426: ('upgrade_required', 'upgrade'),
        428: ('precondition_required', 'precondition'),
        429: ('too_many_requests', 'too_many'),
        431: ('header_fields_too_large', 'fields_too_large'),
        444: ('no_response', 'none'),
        449: ('retry_with', 'retry'),
        450: ('blocked_by_windows_parental_controls', 'parental_controls'),
        451: ('unavailable_for_legal_reasons', 'legal_reasons'),
        499: ('client_closed_request',),
    
        # Server Error.
        500: ('internal_server_error', 'server_error', '/o\\', '✗'),
        501: ('not_implemented',),
        502: ('bad_gateway',),
        503: ('service_unavailable', 'unavailable'),
        504: ('gateway_timeout',),
        505: ('http_version_not_supported', 'http_version'),
        506: ('variant_also_negotiates',),
        507: ('insufficient_storage',),
        509: ('bandwidth_limit_exceeded', 'bandwidth'),
        510: ('not_extended',),
        511: ('network_authentication_required', 'network_auth', 'network_authentication'),
    }
    
    codes = LookupDict(name='status_codes')
    
    def _init():
        for code, titles in _codes.items():
            for title in titles:
                setattr(codes, title, code)
                if not title.startswith(('\\', '/')):
                    setattr(codes, title.upper(), code)
    
        def doc(code):
            names = ', '.join('``%s``' % n for n in _codes[code])
            return '* %d: %s' % (code, names)
    
        global __doc__
        __doc__ = (__doc__ + '\n' +
                   '\n'.join(doc(code) for code in sorted(_codes))
                   if __doc__ is not None else None)
    
    _init()
    

    该内置的状态码查询对象,将相关状态码数字关联到相关语义化词语,能够增强代码可读性。

    import requests
    
    
    if __name__ == '__main__':
        r = requests.get("https://www.baidu.com")
        # 查看请求是否成功
        print(r.status_code == requests.codes.ok)
    

    执行:


    状态码查询对象

    三、抛出状态码异常

    如果我们发送了一个错误的请求,比如访问一个返回404的请求:

    404请求
    如果想要通过异常将该状态码抛出,可以使用Response.raise_for_status():
    import requests
    
    
    if __name__ == '__main__':
        r = requests.get("http://httpbin.org/status/404")
        print(r.status_code)
        r.raise_for_status()
    

    执行后可以看到,404异常被抛出。


    抛出状态码异常

    注意:Response.raise_for_status()仅对访问不正确产生的状态码会抛出异常,如果访问状态码为200,则不会有任何异常被抛出:

    image.png

    相关文章

      网友评论

          本文标题:Requests02.响应状态码

          本文链接:https://www.haomeiwen.com/subject/zbctyctx.html