requests源码阅读学习笔记

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了requests源码阅读学习笔记相关的知识,希望对你有一定的参考价值。

0:此文并不想拆requests的功能,目的仅仅只是让自己以后写的代码更pythonic.可能会涉及到一部分requests的功能模块,但全看心情。

1.另一种类的初始化方式

class Request(object):
    """The :class:`Request` object. It carries out all functionality of
    Requests. Recommended interface is with the Requests functions.
    
    """
    
    _METHODS = (GET, HEAD, PUT, POST, DELETE)
    
    def __init__(self):
        self.url = None
        self.headers = dict()
        self.method = None
        self.params = {}
        self.data = {}
        self.response = Response()
        self.auth = None
        self.sent = False
        
    def __repr__(self):
        try:
            repr = <Request [%s]> % (self.method)
        except:
            repr = <Request object>
        return repr
    
    def __setattr__(self, name, value):
        if (name == method) and (value):
            if not value in self._METHODS:
                raise InvalidMethod()
        
        object.__setattr__(self, name, value)
def get(url, params={}, headers={}, auth=None):
    """Sends a GET request. Returns :class:`Response` object.
    :param url: URL for the new :class:`Request` object.
    :param params: (optional) Dictionary of GET Parameters to send with the :class:`Request`.
    :param headers: (optional) Dictionary of HTTP Headers to sent with the :class:`Request`.
    :param auth: (optional) AuthObject to enable Basic HTTP Auth.
    """
    
    r = Request()
    
    r.method = GET
    r.url = url
    r.params = params
    r.headers = headers
    r.auth = _detect_auth(url, auth)
    
    r.send()
    
    return r.response

2.**kwargs:用于大量参数在方法间的传递,不需要自己每次都初始化一个dict用来传参

def get(url, params={}, headers={}, cookies=None, auth=None):
    return request(GET, url, params=params, headers=headers, cookiejar=cookies, auth=auth)

def request(method, url, **kwargs):
    data = kwargs.pop(data, dict()) or kwargs.pop(params, dict())

    r = Request(method=method, url=url, data=data, headers=kwargs.pop(headers, {}),
                cookiejar=kwargs.pop(cookies, None), files=kwargs.pop(files, None),
                auth=kwargs.pop(auth, auth_manager.get_auth(url)))
    r.send()

    return r.response

 

以上是关于requests源码阅读学习笔记的主要内容,如果未能解决你的问题,请参考以下文章

Go学习笔记02-源码

Spring源码学习笔记

Spring源码学习笔记

Spring源码学习笔记

Spring源码学习笔记

Spring源码学习笔记