本文整理汇总了Python中oauth2.Client类的典型用法代码示例。如果您正苦于以下问题:Python Client类的具体用法?Python Client怎么用?Python Client使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Client类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: tweet
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
示例2: authenticate
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
示例3: post
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)
示例4: get_access_token
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
示例5: do
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'])
示例6: SendMsg
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
示例7: make_api_call
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)
示例8: login
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']))
示例9: on_auth
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'))
示例10: get
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"])
)
示例11: get_user_inf
def get_user_inf():
user = {}
access_token = session.get('access_token')
print access_token
if access_token:
# access_tokenなどを使ってAPIにアクセスする
token = Token(access_token['oauth_token'], access_token['oauth_token_secret'])
client = Client(consumer, token)
resp, content = client.request('http://n.hatena.com/applications/my.json')
if content != 'oauth_problem=token_rejected':
user = json.loads(content)
return user
示例12: ContextIO
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})
示例13: fetch
def fetch(self, username):
from droplet.stream.models import Location
try:
return self.get(username = username)
except self.model.DoesNotExist:
pass
client = Client(
Consumer(
key = settings.TWITTER_CONSUMER_KEY,
secret = settings.TWITTER_CONSUMER_SECRET
),
Token(
key = settings.TWITTER_ACCESS_KEY,
secret = settings.TWITTER_ACCESS_SECRET
)
)
response, content = client.request(
USER_URL + '?' + urlencode(
{
'screen_name': username
}
)
)
if response.status != 200:
return
try:
content = simplejson.loads(content)
except:
return
url = content.get('url')
if url:
try:
url = urlopen(url).url
except:
pass
return self.create(
username = content.get('screen_name'),
display_name = content.get('name'),
description = content.get('description'),
image = content.get('profile_image_url'),
location = Location.objects.fetch(
content.get('location')
),
url = url
)
示例14: ContextIO
class ContextIO(object):
url_base = "https://api-preview.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:
body = json.loads(body)
return body
else:
self.handle_request_error(response, body)
def request(self, url, method, params, headers):
if params:
url += '?' + urlencode(params)
print "{method} {url}".format(url=url, method=method)
return self.client.request(url, method, 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)
for message in body['messages']:
if message['type'] == 'error':
messages.append("error {0}".format(message['code']))
raise Exception('HTTP {status}: {message}'.format(status=response['status'], message=', '.join(messages)))
except ValueError:
raise Exception('HTTP {status}: {body}'.format(status=response['status'], body=body))
示例15: request
def request(self, method, url, query=''):
client = Client(self.consumer, self.token)
headers, body = client.request(self.BASE + url, method=method, body=query)
status = headers.get('status')
json = None
try:
if status < '500':
json = loads(body)
except ValueError:
logging.warn(traceback.format_exc())
logging.warn(body)
return status == '200', status, json