Пример #1
0
class Connection(object):

    def __init__(self, url, email, token, name='default', version='v1',
                 cache=None):
        self.session = Connection._get_session(email, token)
        self.email = email
        self.base_url = URLObject(url)
        self.api_url = self.base_url.add_path_segment(version)
        self.cache = InMemoryCache() if cache is None else cache
        self.name = name

    def http_method(self, method, url, *args, **kwargs):
        """
        Send HTTP request with `method` to `url`.
        """
        method_fn = getattr(self.session, method)
        return method_fn(url, *args, **kwargs)

    def build_absolute_url(self, path):
        """
        Resolve relative `path` against this connection's API url.
        """
        return url_join(self.api_url, path)

    @staticmethod
    def _get_session(email, token):
        session = requests.Session()
        defaults = {
            'X-PW-Application': 'developer_api',
            'X-PW-AccessToken': token,
            'X-PW-UserEmail': email,
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        }
        session.headers.update(defaults)
        return session

    def __getattr__(self, name):
        """
        Turn HTTP verbs into http_method calls so e.g. conn.get(...) works.

        Note that 'get' and 'delete' are special-cased to handle caching
        """
        methods = 'post', 'put', 'patch', 'options'
        if name in methods:
            return functools.partial(self.http_method, name)
        return super(Connection, self).__getattr__(name)

    def get(self, url, *args, **kwargs):
        cached = self.cache.get(url)
        if cached is None:
            cached = self.http_method('get', url, *args, **kwargs)
            self.cache.set(url, cached, max_age=seconds(minutes=5))
        return cached

    def delete(self, url, *args, **kwargs):
        resp = self.http_method('delete', url, *args, **kwargs)
        if resp.ok:
            self.cache.clear(url)
        return resp
Пример #2
0
 def test_add_path_segment_adds_a_path_segment(self):
     url = URLObject('https://github.com/zacharyvoase/urlobject')
     assert (url.add_path_segment('tree') ==
             'https://github.com/zacharyvoase/urlobject/tree')
     assert (url.add_path_segment('tree/master') ==
             'https://github.com/zacharyvoase/urlobject/tree%2Fmaster')
Пример #3
0
 def test_add_path_segment_adds_a_path_segment(self):
     url = URLObject(u'https://github.com/zacharyvoase/urlobject')
     assert (url.add_path_segment('tree') ==
             u'https://github.com/zacharyvoase/urlobject/tree')
     assert (url.add_path_segment('tree/master') ==
             u'https://github.com/zacharyvoase/urlobject/tree%2Fmaster')