本文整理汇总了Python中oauth.oauth.OAuthRequest类的典型用法代码示例。如果您正苦于以下问题:Python OAuthRequest类的具体用法?Python OAuthRequest怎么用?Python OAuthRequest使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了OAuthRequest类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: updateProfile
def updateProfile(token, secret, update_profile_url, profile):
current_site = Site.objects.get_current()
user_profile_url = "%s%s" % (current_site.domain, reverse('profile_detail', args=[profile.user.username]))
oauthToken = OAuthToken(token, secret)
url = urlparse.urlparse(update_profile_url)
params = {}
if url[4] != '':
# We need to copy over the query string params for sites like laconica
params.update(dict([part.split('=') for part in url[4].split('&')]))
params['omb_version'] = OMB_VERSION_01
params['omb_listenee'] = user_profile_url
params['omb_listenee_profile'] = user_profile_url
params['omb_listenee_nickname'] = profile.username
params['omb_listenee_license'] = '%s/license/' % current_site.domain # TODO link to the real license
params['omb_listenee_fullname'] = profile.name
params['omb_listenee_homepage'] = profile.website
params['omb_listenee_bio'] = profile.about
params['omb_listenee_location'] = profile.location
#params['omb_listenee_avatar'] = TODO get the gravatar of the user
consumer = OAuthConsumer(current_site.domain, "")
req = OAuthRequest().from_consumer_and_token(consumer, token=oauthToken, http_url=url.geturl(), parameters=params, http_method="POST")
req.sign_request(OAuthSignatureMethod_HMAC_SHA1(), consumer, oauthToken)
f = urllib.urlopen(url.geturl(), req.to_postdata())
data = f.read()
# TODO log failures
示例2: requestAuthorization
def requestAuthorization(token, url, listener, user):
current_site = Site.objects.get_current()
user_profile_url = "%s%s" % (current_site.domain, reverse('profile_detail', args=[user.username]))
profile = user.get_profile()
url = urlparse.urlparse(url)
params = {}
if url[4] != '':
# We need to copy over the query string params for sites like laconica
params.update(dict([part.split('=') for part in url[4].split('&')]))
params['omb_version'] = OMB_VERSION_01
params['omb_listener'] = listener
params['omb_listenee'] = "http://%s" % user_profile_url
params['omb_listenee_profile'] = "http://%s" % user_profile_url
params['omb_listenee_nickname'] = user.username
params['omb_listenee_license'] = 'http://%s/license/' % current_site.domain # TODO link to the real license
params['omb_listenee_fullname'] = "%s %s" % (user.first_name, user.last_name)
params['omb_listenee_homepage'] = "" # TOOD Pinax doesn't have this
params['omb_listenee_bio'] = profile.about
params['omb_listenee_location'] = profile.location
params['omb_listenee_avatar'] = '' # TODO get the avatar url
params['oauth_callback'] = 'http://%s/omb/finish_follow/' % current_site.domain
consumer = OAuthConsumer(current_site.domain, "")
oauth_request = OAuthRequest().from_consumer_and_token(consumer, http_url=url.geturl(), parameters=params, http_method="GET", token=token)
oauth_request.sign_request(OAuthSignatureMethod_HMAC_SHA1(), consumer, token)
return oauth_request
示例3: initialize_server_request
def initialize_server_request(request):
"""Shortcut for initialization."""
# Django converts Authorization header in HTTP_AUTHORIZATION
# Warning: it doesn't happen in tests but it's useful, do not remove!
# Check to see if it's a dict if it's being called from the LRS app. The LRS app parses everything in a dict first
# then will call this in Authorization with the request dict.
if type(request) == dict:
auth_header = {}
if 'Authorization' in request:
auth_header = {'Authorization': request['Authorization']}
elif 'HTTP_AUTHORIZATION' in request:
auth_header = {'Authorization': request['HTTP_AUTHORIZATION']}
parameters = {}
# TODO-WHAT TO DO WITH THIS?
# if request['method'] == "POST":
# parameters = ast.literal_eval(request['body'])
oauth_request = OAuthRequest.from_request(request['method'],
request['absolute_uri'],
headers=auth_header,
parameters=parameters,
query_string=request['query_string'])
else:
auth_header = {}
if 'Authorization' in request.META:
auth_header = {'Authorization': request.META['Authorization']}
elif 'HTTP_AUTHORIZATION' in request.META:
auth_header = {'Authorization': request.META['HTTP_AUTHORIZATION']}
# Don't include extra parameters when request.method is POST and
# request.MIME['CONTENT_TYPE'] is "application/x-www-form-urlencoded"
# (See http://oauth.net/core/1.0a/#consumer_req_param).
# But there is an issue with Django's test Client and custom content types
# so an ugly test is made here, if you find a better solution...
parameters = {}
if request.method == "POST" and \
(request.META.get('CONTENT_TYPE') == "application/x-www-form-urlencoded" \
or request.META.get('SERVER_NAME') == 'testserver'):
parameters = dict(request.REQUEST.items())
# pdb.set_trace()
oauth_request = OAuthRequest.from_request(request.method,
request.build_absolute_uri(),
headers=auth_header,
parameters=parameters,
query_string=request.META.get('QUERY_STRING', ''))
if oauth_request:
oauth_server = OAuthServer(DataStore(oauth_request))
if 'plaintext' in OAUTH_SIGNATURE_METHODS:
oauth_server.add_signature_method(OAuthSignatureMethod_PLAINTEXT())
if 'hmac-sha1' in OAUTH_SIGNATURE_METHODS:
oauth_server.add_signature_method(OAuthSignatureMethod_HMAC_SHA1())
else:
oauth_server = None
return oauth_server, oauth_request
示例4: cookie_for_token
def cookie_for_token(t):
app=t.share.with_app
try:
activity = AppActivity.objects.get(name="main", app=app)
except AppActivity.DoesNotExist:
activity = AppActivity.objects.get(app=app)
app_index_req = utils.url_request_build(activity.url, "GET", {}, "")
oauth_request = OAuthRequest(app, None, app_index_req, oauth_parameters=t.passalong_params)
oauth_request.sign()
auth = oauth_request.to_header()["Authorization"]
return {'oauth_cookie' : auth}
示例5: 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()
)
示例6: signed_header_for_token
def signed_header_for_token(t):
app = t.share.with_app
headers = {}
app_index_req = utils.url_request_build(app.index_url, "GET", headers, "")
# sign as a two-legged OAuth request for the app
oauth_request = OAuthRequest(
consumer=app,
token=None, # no access tokens: 2-legged request
http_request=app_index_req,
oauth_parameters=t.passalong_params
)
oauth_request.sign()
auth = oauth_request.to_header()["Authorization"]
return auth
示例7: set_session_oauth_token
def set_session_oauth_token(sender, user, request, **kwargs):
# user is an Account instance here
headers = {'Authorization': request.META.get('HTTP_AUTHORIZATION', '')}
orequest = OAuthRequest.from_request(request.method, '', headers=headers)
if orequest and 'oauth_token' in orequest.parameters:
# check for token in headers (handle login_by_token case)
token_key = orequest.get_parameter('oauth_token')
elif settings.READ_ONLY_MODE:
try:
token_key = ''
consumer_user = user.user
if consumer_user is not None:
# check for already existent token
token = Token.objects.get(
name=SESSION_TOKEN_NAME, consumer__user=consumer_user)
token_key = token.token
except Token.DoesNotExist:
# no token, this session will be invalidated when RO mode is off
pass
else:
oauth_token, _ = user.get_or_create_oauth_token(
token_name=SESSION_TOKEN_NAME)
token_key = oauth_token.token
request.session[SESSION_TOKEN_KEY] = token_key
示例8: getTwitterOAuthURL
def getTwitterOAuthURL(conf, oauthTokenDict):
"""
Obtain a URL from twitter.com that we can redirect a user to so they
can authenticate themselves and authorize loveme.do to act on their
behalf.
@param conf: the lovemedo configuration.
@param oauthTokenDict: A C{dict} mapping token keys to tokens.
@return: A C{Deferred} that fires with the URL for OAuth verification.
"""
log.msg('Got login URL request.')
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
consumer = OAuthConsumer(conf.consumer_key, conf.consumer_secret)
request = OAuthRequest.from_consumer_and_token(
consumer, callback=conf.callback_url,
http_url=conf.request_token_url)
request.sign_request(OAuthSignatureMethod_HMAC_SHA1(), consumer, None)
r = RetryingCall(
client.getPage, conf.request_token_url, headers=request.to_header())
d = r.start()
d.addCallback(_makeURL)
d.addErrback(log.err)
return d
示例9: 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))
示例10: 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)
示例11: _fetch_resource
def _fetch_resource(self, url, parameters=None, method = 'GET'):
""" Retrieve a Yammer API resource.
Keyword arguments:
url -- a Yammer API URL (excluding query parameters)
parameters -- used to pass query parameters to add to the request
(optional).
"""
if not self._access_token:
raise YammerError("Can't fetch resource. Missing access token!")
try:
oauth_request = OAuthRequest.from_consumer_and_token(
self._consumer,
token=self._access_token,
http_method=method,
http_url=url,
parameters=parameters)
headers = oauth_request.to_header()
oauth_request.sign_request(self._signature,
self._consumer,
self._access_token)
url = oauth_request.to_url()
except OAuthError, m:
raise YammerError(m.message)
示例12: get_request
def get_request(self, headers=None, **kwargs):
request = super(Flixject, self).get_request(headers=headers, **kwargs)
method = request.get('method', 'GET')
# Apply OAuthness.
csr = OAuthConsumer(*self.api_token)
orq = OAuthRequest.from_consumer_and_token(csr, http_method=method,
http_url=request['uri'])
# OAuthRequest will strip our query parameters, so add them back in.
parts = list(urlparse.urlparse(self._location))
queryargs = cgi.parse_qs(parts[4], keep_blank_values=True)
for key, value in queryargs.iteritems():
orq.set_parameter(key, value[0])
# Sign the request.
osm = OAuthSignatureMethod_HMAC_SHA1()
orq.set_parameter('oauth_signature_method', osm.get_name())
orq.sign_request(osm, csr, None)
if method == 'GET':
request['uri'] = orq.to_url()
else:
request['headers'].update(orq.to_header())
return request
示例13: requestToken
def requestToken(omb):
current_site = Site.objects.get_current()
url = urlparse.urlparse(omb[OAUTH_REQUEST].uris[0].uri)
params = {}
if url[4] != '':
# We need to copy over the query string params for sites like laconica
params.update(dict([part.split('=') for part in url[4].split('&')]))
params['omb_version'] = OMB_VERSION_01
params['omb_listener'] = omb[OAUTH_REQUEST].localid.text
consumer = OAuthConsumer(current_site.domain, "")
req = OAuthRequest().from_consumer_and_token(consumer, http_url=url.geturl(), parameters=params, http_method="POST")
req.sign_request(OAuthSignatureMethod_HMAC_SHA1(), consumer, None)
f = urllib.urlopen(url.geturl(), req.to_postdata())
data = f.read()
requestToken = OAuthToken.from_string(data)
return requestToken
示例14: requestAccessToken
def requestAccessToken(omb_session, oauth_request):
current_site = Site.objects.get_current()
token = OAuthToken(omb_session["token"], omb_session["secret"])
url = urlparse.urlparse(omb_session["access_token_url"])
params = {}
if url[4] != '':
# We need to copy over the query string params for sites like laconica
params.update(dict([part.split('=') for part in url[4].split('&')]))
params['omb_version'] = OMB_VERSION_01
consumer = OAuthConsumer(current_site.domain, "")
req = OAuthRequest().from_consumer_and_token(consumer, token=token, http_url=url.geturl(), parameters=params, http_method="POST")
req.sign_request(OAuthSignatureMethod_HMAC_SHA1(), consumer, token)
f = urllib.urlopen(url.geturl(), req.to_postdata())
data = f.read()
accessToken = OAuthToken.from_string(data)
return accessToken
示例15: fetch_access_token
def fetch_access_token(self,
unauth_request_token_key,
unauth_request_token_secret,
oauth_verifier):
""" After the user has authorizated API access via the authorization
URL, get the (semi-)permanent access key using the user-authorized
request token.
Keyword arguments:
unauth_request_token -- the user-authorized OAuth request token
oauth_verifier -- per OAuth 1.0 Revision A
"""
url = "%s?oauth_verifier=%s" % (YAMMER_ACCESS_TOKEN_URL,
oauth_verifier)
try:
unauth_request_token = OAuthToken(unauth_request_token_key,
unauth_request_token_secret)
oauth_request = OAuthRequest.from_consumer_and_token(
self._consumer,
token=unauth_request_token,
http_method='POST',
http_url=url)
oauth_request.sign_request(self._signature,
self._consumer,
unauth_request_token)
headers = oauth_request.to_header()
except OAuthError, m:
raise YammerError(m.message)