本文整理汇总了Python中oauth2client.client.AccessTokenCredentials类的典型用法代码示例。如果您正苦于以下问题:Python AccessTokenCredentials类的具体用法?Python AccessTokenCredentials怎么用?Python AccessTokenCredentials使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了AccessTokenCredentials类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: check
def check():
result = lambda ok, text: jsonify({'ok': ok, 'text': text})
if not g.user.phone_info.get('valid'):
return result(False, 'invalid phone number')
token = g.user.social_auth.one().tokens
credentials = AccessTokenCredentials(token, app.config['USER_AGENT'])
service = discovery.build('gmail', 'v1', http=credentials.authorize(Http()))
inbox = service.users().messages().list(userId='me', q='in:inbox is:unread').execute()
data = inbox.get('messages', [])
if not data:
return result(False, 'no unread messages')
msg = service.users().messages().get(userId='me', id=data[0]['id']).execute()
subj = [x['value'] for x in msg['payload']['headers'] if x['name'] == 'Subject']
text = msg['snippet'][:160]
try:
fmt_number = lambda x: '+%s%s' % (x.country_code, x.national_number)
client = TwilioRestClient(app.config['TWILIO_ACCOUNT_SID'],
app.config['TWILIO_AUTH_TOKEN'])
client.messages.create(body=text, to=fmt_number(g.user.phone_info['number']),
from_=app.config['TWILIO_NUMBER'])
data = (True, subj[0] if subj else None)
except Exception, exc:
data = (False, str(exc))
示例2: AccessTokenCredentialsTests
class AccessTokenCredentialsTests(unittest.TestCase):
def setUp(self):
access_token = "foo"
user_agent = "refresh_checker/1.0"
self.credentials = AccessTokenCredentials(access_token, user_agent, revoke_uri=GOOGLE_REVOKE_URI)
def test_token_refresh_success(self):
for status_code in REFRESH_STATUS_CODES:
http = HttpMockSequence([({"status": status_code}, b"")])
http = self.credentials.authorize(http)
try:
resp, content = http.request("http://example.com")
self.fail("should throw exception if token expires")
except AccessTokenCredentialsError:
pass
except Exception:
self.fail("should only throw AccessTokenCredentialsError")
def test_token_revoke_success(self):
_token_revoke_test_helper(self, "200", revoke_raise=False, valid_bool_value=True, token_attr="access_token")
def test_token_revoke_failure(self):
_token_revoke_test_helper(self, "400", revoke_raise=True, valid_bool_value=False, token_attr="access_token")
def test_non_401_error_response(self):
http = HttpMockSequence([({"status": "400"}, b"")])
http = self.credentials.authorize(http)
resp, content = http.request("http://example.com")
self.assertEqual(400, resp.status)
def test_auth_header_sent(self):
http = HttpMockSequence([({"status": "200"}, "echo_request_headers")])
http = self.credentials.authorize(http)
resp, content = http.request("http://example.com")
self.assertEqual(b"Bearer foo", content[b"Authorization"])
示例3: __init__
def __init__(self, request):
self.service = None
self.oauth2token = None
try:
if request.user:
provider = request.session.get('social_auth_last_login_backend')
social = request.user.social_auth.filter(
Q(user_id=request.user.id),
Q(uid=request.user.email),
Q(provider=provider)
)
credential = AccessTokenCredentials(
social[0].tokens['access_token'],
'HTTP/1.1'
)
http = httplib2.Http()
http = credential.authorize(http)
self.service = build("calendar", "v3", http=http)
self.oauth2token = OAuth2Token(
client_id = settings.GOOGLE_OAUTH2_CLIENT_ID,
client_secret=settings.GOOGLE_OAUTH2_CLIENT_SECRET,
scope = 'https://apps-apis.google.com/a/feeds/calendar/resource/',
access_token = social[0].tokens['access_token'],
user_agent='HTTP/1.1'
)
except: pass
示例4: AccessTokenCredentialsTests
class AccessTokenCredentialsTests(unittest.TestCase):
def setUp(self):
access_token = "foo"
user_agent = "refresh_checker/1.0"
self.credentials = AccessTokenCredentials(access_token, user_agent)
def test_token_refresh_success(self):
http = HttpMockSequence([
({'status': '401'}, ''),
])
http = self.credentials.authorize(http)
try:
resp, content = http.request("http://example.com")
self.fail("should throw exception if token expires")
except AccessTokenCredentialsError:
pass
except Exception:
self.fail("should only throw AccessTokenCredentialsError")
def test_non_401_error_response(self):
http = HttpMockSequence([
({'status': '400'}, ''),
])
http = self.credentials.authorize(http)
resp, content = http.request('http://example.com')
self.assertEqual(400, resp.status)
def test_auth_header_sent(self):
http = HttpMockSequence([
({'status': '200'}, 'echo_request_headers'),
])
http = self.credentials.authorize(http)
resp, content = http.request('http://example.com')
self.assertEqual('Bearer foo', content['Authorization'])
示例5: post_event
def post_event(request):
if request.method == 'POST':
event_id = json.loads(request.body)
event = Event.objects.get(pk=event_id)
# Parameters for event being saved to google calendar
event_info = {
"end": {
"dateTime": event.end_time
},
"start": {
'dateTime': event.start_time
},
"summary": event.name,
"location": event.venue,
}
# Builds google calendar service with appropriate credentials
user_social_auth = request.user.social_auth.filter(provider='google-oauth2').first()
access_token = user_social_auth.extra_data['access_token']
calID=user_social_auth.uid
credentials = AccessTokenCredentials(access_token, 'my-user-agent/1.0')
http= httplib2.Http()
http = credentials.authorize(http)
service = build(serviceName='calendar', version='v3', http=http, developerKey='HFs_k7g6ml38NKohwrzfi_ii')
created_event = service.events().insert(calendarId='primary', body=event_info).execute()
return HttpResponse(json.dumps(event_id), content_type='application/json')
示例6: _create_remote_playlist
def _create_remote_playlist(request):
# cheking the local playlist
result = {'error': None, 'playlist_obj': None}
try:
youtube_obj = request.user.social_auth.get(provider='google-oauth2')
except:
return result
try:
post_data = simplejson.loads(request.body)
except:
post_data = {}
playlist_name = post_data.get('title', None)
playlist_is_private = post_data.get('is_private', None)
action_pl_update = False
user_playlist, pl_created = \
Playlist.objects.get_or_create(user=request.user)
if not pl_created: # set last update to now
action_pl_update = user_playlist.should_update(
playlist_name, playlist_is_private)
user_playlist.last_update = datetime.datetime.now()
user_playlist.save()
else:
user_playlist.youtube_pl_name = playlist_name
user_playlist.save()
result['playlist_obj'] = user_playlist
if user_playlist.youtube_pl_id is None and request.method == 'POST':
credentials = AccessTokenCredentials(
youtube_obj.extra_data.get('access_token'), 'friendlyvibe/1.0')
youtube = build(
'youtube', 'v3', http=credentials.authorize(httplib2.Http()))
# create the youtube playlist
if action_pl_update is False:
try:
new_playlist = youtube.playlists().insert(
part="snippet,status",
body=dict(
snippet=dict(
title=settings.DEFAULT_YOUTUBE_PLNAME,
description="A playlist automatically created and managed by friendlyvibe.com"
),
status=dict(
privacyStatus='private' if playlist_is_private else 'public'
)
)
).execute()
user_playlist.youtube_json = simplejson.dumps(new_playlist)
user_playlist.youtube_pl_id = new_playlist.get(u'id')
user_playlist.youtube_pl_name = playlist_name
user_playlist.is_private = playlist_is_private
user_playlist.save()
except Exception, e:
# do some signal here to KNOW the user's youtube account is disconnected
result['error'] = str(e)
示例7: getUser
def getUser():
user_agent = request.headers.get('User-Agent')
credentials = AccessTokenCredentials(session.get('credentials'), user_agent)
if credentials is None:
response = make_response(json.dumps('Current user not connected.'), 401)
response.headers['Content-Type'] = 'application/json'
return response
try:
# authorize an instance of Http with a set of credentials
http = httplib2.Http()
http = credentials.authorize(http)
people_resource = SERVICE.people()
people_document = people_resource.get(userId='me').execute(http=http)
return jsonify(people_document)
except AccessTokenRefreshError:
response = make_response(json.dumps('Failed to refresh access token.'), 500)
response.headers['Content-Type'] = 'application/json'
return response
except AccessTokenCredentialsError:
response = make_response(json.dumps('Access token is invalid or expired and cannot be refreshed.'), 500)
response.headers['Content-Type'] = 'application/json'
return response
示例8: profile
def profile():
access_token = session.get('credentials')
credentials = AccessTokenCredentials(access_token, 'user-agent-value')
# Only fetch a list of people for connected users.
if credentials is None:
response = make_response(json.dumps('Current user not connected.'), 401)
response.headers['Content-Type'] = 'application/json'
return response
try:
# Create a new authorized API client.
http = httplib2.Http()
http = credentials.authorize(http)
people_resource = SERVICE.people()
people_document = people_resource.get(userId='me').execute(http=http)
gplusId = people_document['id']
user = User.query.filter_by(gplusId=gplusId).count()
print user
response = make_response('success', 200)
response.headers['Content-Type'] = 'application/json'
return response
except AccessTokenRefreshError:
response = make_response(json.dumps('Failed to refresh access token.'), 500)
response.headers['Content-Type'] = 'application/json'
return response
示例9: get_service
def get_service(self):
"""
:return: servicio de drive
"""
credentials = AccessTokenCredentials(self.token, None)
http = httplib2.Http()
http = credentials.authorize(http)
return build('drive', 'v2', http)
示例10: authorized_request
def authorized_request(user, url):
access_token = get_access_token(user)
if access_token:
credentials = AccessTokenCredentials(access_token, 'my-user-agent/1.0')
http = httplib2.Http()
http = credentials.authorize(http)
response = do_request(http, url)
return response
示例11: get_email
def get_email(access_token):
creds = AccessTokenCredentials(access_token, 'fooapi/0.1')
h = creds.authorize(Http())
resp, content = h.request(app.config['GOOGLE_API_INFO_URL'])
if resp['status'] != '200':
raise UserProfileAccessException('Unable to access the user profile.')
data = json.loads(content)
return data['email']
示例12: get_user_email_from_token
def get_user_email_from_token(access_token):
if debug: print >> sys.stderr,'Called '+sys._getframe().f_code.co_name
user_email = None
credentials = AccessTokenCredentials(access_token, 'test-user')
http = credentials.authorize(httplib2.Http())
user_info_service = build('oauth2', 'v2', http=http)
user_info = user_info_service.userinfo().get().execute()
if 'email' in user_info:
user_email = user_info['email']
return user_email
示例13: __init__
def __init__(self, access_token, collection_name=''):
'''
a method to initialize the driveClient class
:param access_token: string with oauth2 access token for users account
:param collection_name: [optional] string with name of collection for import
'''
title = '%s.__init__' % self.__class__.__name__
# construct input validation model
self.fields = jsonModel(self._class_fields)
# validate inputs
input_fields = {
'access_token': access_token,
'collection_name': collection_name
}
for key, value in input_fields.items():
object_title = '%s(%s=%s)' % (title, key, str(value))
self.fields.validate(value, '.%s' % key, object_title)
# construct access token
self.access_token = access_token
# construct drive client
import httplib2
from googleapiclient import discovery
from oauth2client.client import AccessTokenCredentials
google_credentials = AccessTokenCredentials(self.access_token, 'my-user-agent/1.0')
google_http = httplib2.Http()
google_http = google_credentials.authorize(google_http)
google_drive = discovery.build('drive', 'v3', http=google_http)
self.drive = google_drive.files()
# construct collection properties
self.permissions_write = True
self.permissions_content = True
self.drive_space = 'drive'
self.space_id = ''
if collection_name:
self.collection_name = collection_name
else:
self.collection_name = 'My Drive'
# construct file object
from labpack import __module__
from jsonmodel.loader import jsonLoader
drive_rules = jsonLoader(__module__, 'storage/google/drive-rules.json')
self.object_file = drive_rules['file_object']
# validate access token
self._validate_token()
示例14: dispatch
def dispatch(self):
self._checkauth()
self._decode()
if self._token is None:
self.abort(401)
else:
credentials = AccessTokenCredentials(self._token, "mirror-api-upload-handler/1.0")
http = httplib2.Http()
http = credentials.authorize(http)
http.timeout = 60
self._service = build("mirror", "v1", http=http, discoveryServiceUrl=utils.discovery_service_url)
super(UploadHandler, self).dispatch()
示例15: get_client
def get_client(self):
"""
Get an authenticated calendar api v3 instance.
"""
token = self.get_access_token()
if self.client is None:
credentials = AccessTokenCredentials(token, 'vetware/1.0')
# credentials = SignedJwtAssertionCredentials(self.email, self.private_key,
# "https://www.googleapis.com/auth/calendar")
http = credentials.authorize(Http())
self.client = build('calendar', 'v3', http=http)
return self.client