|
#!/bin/env python |
|
# -*- coding: utf-8 -*- |
|
""" |
|
OAUTH CONSUMER |
|
-------------- |
|
Consume an API that uses OAuth. |
|
|
|
|
|
Copyright (c) 2014 T. Zengerink |
|
|
|
Permission is hereby granted, free of charge, to any person obtaining |
|
a copy of this software and associated documentation files (the |
|
"Software"), to deal in the Software without restriction, including |
|
without limitation the rights to use, copy, modify, merge, publish, |
|
distribute, sublicense, and/or sell copies of the Software, and to |
|
permit persons to whom the Software is furnished to do so, subject to |
|
the following conditions: |
|
|
|
The above copyright notice and this permission notice shall be |
|
included in all copies or substantial portions of the Software. |
|
|
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, |
|
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF |
|
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND |
|
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE |
|
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION |
|
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION |
|
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
|
""" |
|
import ConfigParser, json, sys |
|
from rauth import OAuth1Service, OAuth1Session |
|
|
|
|
|
class Api(object): |
|
|
|
def __init__(self, service, session, key_manager): |
|
self.service = service |
|
self.key_manager = key_manager |
|
self.session = session |
|
self.request_token, self.request_secret = self.get_request_tokens() |
|
self.access_token, self.access_secret = self.get_access_tokens() |
|
|
|
def execute(self, *args, **kwargs): |
|
method = getattr(self.session, args[0]) |
|
data = json.loads(args[2]) if len(args) is 3 else {} |
|
return method('%s%s' % (self.service.base_url, args[1]), |
|
headers={'Content-Type': 'application/json'}, |
|
data=data) |
|
|
|
def get_access_tokens(self): |
|
access_token, access_secret = self.key_manager.get() |
|
if not access_token or not access_secret: |
|
access_token, access_secret = self.service.get_access_token( |
|
self.request_token, |
|
self.request_secret, |
|
method='POST', |
|
header_auth=True, |
|
data={'oauth_verifier':self.get_verifier()}) |
|
self.key_manager.set(access_token, access_secret) |
|
self.session.access_token=access_token |
|
self.session.access_token_secret=access_secret |
|
return access_token, access_secret |
|
|
|
def get_verifier(self): |
|
print(self.service.get_authorize_url(self.request_token)) |
|
return raw_input('Enter authorization code: ') |
|
|
|
def get_request_tokens(self): |
|
return self.service.get_request_token(method='POST', header_auth=True) |
|
|
|
|
|
class Config(dict): |
|
|
|
def __init__(self): |
|
filename = 'service.cnf' |
|
config = ConfigParser.ConfigParser() |
|
config.read(filename) |
|
try: |
|
self.update(dict(config.items('service'))) |
|
except ConfigParser.NoSectionError: |
|
raise Exception('Could not read configuration \'%s\'' % filename) |
|
|
|
|
|
class KeyManager(object): |
|
|
|
def __init__(self): |
|
self.filename = 'keys.cnf' |
|
|
|
def get(self): |
|
str = self.read_file() |
|
if str: |
|
return str.split(':') |
|
return None, None |
|
|
|
def read_file(self): |
|
try: |
|
f = open(self.filename, 'r') |
|
str = f.read() |
|
f.close() |
|
except IOError: |
|
str = '' |
|
return str |
|
|
|
def set(self, token, secret): |
|
self.write_file('%s:%s' % (token, secret)) |
|
|
|
def write_file(self, str): |
|
f = open(self.filename, 'w') |
|
f.write(str) |
|
f.close() |
|
return str |
|
|
|
|
|
def main(args): |
|
config = Config() |
|
session = OAuth1Session(consumer_key=config.get('consumer_key'), |
|
consumer_secret=config.get('consumer_secret')) |
|
api = Api(OAuth1Service(**config), session, KeyManager()) |
|
print(json.dumps(api.execute(*args).json())) |
|
|
|
|
|
if __name__ == '__main__': |
|
if len(sys.argv) > 1: |
|
main(sys.argv[1:]) |
|
else: |
|
print('Usage: %s %s %s %s' % (sys.argv[0], '[http method]', '[uri]', |
|
'[data]')) |