Beispiel #1
0
    def __init__(self, consumer = None, producer = None, token = None):
        if not isinstance(consumer, Consumer):
            raise TypeError
        if not isinstance(producer, Producer):
            raise TypeError
        if not isinstance(token, Token):
            raise TypeError

        self.consumer = consumer
        self.producer = producer
        self.token = token

        self.ua = UserAgent()
Beispiel #2
0
class OAuthAPI(object):
    def __init__(self, consumer = None, producer = None, token = None):
        if not isinstance(consumer, Consumer):
            raise TypeError
        if not isinstance(producer, Producer):
            raise TypeError
        if not isinstance(token, Token):
            raise TypeError

        self.consumer = consumer
        self.producer = producer
        self.token = token

        self.ua = UserAgent()

    def start_authorize(self):
        self.server = SimpleAppServer(self.build_authorizingApp())
        self.server.start()

    def stop_authorize(self):
        self.server.stop()
        self.server = None

    def build_authorizingApp(self):
        authorizing_app = AuthorizingServer(
            consumer = self.consumer,
            producer = self.producer,
            token_file = self.token.file,
        )
        return authorizing_app.to_app

    def setup(self):
        client_id = raw_input('Consumer key: ')
        client_secret = raw_input('Consumer secret: ')
        scope = raw_input('Scope: ')
        new_consumer = Consumer(client_id = client_id, client_secret = client_secret, scope = scope)
        self.consumer = new_consumer

    def call(self, endpoint, request = None, method = 'get'):
        url = self.endpoint+endpoint
        req = self.create_request_object(method, url, request)
        pprint(self.ua.request(req))

    def token_refresh(self):
        param = {
            "grant_type": "refresh_token",
            "client_id": self.consumer.client_id,
            "client_secret": self.consumer.client_secret,
            "refresh_token": self.token.refresh_token,
        }
        new_token = self.ua.post(self.producer.access_token_uri, param)
        self.token.access_token = new_token['access_token']

        self.token.store()

    def create_request_object(self, method, url, request):
        if method == 'get':
            if request is not None:
                params = '?'+urllib.urlencode(request)
                url += params
            req = urllib.request.Request(url)
        else:
            req = urllib.request.Request(url, params)

        req.add_header('Authorization', "%s %s" % ("Bearer", self.access_token))

        print(url)
        return req

    def __del__(self):
        if hasattr(self, "server") and self.server is not None:
            self.stop_authorize()