码迷,mamicode.com
首页 > 其他好文 > 详细

requests源码阅读学习笔记

时间:2017-01-07 19:33:56      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:代码   blog   学习笔记   data   源码阅读   optional   url   span   class   

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源码阅读学习笔记

标签:代码   blog   学习笔记   data   源码阅读   optional   url   span   class   

原文地址:http://www.cnblogs.com/alexkn/p/6259900.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!