1
# -*- coding: utf-8 -*-
3
# Copyright 2011 Canonical Ltd.
5
# This program is free software: you can redistribute it and/or modify it
6
# under the terms of the GNU General Public License version 3, as published
7
# by the Free Software Foundation.
9
# This program is distributed in the hope that it will be useful, but
10
# WITHOUT ANY WARRANTY; without even the implied warranties of
11
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
12
# PURPOSE. See the GNU General Public License for more details.
14
# You should have received a copy of the GNU General Public License along
15
# with this program. If not, see <http://www.gnu.org/licenses/>.
16
"""The common bits of a webclient."""
20
from oauth import oauth
21
from twisted.internet import defer
24
class WebClientError(Exception):
25
"""An http error happened while calling the webservice."""
28
class UnauthorizedError(WebClientError):
29
"""The request ended with bad_request, unauthorized or forbidden."""
32
class Response(object):
33
"""A reponse object."""
35
def __init__(self, content, headers=None):
36
"""Initialize this instance."""
37
self.content = content
38
self.headers = headers
41
class BaseWebClient(object):
42
"""The webclient base class, to be extended by backends."""
44
def __init__(self, username=None, password=None):
45
"""Initialize this instance."""
46
self.username = username
47
self.password = password
49
def request(self, url, method="GET", extra_headers=None,
50
oauth_credentials=None):
51
"""Return a deferred that will be fired with a Response object."""
52
raise NotImplementedError
54
def get_timestamp(self):
55
"""Get a timestamp synchronized with the server."""
56
# pylint: disable=W0511
57
# TODO: get the synchronized timestamp
58
return defer.succeed(time.time())
61
def build_oauth_headers(method, url, credentials, timestamp):
62
"""Build an oauth request given some credentials."""
63
consumer = oauth.OAuthConsumer(credentials["consumer_key"],
64
credentials["consumer_secret"])
65
token = oauth.OAuthToken(credentials["token"],
66
credentials["token_secret"])
69
parameters["oauth_timestamp"] = timestamp
70
request = oauth.OAuthRequest.from_consumer_and_token(
73
parameters=parameters,
74
oauth_consumer=consumer,
76
sig_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
77
request.sign_request(sig_method, consumer, token)
78
return request.to_header()
81
"""Shut down all pending requests (if possible)."""