Here are the examples of the python api requests_oauthlib.OAuth1 taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
104 Examples
3
Example 1
Project: impactstory-tng Source File: views.py
@app.route("/api/auth/twitter/request-token")
def get_twitter_request_token():
request_token_url = 'https://api.twitter.com/oauth/request_token'
oauth = OAuth1(
os.getenv('TWITTER_CONSUMER_KEY'),
client_secret=os.getenv('TWITTER_CONSUMER_SECRET'),
callback_uri=request.args.get('redirectUri')
)
r = requests.post(request_token_url, auth=oauth)
oauth_token_dict = dict(parse_qsl(r.text))
return jsonify(oauth_token_dict)
3
Example 2
Project: firefox-flicks Source File: vimeo.py
def _vimeo_request(vimeo_method, request_method, **data):
oauth = OAuth1(settings.VIMEO_CLIENT_KEY,
client_secret=settings.VIMEO_CLIENT_SECRET,
resource_owner_key=settings.VIMEO_RESOURCE_OWNER_KEY,
resource_owner_secret=settings.VIMEO_RESOURCE_OWNER_SECRET)
url = 'http://vimeo.com/api/rest/v2?method={0}'.format(vimeo_method)
data['format'] = 'json'
try:
response = requests.request(request_method, url, auth=oauth, data=data)
except requests.RequestException, e:
logger.error(u'Error connecting to Vimeo: {0}'.format(e))
raise VimeoServiceError(e)
return response.json()
3
Example 3
Project: crawlers Source File: setup.py
def get_oauth1(keys):
if not keys['oauth_token']:
keys['oauth_token'], keys['oauth_token_secret']\
= setup_oauth1(keys)
print '\nInput the keys below to twitter/settings.py'
import pprint; pprint.pprint(keys)
import sys; sys.exit()
oauth = OAuth1(keys['consumer_key'],
client_secret=keys['consumer_secret'],
resource_owner_key=keys['oauth_token'],
resource_owner_secret=keys['oauth_token_secret'])
return oauth
3
Example 4
Project: pyxero Source File: auth.py
def _init_oauth(self, oauth_token, oauth_token_secret):
"Store and initialize a verified set of OAuth credentials"
self.oauth_token = oauth_token
self.oauth_token_secret = oauth_token_secret
self._oauth = OAuth1(
self.consumer_key,
client_secret=self.consumer_secret,
resource_owner_key=self.oauth_token,
resource_owner_secret=self.oauth_token_secret,
rsa_key=self.rsa_key,
signature_method=self._signature_method
)
3
Example 5
Project: django-channels Source File: twitter.py
def send(self, message, fail_silently=False, options=None):
payload = {
"status": message
}
self._set_payload_from_options(payload, options, "twitter", [
"in_reply_to_status_id", "possibly_sensitive", "lat", "long",
"place_id", "display_coordinates", "trim_user", "media_ids"])
auth = OAuth1(self.api_key, self.api_secret, self.access_token,
self.access_token_secret)
try:
response = requests.post(self.url, auth=auth, data=payload)
if response.status_code != requests.codes.ok:
raise HttpError(response.status_code, response.text)
except:
if not fail_silently:
raise
3
Example 6
def _get_access_token(self, request_token):
"""Retrieve the access token if OAuth hybrid was used"""
oauth = OAuth1(
self.oauth_key,
client_secret=self.oauth_secret,
resource_owner_key=request_token)
resp = requests.post(GOOGLE_OAUTH, auth=oauth)
if resp.status_code != 200:
log.error(
'OAuth token validation failed. Status: %d, Content: %s',
resp.status_code, resp.content)
else:
access_token = dict(parse_qsl(resp.text))
return {
'oauthAccessToken': access_token['oauth_token'],
'oauthAccessTokenSecret': access_token['oauth_token_secret'],
}
3
Example 7
Project: ask-alexa-pykit Source File: twitter.py
def get_request_token(callback_url=None):
url = "https://api.twitter.com/oauth/request_token"
consumer_key, consumer_secret = local_cache.get_server_state()['twitter_keys']
auth = OAuth1(consumer_key, consumer_secret)
params = { "oauth_callback" : callback_url }
r = requests.post(url, auth=auth, params=params)
response_obj = parse_qs(r.text)
local_cache.update_server_state({ "request_token" : response_obj['oauth_token'][0],
"request_secret": response_obj['oauth_token_secret'][0] })
return response_obj['oauth_token_secret'], response_obj['oauth_token']
3
Example 8
def request(self, method, url, **kwargs):
"Build remote url request. Constructs necessary auth."
user_token = kwargs.pop('token', self.token)
token, secret = self.parse_raw_token(user_token)
callback = kwargs.pop('oauth_callback', None)
verifier = kwargs.get('data', {}).pop('oauth_verifier', None)
oauth = OAuth1(
resource_owner_key=token,
resource_owner_secret=secret,
client_key=self.provider.consumer_key,
client_secret=self.provider.consumer_secret,
verifier=verifier,
callback_uri=callback,
)
kwargs['auth'] = oauth
return super(OAuthClient, self).request(method, url, **kwargs)
3
Example 9
Project: my-weather-indicator Source File: wyahooapi.py
def __init__(self,
longitude=-0.418,
latitude=39.360,
units=weatherservice.Units()):
WeatherService.__init__(self, longitude, latitude, units)
self.oauth = OAuth1(API_KEY, SHARED_SECRET)
self.woeid = geocodeapi.get_woeid(latitude, longitude)
3
Example 10
Project: ion Source File: notifications.py
def notify_twitter(status):
url = 'https://api.twitter.com/1.1/statuses/update.json'
cfg = settings.TWITTER_KEYS
if not cfg:
return False
auth = OAuth1(cfg["consumer_key"], cfg["consumer_secret"], cfg["access_token_key"], cfg["access_token_secret"])
data = {"status": status}
req = requests.post(url, data=data, auth=auth)
return req.text
3
Example 11
Project: feedhq Source File: forms.py
def check_xauth(self, key, secret, token_url):
"""Check a generic xAuth provider"""
auth = OAuth1(key, secret)
params = {
'x_auth_username': self.cleaned_data['username'],
'x_auth_password': self.cleaned_data['password'],
'x_auth_mode': 'client_auth',
}
response = requests.post(token_url, auth=auth, data=params)
if response.status_code != 200:
raise forms.ValidationError(
_("Unable to verify your %s credentials. Please double-check "
"and try again") % self.service,
)
request_token = dict(urlparse.parse_qsl(response.text))
self.user.read_later_credentials = json.dumps(request_token)
3
Example 12
def __init__(self, server_address, consumer_key,
token_key, token_secret):
"""
Arguments:
server_address: maas server ip/hostname
consumer_key: maas consumer key for authenticated maas user
token_key: user token
token_secret: user token secret
"""
self.api_url = "http://{}:5240/MAAS/api/{}".format(server_address,
self.API_VERSION)
self.oauth = OAuth1(consumer_key,
resource_owner_key=token_key,
resource_owner_secret=token_secret,
signature_method='PLAINTEXT')
3
Example 13
Project: oauth-dropins Source File: twitter_auth.py
def auth_header(url, token_key, token_secret, method='GET'):
"""Generates an Authorization header and returns it in a header dict.
Args:
url: string
token_key: string
token_secret: string
method: string
Returns: single element dict with key 'Authorization'
"""
oauth1 = requests_oauthlib.OAuth1(
client_key=appengine_config.TWITTER_APP_KEY,
client_secret=appengine_config.TWITTER_APP_SECRET,
resource_owner_key=token_key,
resource_owner_secret=token_secret,
)
req = requests.Request(method=method, url=url, auth=oauth1).prepare()
return req.headers
3
Example 14
def refresh(self):
"Refresh an expired token"
# Construct the credentials for the verification request
oauth = OAuth1(
self.consumer_key,
client_secret=self.consumer_secret,
resource_owner_key=self.oauth_token,
resource_owner_secret=self.oauth_token_secret,
rsa_key=self.rsa_key,
signature_method=self._signature_method
)
# Make the verification request, getting back an access token
params = {'oauth_session_handle': self.oauth_session_handle}
response = requests.post(url=self.base_url + ACCESS_TOKEN_URL,
params=params, auth=oauth, cert=self.client_cert)
self._process_oauth_response(response)
3
Example 15
Project: requests-oauthlib Source File: test_core.py
def testCanPostBinaryData(self, generate_nonce, generate_timestamp):
"""
Test we can post binary data. Should prevent regression of the
UnicodeDecodeError issue.
"""
generate_nonce.return_value = 'abc'
generate_timestamp.return_value = '1'
oauth = requests_oauthlib.OAuth1('client_key')
dirname = os.path.dirname(__file__)
fname = os.path.join(dirname, 'test.bin')
with open(fname, 'rb') as f:
r = requests.post('http://httpbin.org/post', data={'hi': 'there'},
files={'media': (os.path.basename(f.name), f)},
headers={'content-type':'application/octet-stream'},
auth=oauth)
self.assertEqual(r.status_code, 200)
3
Example 16
Project: redwind Source File: twitter.py
def get_auth():
return OAuth1(
client_key=get_settings().twitter_api_key,
client_secret=get_settings().twitter_api_secret,
resource_owner_key=get_settings().twitter_oauth_token,
resource_owner_secret=get_settings().twitter_oauth_token_secret)
3
Example 17
def login(self, request):
"""Initiate a Twitter login"""
# grab the initial request token
oauth = OAuth1(
self.consumer_key,
client_secret=self.consumer_secret,
callback_uri=request.route_url(self.callback_route))
resp = requests.post(REQUEST_URL, auth=oauth)
if resp.status_code != 200:
raise ThirdPartyFailure("Status %s: %s" % (
resp.status_code, resp.content))
request_token = dict(parse_qsl(resp.text))
# store the token for later
request.session['velruse.token'] = request_token
# redirect the user to authorize the app
auth_url = flat_url(AUTH_URL, oauth_token=request_token['oauth_token'])
return HTTPFound(location=auth_url)
3
Example 18
def request(self, method, url, **kwargs):
"""Build remote url request. Constructs necessary auth."""
user_token = kwargs.pop('token', self.token)
token, secret, _ = self.parse_raw_token(user_token)
callback = kwargs.pop('oauth_callback', None)
verifier = kwargs.get('data', {}).pop('oauth_verifier', None)
oauth = OAuth1(
resource_owner_key=token,
resource_owner_secret=secret,
client_key=self.consumer_key,
client_secret=self.consumer_secret,
verifier=verifier,
callback_uri=callback,
)
kwargs['auth'] = oauth
return super(OAuthProvider, self).request(method, url, **kwargs)
3
Example 19
Project: requests-oauthlib Source File: test_core.py
def test_url_is_native_str(self, generate_nonce, generate_timestamp):
"""
Test that the URL is always a native string.
"""
generate_nonce.return_value = 'abc'
generate_timestamp.return_value = '1'
oauth = requests_oauthlib.OAuth1('client_key')
r = requests.get('http://httpbin.org/get', auth=oauth)
self.assertTrue(isinstance(r.request.url, str))
3
Example 20
def oauth_auth(self, token=None, oauth_verifier=None,
signature_type=SIGNATURE_TYPE_AUTH_HEADER):
key, secret = self.get_key_and_secret()
oauth_verifier = oauth_verifier or self.data.get('oauth_verifier')
token = token or {}
# decoding='utf-8' produces errors with python-requests on Python3
# since the final URL will be of type bytes
decoding = None if six.PY3 else 'utf-8'
state = self.get_or_create_state()
return OAuth1(key, secret,
resource_owner_key=None,
resource_owner_secret=None,
callback_uri=self.get_redirect_uri(state),
verifier=oauth_verifier,
signature_type=signature_type,
decoding=decoding)
3
Example 21
Project: python-social-auth Source File: khanacademy.py
def oauth_auth(self, token=None, oauth_verifier=None):
key, secret = self.get_key_and_secret()
oauth_verifier = oauth_verifier or self.data.get('oauth_verifier')
token = token or {}
# decoding='utf-8' produces errors with python-requests on Python3
# since the final URL will be of type bytes
decoding = None if six.PY3 else 'utf-8'
state = self.get_or_create_state()
return OAuth1(key, secret,
resource_owner_key=token.get('oauth_token'),
resource_owner_secret=token.get('oauth_token_secret'),
callback_uri=self.get_redirect_uri(state),
verifier=oauth_verifier,
signature_method=SIGNATURE_HMAC,
signature_type=SIGNATURE_TYPE_QUERY,
decoding=decoding)
3
Example 22
def get_request_kwargs(self, api_params, *args, **kwargs):
params = super(TwitterClientAdapter, self).get_request_kwargs(
api_params, *args, **kwargs)
params['auth'] = OAuth1(api_params.get('api_key'),
client_secret=api_params.get('api_secret'),
resource_owner_key=api_params.get('access_token', ''),
resource_owner_secret=api_params.get('access_token_secret', ''))
return params
3
Example 23
Project: requests-oauthlib Source File: test_core.py
def test_content_type_override(self, generate_nonce, generate_timestamp):
"""
Content type should only be guessed if none is given.
"""
generate_nonce.return_value = 'abc'
generate_timestamp.return_value = '1'
oauth = requests_oauthlib.OAuth1('client_key')
data = 'a'
r = requests.post('http://httpbin.org/get', data=data, auth=oauth)
self.assertEqual(r.request.headers.get('Content-Type'),
'application/x-www-form-urlencoded')
r = requests.post('http://httpbin.org/get', auth=oauth, data=data,
headers={'Content-type': 'application/json'})
self.assertEqual(r.request.headers.get('Content-Type'),
'application/json')
3
Example 24
def do_search(term='Food', location='San Francisco'):
base_url = 'https://api.yelp.com/v2/search'
term = term.replace(' ', '+')
location = location.replace(' ', '+')
url = "{base_url}?term={term}&location={location}".format(base_url=base_url,
term=term,
location=location)
auth = OAuth1(consumer_key,
consumer_secret,
token,
token_secret)
r = requests.get(url, auth=auth)
return r.json(), r.text
3
Example 25
Project: BitBucket-api Source File: bitbucket.py
def finalize_oauth(self, access_token, access_token_secret):
""" Called internally once auth process is complete. """
self.access_token = access_token
self.access_token_secret = access_token_secret
# Final OAuth object
self.oauth = OAuth1(
self.consumer_key,
client_secret=self.consumer_secret,
resource_owner_key=self.access_token,
resource_owner_secret=self.access_token_secret)
3
Example 26
def oauth_client(self, service):
service_settings = getattr(settings, service.upper())
creds = json.loads(self.user.read_later_credentials)
auth = OAuth1(service_settings['CONSUMER_KEY'],
service_settings['CONSUMER_SECRET'],
creds['oauth_token'],
creds['oauth_token_secret'])
return auth
3
Example 27
def authenticate(self):
"""
Write a custom auth property where we grab the auth token and put it in
the headers
"""
from requests_oauthlib import OAuth1
auth = OAuth1(self.app_key, self.app_secret, self.oauth_token,
self.oauth_token_secret)
return auth
3
Example 28
def get_request_token(self, callback=None):
"The first step of the OAuth workflow."
oauth = OAuth1(self._client.token,
client_secret=self._client.secret,
callback_uri=callback,
signature_method=SIGNATURE_PLAINTEXT)
r = requests.post(urlparse.urljoin(
self.url, 'oauth/request_token/'), auth=oauth)
credentials = urlparse.parse_qs(r.text)
self.__request = OAuthToken(credentials.get('oauth_token')[0],
credentials.get(
'oauth_token_secret')[0])
return self.__request
3
Example 29
def __init__(self, consumer_key, rsa_key):
self.consumer_key = consumer_key
self.rsa_key = rsa_key
self.base_url = XERO_BASE_URL
# Private API uses consumer key as the OAuth token.
self.oauth_token = consumer_key
self.oauth = OAuth1(
self.consumer_key,
resource_owner_key=self.oauth_token,
rsa_key=self.rsa_key,
signature_method=SIGNATURE_RSA,
signature_type=SIGNATURE_TYPE_AUTH_HEADER,
)
3
Example 30
def _get_access_token(self, request_token):
oauth = OAuth1(
self.oauth_key,
client_secret=self.oauth_secret,
resource_owner_key=request_token)
resp = requests.post(YAHOO_OAUTH, auth=oauth)
if resp.status_code != 200:
log.error(
'OAuth token validation failed. Status: %d, Content: %s',
resp.status_code, resp.content)
else:
access_token = dict(parse_qsl(resp.text))
return {
'oauthAccessToken': access_token['oauth_token'],
'oauthAccessTokenSecret': access_token['oauth_token_secret'],
}
3
Example 31
def verify(self, verifier):
"Verify an OAuth token"
# Construct the credentials for the verification request
oauth = OAuth1(
self.consumer_key,
client_secret=self.consumer_secret,
resource_owner_key=self.oauth_token,
resource_owner_secret=self.oauth_token_secret,
verifier=verifier,
rsa_key=self.rsa_key,
signature_method=self._signature_method
)
# Make the verification request, gettiung back an access token
url = self.base_url + ACCESS_TOKEN_URL
response = requests.post(url=url, auth=oauth, cert=self.client_cert)
self._process_oauth_response(response)
self.verified = True
3
Example 32
def login(self, request):
"""Initiate a bitbucket login"""
# grab the initial request token
oauth = OAuth1(
self.consumer_key,
client_secret=self.consumer_secret,
callback_uri=request.route_url(self.callback_route))
resp = requests.post(REQUEST_URL, auth=oauth)
if resp.status_code != 200:
raise ThirdPartyFailure("Status %s: %s" % (
resp.status_code, resp.content))
request_token = dict(parse_qsl(resp.text))
# store the token for later
request.session['velruse.token'] = request_token
# redirect the user to authorize the app
auth_url = flat_url(AUTH_URL, oauth_token=request_token['oauth_token'])
return HTTPFound(location=auth_url)
3
Example 33
Project: impactstory-tng Source File: twitter.py
def get_twitter_creds(twitter_token, twitter_verifier):
access_token_url = 'https://api.twitter.com/oauth/access_token'
auth = OAuth1(os.getenv('TWITTER_CONSUMER_KEY'),
client_secret=os.getenv('TWITTER_CONSUMER_SECRET'),
resource_owner_key=twitter_token,
verifier=twitter_verifier)
r = requests.post(access_token_url, auth=auth)
twitter_creds = dict(parse_qsl(r.text))
print u"got back twitter_creds from twitter {}".format(twitter_creds)
return twitter_creds
3
Example 34
def __init__(self, credentials):
self.credentials = credentials
self.oauth = OAuth1(credentials.consumer_key,
credentials.consumer_secret,
credentials.access_token,
credentials.access_token_secret,
signature_type='query')
self.client = requests.Session()
self.client.auth = self.oauth
self.client.params.update({'userid': credentials.user_id})
3
Example 35
def __init__(self, *a, **kw):
super(Twitter, self).__init__(*a, **kw)
self.session.auth = OAuth1(
config['twitter']['consumer_key'],
config['twitter']['consumer_secret'],
config['twitter']['access_token'],
config['twitter']['access_secret'],
signature_type='auth_header'
)
3
Example 36
def login(self, request):
"""Initiate a LinkedIn login"""
# grab the initial request token
oauth = OAuth1(
self.consumer_key,
client_secret=self.consumer_secret,
callback_uri=request.route_url(self.callback_route))
resp = requests.post(REQUEST_URL, auth=oauth)
if resp.status_code != 200:
raise ThirdPartyFailure("Status %s: %s" % (
resp.status_code, resp.content))
request_token = dict(parse_qsl(resp.text))
# store the token for later
request.session['velruse.token'] = request_token
# redirect the user to authorize the app
auth_url = flat_url(AUTH_URL, oauth_token=request_token['oauth_token'])
return HTTPFound(location=auth_url)
3
Example 37
def call_api_method(http_method, flickr_method, params,
token=None, secret=None, site=None):
auth = OAuth1(
client_key=current_app.config['FLICKR_CLIENT_KEY'],
client_secret=current_app.config['FLICKR_CLIENT_SECRET'],
resource_owner_key=token or site.token or site.account.token,
resource_owner_secret=secret or site.token_secret or
site.account.token_secret)
full_params = {
'nojsoncallback': 1,
'format': 'json',
'method': flickr_method,
}
full_params.update(params)
return requests.request(http_method, API_URL, params=full_params,
auth=auth)
3
Example 38
def apply_auth(self):
return OAuth1(self.consumer_key,
client_secret=self.consumer_secret,
resource_owner_key=self.access_token,
resource_owner_secret=self.access_token_secret,
decoding=None)
3
Example 39
def _do_request(self, *args, **kwargs):
if not self._access.is_valid():
raise APIError('You must obtain an access token'
'before making API calls.')
# Add the OAuth parameters.
kwargs['auth'] = OAuth1(self._client.token,
client_secret=self._client.secret,
resource_owner_key=self._access.token,
resource_owner_secret=self._access.secret,
signature_method=SIGNATURE_PLAINTEXT)
return super(OAuthClient, self)._do_request(*args, **kwargs)
3
Example 40
Project: givinggraph Source File: config.py
def get_twitter_authentication():
"""Return the OAuth token for Twitter's API."""
return OAuth1(read_config('twitter', 'client_key'),
client_secret=read_config('twitter', 'client_secret'),
resource_owner_key=read_config('twitter', 'resource_owner_key'),
resource_owner_secret=read_config('twitter', 'resource_owner_secret'))
2
Example 41
Project: requests-oauthlib Source File: test_core.py
def test_register_client_class(self, generate_timestamp, generate_nonce):
class ClientSubclass(oauthlib.oauth1.Client):
pass
self.assertTrue(hasattr(requests_oauthlib.OAuth1, 'client_class'))
self.assertEqual(
requests_oauthlib.OAuth1.client_class,
oauthlib.oauth1.Client)
normal = requests_oauthlib.OAuth1('client_key')
self.assertTrue(isinstance(normal.client, oauthlib.oauth1.Client))
self.assertFalse(isinstance(normal.client, ClientSubclass))
requests_oauthlib.OAuth1.client_class = ClientSubclass
self.assertEqual(requests_oauthlib.OAuth1.client_class, ClientSubclass)
custom = requests_oauthlib.OAuth1('client_key')
self.assertTrue(isinstance(custom.client, oauthlib.oauth1.Client))
self.assertTrue(isinstance(custom.client, ClientSubclass))
overridden = requests_oauthlib.OAuth1('client_key',
client_class = oauthlib.oauth1.Client)
self.assertTrue(isinstance(overridden.client, oauthlib.oauth1.Client))
self.assertFalse(isinstance(normal.client, ClientSubclass))
0
Example 42
def get(self, endpoint, process_response=True, **params):
"""
Performs an HTTP GET from the specified endpoint (API path),
passing parameters if given.
The api_version is prepended to the endpoint,
if it was specified when the Trovebox object was created.
Returns the decoded JSON dictionary, and raises exceptions if an
error code is received.
Returns the raw response if process_response=False
"""
params = self._process_params(params)
url = self._construct_url(endpoint)
if self.auth.consumer_key:
auth = requests_oauthlib.OAuth1(self.auth.consumer_key,
self.auth.consumer_secret,
self.auth.token,
self.auth.token_secret)
else:
auth = None
with requests.Session() as session:
session.verify = self.config["ssl_verify"]
response = session.get(url, params=params, auth=auth)
self._logger.info("============================")
self._logger.info("GET %s" % url)
self._logger.info("---")
self._logger.info(response.text[:1000])
if len(response.text) > 1000: # pragma: no cover
self._logger.info("[Response truncated to 1000 characters]")
self.last_url = url
self.last_params = params
self.last_response = response
if process_response:
return self._process_response(response)
else:
if 200 <= response.status_code < 300:
return response.text
else:
raise TroveboxError("HTTP Error %d: %s" %
(response.status_code, response.reason))
0
Example 43
Project: requests-oauthlib Source File: test_core.py
def testNonFormEncoded(self, generate_nonce, generate_timestamp):
"""OAuth signature only depend on body if it is form encoded."""
generate_nonce.return_value = 'abc'
generate_timestamp.return_value = '1'
oauth = requests_oauthlib.OAuth1('client_key')
r = requests.Request(method='POST', url='http://a.b/path?query=retain',
auth=oauth, data='this really is not form encoded')
a = r.prepare()
r = requests.Request(method='POST', url='http://a.b/path?query=retain',
auth=oauth)
b = r.prepare()
self.assertEqual(a.headers.get('Authorization'),
b.headers.get('Authorization'))
r = requests.Request(method='POST', url='http://a.b/path?query=retain',
auth=oauth, files={'test': StringIO('hello')})
c = r.prepare()
self.assertEqual(b.headers.get('Authorization'),
c.headers.get('Authorization'))
0
Example 44
def get_access_token(self):
"""
Obtain the access token to access private resources at the API
endpoint.
"""
if self.access_token is None:
request_token = self._get_rt_from_session()
oauth = OAuth1(
self.consumer_key,
client_secret=self.consumer_secret,
resource_owner_key=request_token['oauth_token'],
resource_owner_secret=request_token['oauth_token_secret'])
at_url = self.access_token_url
# Passing along oauth_verifier is required according to:
# http://groups.google.com/group/twitter-development-talk/browse_frm/thread/472500cfe9e7cdb9#
# Though, the custom oauth_callback seems to work without it?
oauth_verifier = get_request_param(self.request, 'oauth_verifier')
if oauth_verifier:
at_url = at_url + '?' + urlencode(
{'oauth_verifier': oauth_verifier})
response = requests.post(url=at_url, auth=oauth)
if response.status_code not in [200, 201]:
raise OAuthError(
_('Invalid response while obtaining access token'
' from "%s".') % get_token_prefix(
self.request_token_url))
self.access_token = dict(parse_qsl(response.text))
self.request.session['oauth_%s_access_token' % get_token_prefix(
self.request_token_url)] = self.access_token
return self.access_token
0
Example 45
Project: openphoto-python Source File: http.py
def post(self, endpoint, process_response=True, files=None, **params):
"""
Performs an HTTP POST to the specified endpoint (API path),
passing parameters if given.
The api_version is prepended to the endpoint,
if it was specified when the Trovebox object was created.
Returns the decoded JSON dictionary, and raises exceptions if an
error code is received.
Returns the raw response if process_response=False
"""
params = self._process_params(params)
url = self._construct_url(endpoint)
if not self.auth.consumer_key:
raise TroveboxError("Cannot issue POST without OAuth tokens")
auth = requests_oauthlib.OAuth1(self.auth.consumer_key,
self.auth.consumer_secret,
self.auth.token,
self.auth.token_secret)
with requests.Session() as session:
session.verify = self.config["ssl_verify"]
if files:
# Need to pass parameters as URL query, so they get OAuth signed
response = session.post(url, params=params,
files=files, auth=auth)
else:
# Passing parameters as URL query doesn't work
# if there are no files to send.
# Send them as form data instead.
response = session.post(url, data=params, auth=auth)
self._logger.info("============================")
self._logger.info("POST %s" % url)
self._logger.info("params: %s" % repr(params))
if files:
self._logger.info("files: %s" % repr(files))
self._logger.info("---")
self._logger.info(response.text[:1000])
if len(response.text) > 1000: # pragma: no cover
self._logger.info("[Response truncated to 1000 characters]")
self.last_url = url
self.last_params = params
self.last_response = response
if process_response:
return self._process_response(response)
else:
if 200 <= response.status_code < 300:
return response.text
else:
raise TroveboxError("HTTP Error %d: %s" %
(response.status_code, response.reason))
0
Example 46
Project: jira Source File: jirashell.py
def oauth_dance(server, consumer_key, key_cert_data, print_tokens=False, verify=None):
if verify is None:
verify = server.startswith('https')
# step 1: get request tokens
oauth = OAuth1(
consumer_key, signature_method=SIGNATURE_RSA, rsa_key=key_cert_data)
r = requests.post(
server + '/plugins/servlet/oauth/request-token', verify=verify, auth=oauth)
request = dict(parse_qsl(r.text))
request_token = request['oauth_token']
request_token_secret = request['oauth_token_secret']
if print_tokens:
print("Request tokens received.")
print(" Request token: {}".format(request_token))
print(" Request token secret: {}".format(request_token_secret))
# step 2: prompt user to validate
auth_url = '{}/plugins/servlet/oauth/authorize?oauth_token={}'.format(
server, request_token)
if print_tokens:
print(
"Please visit this URL to authorize the OAuth request:\n\t{}".format(auth_url))
else:
webbrowser.open_new(auth_url)
print(
"Your browser is opening the OAuth authorization for this client session.")
approved = input(
'Have you authorized this program to connect on your behalf to {}? (y/n)'.format(server))
if approved.lower() != 'y':
exit(
'Abandoning OAuth dance. Your partner faceplants. The audience boos. You feel shame.')
# step 3: get access tokens for validated user
oauth = OAuth1(consumer_key,
signature_method=SIGNATURE_RSA,
rsa_key=key_cert_data,
resource_owner_key=request_token,
resource_owner_secret=request_token_secret
)
r = requests.post(
server + '/plugins/servlet/oauth/access-token', verify=verify, auth=oauth)
access = dict(parse_qsl(r.text))
if print_tokens:
print("Access tokens received.")
print(" Access token: {}".format(access['oauth_token']))
print(" Access token secret: {}".format(
access['oauth_token_secret']))
return {
'access_token': access['oauth_token'],
'access_token_secret': access['oauth_token_secret'],
'consumer_key': consumer_key,
'key_cert': key_cert_data}
0
Example 47
def __init__(self, app_key=None, app_secret=None, oauth_token=None,
oauth_token_secret=None, access_token=None,
token_type='bearer', oauth_version=1, api_version='1.1',
client_args=None, auth_endpoint='authenticate'):
"""Instantiates an instance of Twython. Takes optional parameters for
authentication and such (see below).
:param app_key: (optional) Your applications key
:param app_secret: (optional) Your applications secret key
:param oauth_token: (optional) When using **OAuth 1**, combined with
oauth_token_secret to make authenticated calls
:param oauth_token_secret: (optional) When using **OAuth 1** combined
with oauth_token to make authenticated calls
:param access_token: (optional) When using **OAuth 2**, provide a
valid access token if you have one
:param token_type: (optional) When using **OAuth 2**, provide your
token type. Default: bearer
:param oauth_version: (optional) Choose which OAuth version to use.
Default: 1
:param api_version: (optional) Choose which Twitter API version to
use. Default: 1.1
:param client_args: (optional) Accepts some requests Session parameters
and some requests Request parameters.
See http://docs.python-requests.org/en/latest/api/#sessionapi
and requests section below it for details.
[ex. headers, proxies, verify(SSL verification)]
:param auth_endpoint: (optional) Lets you select which authentication
endpoint will use your application.
This will allow the application to have DM access
if the endpoint is 'authorize'.
Default: authenticate.
"""
# API urls, OAuth urls and API version; needed for hitting that there
# API.
self.api_version = api_version
self.api_url = 'https://api.twitter.com/%s'
self.app_key = app_key
self.app_secret = app_secret
self.oauth_token = oauth_token
self.oauth_token_secret = oauth_token_secret
self.access_token = access_token
# OAuth 1
self.request_token_url = self.api_url % 'oauth/request_token'
self.access_token_url = self.api_url % 'oauth/access_token'
self.authenticate_url = self.api_url % ('oauth/%s' % auth_endpoint)
if self.access_token: # If they pass an access token, force OAuth 2
oauth_version = 2
self.oauth_version = oauth_version
# OAuth 2
if oauth_version == 2:
self.request_token_url = self.api_url % 'oauth2/token'
self.client_args = client_args or {}
default_headers = {'User-Agent': 'Twython v' + __version__}
if 'headers' not in self.client_args:
# If they didn't set any headers, set our defaults for them
self.client_args['headers'] = default_headers
elif 'User-Agent' not in self.client_args['headers']:
# If they set headers, but didn't include User-Agent.. set
# it for them
self.client_args['headers'].update(default_headers)
# Generate OAuth authentication object for the request
# If no keys/tokens are passed to __init__, auth=None allows for
# unauthenticated requests, although I think all v1.1 requests
# need auth
auth = None
if oauth_version == 1:
# User Authentication is through OAuth 1
if self.app_key is not None and self.app_secret is not None:
auth = OAuth1(self.app_key, self.app_secret,
self.oauth_token, self.oauth_token_secret)
elif oauth_version == 2 and self.access_token:
# Application Authentication is through OAuth 2
token = {'token_type': token_type,
'access_token': self.access_token}
auth = OAuth2(self.app_key, token=token)
self.client = requests.Session()
self.client.auth = auth
# Make a copy of the client args and iterate over them
# Pop out all the acceptable args at this point because they will
# Never be used again.
client_args_copy = self.client_args.copy()
for k, v in client_args_copy.items():
if k in ('cert', 'hooks', 'max_redirects', 'proxies'):
setattr(self.client, k, v)
self.client_args.pop(k) # Pop, pop!
# Headers are always present, so we unconditionally pop them and merge
# them into the session headers.
self.client.headers.update(self.client_args.pop('headers'))
self._last_call = None
0
Example 48
def _get_request_token(self):
"""
Obtain a temporary request token to authorize an access token and to
sign the request to obtain the access token
"""
if self.request_token is None:
get_params = {}
if self.parameters:
get_params.update(self.parameters)
get_params['oauth_callback'] \
= self.request.build_absolute_uri(self.callback_url)
rt_url = self.request_token_url + '?' + urlencode(get_params)
oauth = OAuth1(self.consumer_key,
client_secret=self.consumer_secret)
response = requests.post(url=rt_url, auth=oauth)
if response.status_code not in [200, 201]:
raise OAuthError(
_('Invalid response while obtaining request token'
' from "%s".') % get_token_prefix(
self.request_token_url))
self.request_token = dict(parse_qsl(response.text))
self.request.session['oauth_%s_request_token' % get_token_prefix(
self.request_token_url)] = self.request_token
return self.request_token
0
Example 49
def query(self, url, method="GET", params=dict(), headers=dict()):
"""
Request a API endpoint at ``url`` with ``params`` being either the
POST or GET data.
"""
access_token = self._get_at_from_session()
oauth = OAuth1(
self.consumer_key,
client_secret=self.secret_key,
resource_owner_key=access_token['oauth_token'],
resource_owner_secret=access_token['oauth_token_secret'])
response = getattr(requests, method.lower())(url,
auth=oauth,
headers=headers,
params=params)
if response.status_code != 200:
raise OAuthError(
_('No access to private resources at "%s".')
% get_token_prefix(self.request_token_url))
return response.text
0
Example 50
Project: requests-oauthlib Source File: test_core.py
def testFormEncoded(self, generate_nonce, generate_timestamp):
"""OAuth1 assumes form encoded if content type is not specified."""
generate_nonce.return_value = 'abc'
generate_timestamp.return_value = '1'
oauth = requests_oauthlib.OAuth1('client_key')
headers = {'Content-type': 'application/x-www-form-urlencoded'}
r = requests.Request(method='POST', url='http://a.b/path?query=retain',
auth=oauth, data='this=really&is=&+form=encoded', headers=headers)
a = r.prepare()
self.assertEqual(a.url, 'http://a.b/path?query=retain')
self.assertEqual(a.body, 'this=really&is=&+form=encoded')
self.assertEqual(a.headers.get('Content-Type'), 'application/x-www-form-urlencoded')
# guess content-type
r = requests.Request(method='POST', url='http://a.b/path?query=retain',
auth=oauth, data='this=really&is=&+form=encoded')
b = r.prepare()
self.assertEqual(b.url, 'http://a.b/path?query=retain')
self.assertEqual(b.body, 'this=really&is=&+form=encoded')
self.assertEqual(b.headers.get('Content-Type'), 'application/x-www-form-urlencoded')
self.assertEqual(a.headers.get('Authorization'),
b.headers.get('Authorization'))