本文整理汇总了Python中oauth2.Client.request方法的典型用法代码示例。如果您正苦于以下问题:Python Client.request方法的具体用法?Python Client.request怎么用?Python Client.request使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类oauth2.Client
的用法示例。
在下文中一共展示了Client.request方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get
# 需要导入模块: from oauth2 import Client [as 别名]
# 或者: from oauth2.Client import request [as 别名]
def get(self, ckey, csec):
"""
oauthを行う。
tokenを要求した後、PINの入力を受付け、
その結果、token情報を返す
"""
"""
リプライをパースするλ式
oauth_token=IE&oauth_token_secret=0x&oauth_callback_confirmed=true'
を
{'oauth_token_secret': '0x', 'oauth_token': 'IEb', 'oauth_callback_confirmed': 'true'}
のようにする
"""
parseparam = lambda x: dict(map(lambda y: y.split('='), x.split("&")))
# 設定ファイルに情報があるならそこからもらい返す
ukey, usec = self.getfromcfg()
if ukey != "" and usec != "":
return( (ukey, usec) )
# oauth用のクラス定義
client = Client(Consumer(ckey, csec), None)
# トークンの要求
liRes = client.request(self.urlReqToken,
'GET')
diRes = parseparam(liRes[1])
# 得たトークンを基にPINの要求を行う
request_token = Token(diRes["oauth_token"], diRes["oauth_token_secret"])
print("plz access: " + self.urlReqPin + request_token.key)
stPin = raw_input('PIN:')
request_token.set_verifier(stPin)
# 実際のキーをもらう
client.token = request_token
liRes = client.request(self.urlReqKey,
'POST')
# 情報をパースする
diRes = parseparam(liRes[1])
ukey = diRes["oauth_token"]
usec = diRes["oauth_token_secret"]
# 設定ファイルに書き込む
self.setcfg(ukey, usec)
return(
(ukey,
usec,
diRes["user_id"],
diRes["screen_name"])
)
示例2: ContextIO
# 需要导入模块: from oauth2 import Client [as 别名]
# 或者: from oauth2.Client import request [as 别名]
class ContextIO(object):
url_base = "https://api.context.io"
def __init__(self, consumer_key, consumer_secret):
self.consumer = Consumer(key=consumer_key, secret=consumer_secret)
self.client = Client(self.consumer)
self.client.set_signature_method(sha1())
self.base_uri = '2.0'
def request_uri(self, uri, method="GET", params={}, headers={}):
url = '/'.join((self.url_base, self.base_uri, uri))
response, body = self.request(url, method, params, headers)
status = int(response['status'])
if status in (200, 201) :
body = json.loads(body)
return body
else:
self.handle_request_error(response, body)
def request(self, url, method, params, headers):
query_params = urlencode(params)
if params and method == 'GET':
url += '?' + query_params
return self.client.request(url, method, headers=headers)
return self.client.request(url, method, query_params, headers=headers)
def get_accounts(self):
return [Account(self, obj) for obj in self.request_uri('accounts')]
def post_account(self, email, first_name=None, last_name=None):
pass
def delete_account(self, account_id):
pass
def put_account(self, first_name=None, last_name=None):
pass
def handle_request_error(self, response, body):
messages = []
try:
body = json.loads(body)
raise Exception('HTTP {status}: {message}'.format(status=response['status'], message=body['value']))
except ValueError:
raise Exception('HTTP {status}: {body}'.format(status=response['status'], body=body))
示例3: authenticate
# 需要导入模块: from oauth2 import Client [as 别名]
# 或者: from oauth2.Client import request [as 别名]
def authenticate(self, key, secret):
consumer = Consumer(settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CONSUMER_SECRET)
token = Token(key, secret)
client = Client(consumer, token)
response, content = client.request(twitter_auth_settings.ACCESS_TOKEN_URL, "GET")
if not response.get('status') == '200':
raise TwitterAuthException("Invalid response from Twitter.", response)
access_token = dict(cgi.parse_qsl(content))
# if we have an access token, it means we have authenticated with Twitter
user, created = User.objects.get_or_create(username=access_token['screen_name'])
if created:
twitter_user_created.send(
sender="TwitterAuth",
user=user,
screen_name=access_token['screen_name'],
user_id=access_token['user_id']
)
# give the user a temporary password - it should never be needed since
# Twitter is providing the authentication token.
user.set_password(User.objects.make_random_password(length=12))
user.save()
# update credentials
user.twitterauth.oauth_token = access_token.get('oauth_token')
user.twitterauth.oauth_secret = access_token.get('oauth_token_secret')
user.twitterauth.save()
twitter_user_authenticated.send(sender='TwitterAuth', user=user)
return user
示例4: post
# 需要导入模块: from oauth2 import Client [as 别名]
# 或者: from oauth2.Client import request [as 别名]
def post(self, obj, access_token):
site = Site.objects.get_current()
token = Token(
key = ''.join(access_token.get('oauth_token')),
secret = ''.join(access_token.get('oauth_token_secret')),
)
title = unicode(obj)
content_type = unicode(obj._meta.verbose_name)
url = self.shorten_url('http://%s%s' % (site.domain, obj.get_absolute_url()))
prefix = 'I\'ve just commented on the '
pattern = u'%s%s %s %s'
title_avail = 140 - len(prefix) - (len(url) + 1) - (len(content_type) + 1)
while len(title) > title_avail:
before_space, space, after_space = title[:title_avail - 3].rpartition(' ')
title = before_space + '...'
text = pattern % (prefix, content_type, title, url)
client = Client(self.consumer(), token)
response, content = client.request(self.post_url, 'POST',
body = 'status=%s' % urlquote(text)
)
json = simplejson.loads(content)
if json.get('error'):
raise Exception(resp['error'])
if json.get('id'):
return True
raise Exception(json)
示例5: tweet
# 需要导入模块: from oauth2 import Client [as 别名]
# 或者: from oauth2.Client import request [as 别名]
def tweet(message, key, secret, auth_key):
"""
get access key and call twitter api.
>>> tweet_with_auth("hello", "key", "secret", "verifier")
:param message: message to tweet
:type key: str
:param key:
:type key: str
:param secret:
:type key: str
:param auth_key: authorize key
:type key: str
:returns: result call api
:rtype: dict, dict
"""
post_body = "status={}".format(message)
# tweet
client = Client(Consumer(V.CONSUMER_KEY, V.CONSUMER_SECRET),
Token(key, secret))
res, content = client.request(V.STATUSES_UPDATE_URL,
method="POST",
body=post_body )
set_cache(auth_key, V.TW_RESPONCE, res)
set_cache(auth_key, V.TW_CONTENT, content)
return res, content
示例6: doSetup
# 需要导入模块: from oauth2 import Client [as 别名]
# 或者: from oauth2.Client import request [as 别名]
def doSetup(self):
print "Running twitter setup..."
consumer = Consumer(self.consumer_key, self.consumer_secret)
print consumer
client = Client(consumer)
resp, content = client.request(TWITTER_REQUEST_TOKEN_URL, "GET")
if resp["status"] != "200":
raise Exception("Invalid response %s." % resp["status"])
self.request_token = dict(urlparse(content))
print "Request Token:"
print " - oauth_token = %s" % self.request_token["oauth_token"]
print " - oauth_token_secret = %s" % self.request_token["oauth_token_secret"]
print
# Step 2: Redirect to the provider. Since this is a CLI script we do not
# redirect. In a web application you would redirect the user to the URL
# below.
print "Go to the following link in your browser:"
print "%s?oauth_token=%s" % (TWITTER_AUTHORIZE_URL, self.request_token["oauth_token"])
print
# After the user has granted access to you, the consumer, the provider will
# redirect you to whatever URL you have told them to redirect to. You can
# usually define this in the oauth_callback argument as well.
accepted = "n"
while accepted.lower() == "n":
accepted = raw_input("Have you authorized me? (y/n) ")
oauth_verifier = raw_input("What is the PIN? ")
# Step 3: Once the consumer has redirected the user back to the oauth_callback
# URL you can request the access token the user has approved. You use the
# request token to sign this request. After this is done you throw away the
# request token and use the access token returned. You should store this
# access token somewhere safe, like a database, for future use.
token = Token(self.request_token["oauth_token"], self.request_token["oauth_token_secret"])
token.set_verifier(oauth_verifier)
client = Client(consumer, token)
resp, content = client.request(TWITTER_ACCESS_TOKEN_URL, "POST")
self.access_token = dict(urlparse(content))
print "Access Token:"
print " - oauth_token = %s" % self.access_token["oauth_token"]
print " - oauth_token_secret = %s" % self.access_token["oauth_token_secret"]
print
print "You may now access protected resources using the access tokens above."
示例7: Tweeter
# 需要导入模块: from oauth2 import Client [as 别名]
# 或者: from oauth2.Client import request [as 别名]
class Tweeter(object):
def __init__(self, consumer_key, consumer_secret, user_key, user_secret):
self._consumer = Consumer(consumer_key, consumer_secret)
self._token = Token(user_key, user_secret)
self._client = Client(self._consumer, self._token)
def tweet(self, content):
return self._client.request('https://api.twitter.com/1.1/statuses/update.json', 'POST', urlencode({'status': content}))
示例8: get_access_token
# 需要导入模块: from oauth2 import Client [as 别名]
# 或者: from oauth2.Client import request [as 别名]
def get_access_token(config, token, sec, verifier):
consumer = Consumer(config['consumer_key'], config['consumer_sec'])
token = Token(token, sec)
token.set_verifier(verifier)
client = Client(consumer, token)
response, content = client.request(ACCESS_TOKEN_URL)
access_token = dict(urlparse.parse_qsl(content))
print access_token
示例9: do
# 需要导入模块: from oauth2 import Client [as 别名]
# 或者: from oauth2.Client import request [as 别名]
def do(config, token=None, sec=None, verifier=None):
consumer = Consumer(config['consumer_key'], config['consumer_sec'])
client = Client(consumer)
response, content = client.request(REQUEST_TOKEN_URL, 'GET')
request_token = dict(urlparse.parse_qsl(content))
print request_token['oauth_token']
print request_token['oauth_token_secret']
print '%s?oauth_token=%s' % (AUTHORIZE_URL, request_token['oauth_token'])
示例10: SendMsg
# 需要导入模块: from oauth2 import Client [as 别名]
# 或者: from oauth2.Client import request [as 别名]
def SendMsg(self, update):
token = Token(key=self.access_key, secret=self.access_secret)
consumer = Consumer(key=self.consumer_key, secret=self.consumer_secret)
client = Client(consumer, token)
request_uri = "https://api.twitter.com/1/statuses/update.json"
data = {u"status": unicodedata.normalize("NFKD", update[:140]).encode("ASCII", "ignore")}
resp = client.request(request_uri, "POST", urllib.urlencode(data))[0]
print resp.content
print resp.status
示例11: make_api_call
# 需要导入模块: from oauth2 import Client [as 别名]
# 或者: from oauth2.Client import request [as 别名]
def make_api_call(self, kind, url, token, method="GET", **kwargs):
if isinstance(token, basestring):
token = Token.from_string(token)
client = Client(self.consumer, token=token)
request_kwargs = dict(method=method)
if method == "POST":
request_kwargs["body"] = urlencode(kwargs["params"])
response, content = client.request(url, **request_kwargs)
return self._process_response(kind, response, content)
示例12: login
# 需要导入模块: from oauth2 import Client [as 别名]
# 或者: from oauth2.Client import request [as 别名]
def login():
# リクエストトークンの取得
client = Client(consumer)
print "client : %s" %client
resp, content = client.request('%s?scope=%s&oauth_callback=%s%s' % \
(REQUEST_TOKEN_URL, SCOPE, request.host_url,'on-auth'))
# セッションへリクエストトークンを保存しておく
session['request_token'] = dict(urlparse.parse_qsl(content))
# 認証用URLにリダイレクトする
return redirect('%s?oauth_token=%s' % (AUTHENTICATE_URL, session['request_token']['oauth_token']))
示例13: on_auth
# 需要导入模块: from oauth2 import Client [as 别名]
# 或者: from oauth2.Client import request [as 别名]
def on_auth():
# リクエストトークンとverifierを用いてアクセストークンを取得
request_token = session['request_token']
token = Token(request_token['oauth_token'], request_token['oauth_token_secret'])
token.set_verifier(request.args['oauth_verifier'])
client = Client(consumer, token)
resp, content = client.request(ACCESS_TOKEN_URL)
# アクセストークンをセッションに記録しておく
session['access_token'] = dict(urlparse.parse_qsl(content))
return redirect(url_for('index'))
示例14: oauthdance
# 需要导入模块: from oauth2 import Client [as 别名]
# 或者: from oauth2.Client import request [as 别名]
def oauthdance(
consumer_key,
consumer_secret,
request_token_url="http://twitter.com/oauth/request_token",
authorize_url="http://twitter.com/oauth/authorize",
access_token_url="http://twitter.com/oauth/access_token",
):
"""
"""
from oauth2 import Consumer, Client, Token
from urlparse import parse_qsl
con = Consumer(consumer_key, consumer_secret)
cli = Client(con)
res, bod = cli.request(request_token_url, "GET")
assert res["status"] == "200", "Expected status=200, got %s." % res["status"]
tok = dict(parse_qsl(bod))
tok = Token(tok["oauth_token"], tok["oauth_token_secret"])
print "Visit this URL to get a PIN:"
print " %s?oauth_token=%s" % (authorize_url, tok.key)
pin = raw_input("PIN: ").strip()
tok.set_verifier(pin)
cli = Client(con, tok)
res, bod = cli.request(access_token_url, "GET")
assert res["status"] == "200", "Expected status=200, got %s." % res["status"]
tok = dict(parse_qsl(bod))
tok = Token(tok["oauth_token"], tok["oauth_token_secret"])
print "Your token key is: ", tok.key
print "And your secret is:", tok.secret
return tok
示例15: ContextIO
# 需要导入模块: from oauth2 import Client [as 别名]
# 或者: from oauth2.Client import request [as 别名]
class ContextIO(object):
url_base = "https://api.context.io"
def __init__(self, consumer_key, consumer_secret):
self.consumer = Consumer(key=consumer_key, secret=consumer_secret)
self.client = Client(self.consumer)
self.client.set_signature_method(sha1())
self.base_uri = '2.0'
def request_uri(self, uri, method="GET", params={}, headers={}):
url = '/'.join((self.url_base, self.base_uri, uri))
response, body = self.request(url, method, params, headers)
status = int(response['status'])
if status >= 200 and status < 300:
body = json.loads(body)
return body
else:
self.handle_request_error(response, body)
def request(self, url, method, params, headers):
body = ''
if method == 'GET' and params:
url += '?' + urlencode(params)
elif method == 'POST' and params:
body = urlencode(params)
print method + ' ' + url
return self.client.request(url, method, headers=headers, body=body)
def get_accounts(self, **params):
params = Resource.sanitize_params(params, ['email', 'status', 'status_ok', 'limit', 'offset'])
return [Account(self, obj) for obj in self.request_uri('accounts', params=params)]
def post_account(self, email, **params):
params = Resource.sanitize_params(params, ['first_name', 'last_name'])
params['email'] = email
return Account(self, self.request_uri('accounts', method="POST", params=params))
def delete_account(self, account_id):
pass
def put_account(self, first_name=None, last_name=None):
pass
def handle_request_error(self, response, body):
try:
import logging
logging.info('body '+str(body))
body = json.loads(body)
raise Exception('HTTP %(status)s - %(type)s %(code)s: %(message)s' % { 'status': response['status'], 'type': body['type'], 'code': body['code'], 'message': body['value']})
except ValueError:
raise Exception('HTTP %(status)s: %(body)s' % {'status':response['status'], 'body':body})