本文整理匯總了Python中oauth.oauth.OAuthToken類的典型用法代碼示例。如果您正苦於以下問題:Python OAuthToken類的具體用法?Python OAuthToken怎麽用?Python OAuthToken使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了OAuthToken類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: dropbox_client
def dropbox_client():
access_token_file = os.path.join(os.environ["HOME"], ".dropbox-tools-access-token")
sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE)
try:
with open(access_token_file) as f:
access_token = OAuthToken.from_string(f.read())
sess.set_token(access_token.key, access_token.secret)
except (IOError, EOFError, KeyError):
request_token = sess.obtain_request_token()
url = sess.build_authorize_url(request_token)
print "Please visit\n\n %s\n\nand press the 'Allow' button, then hit 'Enter' here."%url
raw_input()
# This will fail if the user didn't visit the above URL and hit 'Allow'
access_token = sess.obtain_access_token(request_token)
# dropbox access tokens don't have serialisation methods on them,
my_token = OAuthToken(access_token.key, access_token.secret)
with open(access_token_file, "w") as f:
f.write(my_token.to_string())
conn = client.DropboxClient(sess)
print "linked account:", conn.account_info()["display_name"]
return conn
示例2: process_request
def process_request(self, request):
"""Import the Twitter token from the Session into the Request."""
request.twitter_access_token = None
request.twitter_request_token = None
request.twitter_userinfo = None
if ACCESS_KEY in request.session:
token_str = request.session[ACCESS_KEY]
token = OAuthToken.from_string(token_str)
request.twitter_access_token = token
userinfo = SimpleLazyObject(curry(cached_user_info,
request, token))
request.twitter_userinfo = userinfo
if REQUEST_KEY in request.session:
token_str = request.session[REQUEST_KEY]
request.twitter_request_token = OAuthToken.from_string(token_str)
示例3: fetch_url
def fetch_url(self, url, token, **kwargs):
from StringIO import StringIO
token = OAuthToken.from_string(str(token))
consumer = self.get_consumer()
connection = self.get_connection(False)
request = OAuthRequest.from_consumer_and_token(
consumer, token = token, http_method = 'GET',
http_url = url, parameters = kwargs
)
request.sign_request(self.signature_method, consumer, token)
url = request.to_url()
start = 'http://%s' % self.server
if url.startswith(start):
url = url[len(start):]
start = 'https://%s' % self.server
if url.startswith(start):
url = url[len(start):]
connection.request(request.http_method, url, '', request.to_header())
resp = connection.getresponse().read()
return StringIO(resp)
示例4: exchange_request_token
def exchange_request_token(request_token):
consumer = OAuthConsumer(settings.ORCHARD_KEY, settings.ORCHAR_SECRET)
oauth_request = OAuthRequest.from_consumer_and_token(
consumer, request_token, http_url=ACCESS_TOKEN_URL)
return OAuthToken.from_string(
_make_request(consumer, oauth_request, request_token))
示例5: get_dropbox
def get_dropbox(request, sess = None):
if not sess:
_keys = settings.DROPBOX_SETTINGS
sess = session.DropboxSession(_keys['app_key'], _keys['app_secret'],_keys['type'])
token = request.user.django_dropbox.dropbox_token
sess.token = OAuthToken.from_string(token)
return client.DropboxClient(sess)
示例6: dropbox_auth_callback
def dropbox_auth_callback(self, site):
"""
Handle the server callback after user has granted access.
This callback contains oauth_token and oauth_verifier. The oauth verifier is
currently not used by dropbox?
"""
# First get the token we stored with the user
cookie = self.request.cookies["token"]
assert cookie, "No cookie!"
token = OAuthToken.from_string(cookie)
self.response.headers["Set-Cookie"] = "token=" # erase the auth token
# Then, get the verifier from the get parameters
request_token = self.request.get("oauth_token")
request_verifier = self.request.get("oauth_verifier")
# Something is wrong if the tokens don't match
if not request_token == token.key:
logging.error(
"AuthHandler.dropbox_oauth_callback: request (%s) and cookie (%s) tokens do not match"
% (request_token, token.key)
)
# Now, get an access token to store for future use
logging.debug("AuthHandler.dropbox_oauth_callback. oauth_verifier: %s" % request_verifier)
access_token = models.Site.dropbox_auth.obtain_access_token(token, "")
logging.debug("AuthHandler.dropbox_oauth_callback. Obtained access_token: %s" % access_token.to_string())
# Save the access token for later use
site = models.Site.get_or_insert_current_site()
site.dropbox_access_token = access_token.to_string()
site.put()
self.redirect(self.returnurl)
示例7: _makeURL
def _makeURL(result):
token = OAuthToken.from_string(result)
# Store the token by key so we can find it when the callback comes.
oauthTokenDict[token.key] = token
request = OAuthRequest.from_token_and_callback(
token=token, http_url=conf.authorization_url)
url = request.to_url()
log.msg('Browser OAuth redirect URL = %r' % url)
return url
示例8: __init__
def __init__(self, domain_name=None):
BaseSpider.__init__(self, domain_name)
consumer_key = config.get('yammer', 'consumer_key')
consumer_secret = config.get('yammer', 'consumer_secret')
app_token = config.get('yammer', 'app_token')
self.consumer = OAuthConsumer(consumer_key, consumer_secret)
self.signature = OAuthSignatureMethod_PLAINTEXT()
self.token = OAuthToken.from_string(app_token)
示例9: get_request_token
def get_request_token(self):
oa_req = OAuthRequest.from_consumer_and_token(
self.consumer,
http_url=self.request_token_url)
oa_req.sign_request(self.signature_method,
self.consumer,
None)
req = self.http.get_url(self.request_token_url, headers = oa_req.to_header())
if not str(req.status).startswith('2'):
self.analyze_error(req)
return OAuthToken.from_string(req.data)
示例10: auth
def auth(request, site):
creds = OAUTH_CREDENTIALS.get(site.upper())
if not creds:
raise Http404('Site %s not found' % site)
urls = creds.get('URLS', {})
if 'DIALOG' in urls:
request.session['preauth_url'] = request.META.get('HTTP_REFERER')
return HttpResponseRedirect(urls['DIALOG'])
ssl = creds.get('SSL', False)
server = creds.get('SERVER', '%s.com' % site.lower())
klass = ssl and HTTPSConnection or HTTPConnection
request.session['preauth_url'] = request.META.get('HTTP_REFERER')
consumer = OAuthConsumer(
str(creds['CONSUMER_KEY']),
str(creds['CONSUMER_SECRET'])
)
oauth_request = OAuthRequest.from_consumer_and_token(
consumer, http_url = urls.get('REQUEST_TOKEN')
)
oauth_request.sign_request(SIGNATURE_METHOD(), consumer, None)
url = oauth_request.to_url()
connection = klass(server)
connection.request(oauth_request.http_method, url)
response = connection.getresponse()
resp = response.read()
token = OAuthToken.from_string(resp)
request.session['unauth_token'] = token
auth_url = urls.get('AUTHORISATION')
if isinstance(auth_url, (list, tuple)):
params = auth_url[1]
auth_url = auth_url[0]
else:
params = {}
oauth_request = OAuthRequest.from_consumer_and_token(
consumer, token = token,
http_url = auth_url, parameters = params
)
oauth_request.sign_request(SIGNATURE_METHOD(), consumer, token)
return HttpResponseRedirect(
oauth_request.to_url()
)
示例11: callback_view
def callback_view(request):
if request.GET.has_key('bounceback'):
request.session['bounceback'] = request.GET['bounceback']
if request.GET.has_key("oauth_token_secret"):
oauth_token = OAuthToken.from_string("oauth_token_secret=%s&oauth_token=%s" % (request.GET['oauth_token_secret'], request.GET['oauth_token']))
api = TroveAPI(TROVE['KEY'], TROVE['SECRET'], TROVE['CONTENT_REQUESTED'], oauth_token)
elif request.session.has_key('request_token'):
api = TroveAPI(TROVE['KEY'], TROVE['SECRET'], TROVE['CONTENT_REQUESTED'])
oauth_token = api.get_access_token(request.session['request_token'])
del request.session['request_token']
else:
return redirect('trove-login')
try:
at = TroveAccessToken.objects.get(oauth_token_as_string=oauth_token.__str__())
except TroveAccessToken.DoesNotExist:
# we have to create one! -- although this does run into issues with users having different access tokens
user_info = api.get_user_info()
try:
u = User.objects.get(username=user_info['trove_internal_id'])
except User.DoesNotExist:
u = User()
u.username = user_info['trove_internal_id']
try:
u.first_name = user_info['first_name']
except:
pass
try:
u.last_name = user_info['last_name']
except:
pass
u.set_unusable_password()
u.email = ""
u.is_active = True
u.save()
at = TroveAccessToken()
at.user = u
at.oauth_token_as_string = oauth_token.__str__()
at.save()
user = authenticate(access_token=oauth_token.__str__())
if user is not None:
if user.is_active:
login(request, user)
return __bounceback__(request)
else:
return redirect('trove-login')
else:
return redirect('trove-login')
示例12: exchange_pin_for_access_token
def exchange_pin_for_access_token(pin, request_token):
parameters=dict(oauth_verifier=pin)
oauth_request = OAuthRequest.from_consumer_and_token(
consumer, request_token, http_method="POST", http_url=ACCESS_TOKEN_URL,
parameters=parameters)
oauth_request.sign_request(HMAC(), consumer, request_token)
headers = oauth_request.to_header()
client = Http()
response, body = client.request(ACCESS_TOKEN_URL, "POST", headers=headers)
token = OAuthToken.from_string(body)
return token, body
示例13: get_request_token
def get_request_token():
oauth_request = OAuthRequest.from_consumer_and_token(
consumer, http_method="POST", http_url=REQUEST_TOKEN_URL,
callback="oob")
oauth_request.sign_request(HMAC(), consumer, "")
headers = oauth_request.to_header()
client = Http()
response, body = client.request(REQUEST_TOKEN_URL, "POST", headers=headers)
token = OAuthToken.from_string(body)
return token
示例14: lookup_token
def lookup_token(self, token_type, token_field):
"""
:param token_type: type of token to lookup
:param token_field: token to look up
:note: token_type should always be 'access' as only such tokens are
stored in database
:returns: OAuthToken object
"""
assert token_type == 'access'
try:
token = Token.objects.get(token=token_field)
# Piston expects OAuth tokens to have 'consumer' and 'user' atts.
# (see piston.authentication.OAuthAuthentication.is_authenticated)
oauthtoken = OAuthToken(token.token, token.token_secret)
oauthtoken.consumer = token.consumer
oauthtoken.user = token.consumer.user
return oauthtoken
except Token.DoesNotExist:
return None
示例15: swap_tokens
def swap_tokens(self, *args, **kwargs):
if self.token_required:
consumer, token = args
token = OAuthToken.from_string(token)
request = OAuthRequest.from_consumer_and_token(
consumer, token = token,
http_url = self.access_token_url,
parameters = kwargs
)
request.sign_request(self.signature_method, consumer, token)
url = request.to_url()
if url.startswith('http://'):
url = url[7:]
elif url.startswith('https://'):
url = url[8:]
if url.startswith(self.server):
url = url[len(self.server):]
q = url.find('?')
if q > 01:
qs = url[q + 1:]
url = url[:q]
else:
qs = ''
connection = self.get_connection(False)
connection.request(request.http_method, url, qs, request.to_header())
resp = connection.getresponse().read()
return OAuthToken.from_string(resp)
else:
raise NotImplementedError('Method not implemented for non-standard OAuth provider.')