本文整理汇总了Python中oauth2client.contrib.django_orm.Storage类的典型用法代码示例。如果您正苦于以下问题:Python Storage类的具体用法?Python Storage怎么用?Python Storage使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Storage类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_credentials
def get_credentials(gmail_account):
"""
Get the credentials for the given EmailAccount, what should be a Gmail account.
If there are no valid credentials for the account, is_authorized is set to
False and there will be an InvalidCredentialsError raised.
Arguments:
gmail_account (instance): EmailAccount instance
Returns:
credentials for the EmailAccount
Raises:
InvalidCredentialsError, if there are no valid credentials for the account.
"""
storage = Storage(GmailCredentialsModel, 'id', gmail_account, 'credentials')
credentials = storage.get()
if credentials is not None and credentials.invalid is False:
return credentials
else:
gmail_account.is_authorized = False
gmail_account.save()
logger.error('No or invalid credentials for account %s' % gmail_account)
raise InvalidCredentialsError('No or invalid credentials for account %s' % gmail_account)
示例2: run_youtubesubs
def run_youtubesubs(ffu):
added = 0
storage = Storage(CredentialsModel, 'id', ffu.credentials, 'credential')
credential = storage.get()
if credential is None or credential.invalid == True:
raise Exception("bad creds")
return added
http = httplib2.Http()
http = credential.authorize(http)
resp, data = http.request("%ssubscriptions?part=subscriberSnippet&myRecentSubscribers=true&maxResults=25" % BASE_URL)
data = json.loads(data)
if 'error' in data:
raise Exception("Error fetching youtubesubs: %s" % json.dumps(data['error']))
events = []
if 'items' in data:
for i in data['items']:
unique_id = i['subscriberSnippet']['channelId']
if YoutubeSubEvent.objects.filter(external_id=i['id'], updater=ffu).count() > 0:
break
details = json.dumps(i)
try:
ffe = YoutubeSubEvent(external_id=i['id'], updater=ffu, details=details)
events.append(ffe)
except Exception, E:
print "Failed in individual youtubesubs run: %s\nData:\n%s" % (E, details)
added += 1
for event in reversed(events):
try:
event.save()
added += 1
except Exception, E:
print "Failed in individual sponsor run: %s\nData:\n%s" % (E, ffe.details)
示例3: auth_granted
def auth_granted(request):
get_params = request.GET
try:
if 'error' in get_params:
raise ValueError('Error authorizing application: %s' % get_params[error])
session_key = request.session.session_key
session = Session.objects.get(pk = session_key)
flow_obj = FlowModel.objects.get(session_id = session)
flow = flow_obj.flow
credentials = flow.step2_exchange(get_params["code"])
http = httplib2.Http()
http = credentials.authorize(http)
(resp, content) = http.request("https://drchrono.com/api/users/current",
"GET")
data = json.loads(content.decode("utf-8"))
print(data)
doctor_id = data['doctor']
doctor = Doctor(pk = doctor_id)
doctor.save()
storage = Storage(CredentialsModel, 'doctor_id', doctor_id, "credential")
storage.put(credentials)
except ValueError as err:
print('Handling run-time error: ', err)
return render(request, "success.html")
示例4: index
def index(request):
'''I Have created a static user as I dont have any logged in user in my app right now'''
U = User(
username = 'example',
firstname= 'Bla Bla',
lastname= 'Bla Bla',
email = '[email protected]'
)
U.save()
#This is a class created by google to save the credentials automatically in the database
storage = Storage(CredentialsModel, 'id', U, 'credential')
credential = storage.get()
if credential is None or credential.invalid == True:
FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY,
U)
authorize_url = FLOW.step1_get_authorize_url()
print(authorize_url)
return HttpResponseRedirect(authorize_url)
else:
http = httplib2.Http()
http = credential.authorize(http)
service = build('drive', 'v3', http=http)
#GOOGLE DRIVE FUNCTION CALLS
id = getFolderID(service)
#id1 = creatingFolderInsideAFolder(service, id)
print("Successful")
return id
示例5: run_subs
def run_subs(ffu):
storage = Storage(CredentialsModel, 'id', ffu.credentials, 'credential')
credential = storage.get()
if credential is None or credential.invalid == True:
raise Exception("invalid credentials")
http = httplib2.Http()
http = credential.authorize(http)
service = discovery.build('gmail', 'v1', http)
output = ListRecentMessagesMatchingQuery(service, "me", '"has subscribed to you"')
added = 0
for item in output:
if SubEvent.objects.filter(external_id=item['id'], updater=ffu).count():
break
message = GetMessage(service, "me", item['id'])
headers = message['payload']['headers']
f, s, d = '', '', ''
for header in headers:
if header['name'] == "From": f = header['value']
if header['name'] == "Subject": s = header['value']
if header['name'] == "Date": d = header['value']
if '[email protected]' in f:
s = s.strip().replace(" has subscribed to you on YouTube!", "")
try:
e = SubEvent(external_id=item['id'], details = s, updater=ffu)
e.save()
added += 1
except Exception, E:
print "Failed to create specific subevent for %s: \n %s: %s" % (ffu.id, type(E), E)
示例6: run_fan_funding
def run_fan_funding(ffu):
added = 0
storage = Storage(CredentialsModel, 'id', ffu.credentials, 'credential')
credential = storage.get()
if credential is None or credential.invalid == True:
raise Exception("bad creds")
return added
http = httplib2.Http()
http = credential.authorize(http)
resp, data = http.request("%sfanFundingEvents?part=snippet&maxResults=5" % BASE_URL)
data = json.loads(data)
if 'error' in data:
raise Exception("Error fetching fanfunding: %s" % json.dumps(data['error']))
events = []
if 'items' in data:
for i in data['items']:
if FanFundingEvent.objects.filter(external_id=i['id'], updater=ffu).count() > 0:
break
details = json.dumps(i)
try:
ffe = FanFundingEvent(external_id=i['id'], updater=ffu, details=details)
ffe.save()
except Exception, E:
print "Failed in individual fan funding run: %s\nData:\n%s" % (E, details)
added += 1
示例7: events_get
def events_get(request):
REDIRECT_URI = "https://%s%s" % (
request.get_host(), reverse("scheduler:events_return"))
# FLOW = flow_from_clientsecrets(
# CLIENT_SECRETS,
# scope=SCOPES,
# redirect_uri=REDIRECT_URI
# )
FLOW = OAuth2WebServerFlow(
client_id='323423619559-orlpuuiaalb7sp3ooblt4mjmp32ffq1t.apps.googleusercontent.com',
client_secret=os.environ['CLIENT_SECRET'],
scope=SCOPES,
redirect_uri=REDIRECT_URI
)
user = request.user
storage = Storage(CredentialsModel, 'id', user, 'credential')
credential = storage.get()
if credential is None or credential.invalid is True:
FLOW.params['state'] = xsrfutil.generate_token(
settings.SECRET_KEY, user)
authorize_url = FLOW.step1_get_authorize_url()
f = FlowModel(id=user, flow=FLOW)
f.save()
return HttpResponseRedirect(authorize_url)
else:
http = httplib2.Http()
http = credential.authorize(http)
service = build('calendar', 'v3', http=http)
events = service.events().list(calendarId='primary').execute()
return Response(events)
示例8: finalize
def finalize(request):
ac = AppCreds(user=request.user, label=request.POST['label'])
ac.save()
credential = FLOW.step2_exchange(request.POST)
internal_label = "%s-%s" % (request.user.id, request.POST['label'])
storage = Storage(CredentialsModel, 'id', ac, 'credential')
storage.put(credential)
return HttpResponseRedirect("/googleaccount/")
示例9: auth_return
def auth_return(request):
if not xsrfutil.validate_token(settings.SECRET_KEY, request.REQUEST['state'],
request.user):
return HttpResponseBadRequest()
credential = FLOW.step2_exchange(request.REQUEST)
storage = Storage(CredentialsModel, 'id', request.user, 'credential')
storage.put(credential)
return HttpResponseRedirect("/")
示例10: oauth2callback
def oauth2callback(request):
if not xsrfutil.validate_token(settings.SECRET_KEY, str(request.GET['state']), request.user):
return HttpResponseBadRequest()
credential = FLOW.step2_exchange(request.GET)
storage = Storage(GoogleCredentialsModel, 'id', request.user, 'credential')
storage.put(credential)
redirect_url = request.session['redirect_uri_after_step2']
return HttpResponseRedirect(redirect_url)
示例11: index
def index(request):
'''I Have created a static user as I dont have any logged in user in my app right now'''
U = User(
username = 'example',
firstname= 'Bla Bla',
lastname= 'Bla Bla',
email = '[email protected]'
)
U.save()
#This is a class created by google to save the credentials automatically in the database
storage = Storage(CredentialsModel, 'id', U, 'credential')
credential = storage.get()
if credential is None or credential.invalid == True:
FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY,
U)
authorize_url = FLOW.step1_get_authorize_url()
print(authorize_url)
return HttpResponseRedirect(authorize_url)
else:
http = httplib2.Http()
http = credential.authorize(http)
service = build('calendar', 'v3', http=http)
listEvents(service)
'''Just For Testing'''
event = {
'summary': 'Google I/O 2015',
'location': '800 Howard St., San Francisco, CA 94103',
'description': 'A chance to hear more about Google\'s developer products.',
'start': {
'dateTime': '2016-04-07T09:00:00-07:00',
'timeZone': 'America/Los_Angeles',
},
'end': {
'dateTime': '2016-04-08T17:00:00-07:00',
'timeZone': 'America/Los_Angeles',
},
'recurrence': [
'RRULE:FREQ=DAILY'
],
'attendees': [
{'email': '[email protected]'}
],
'reminders': {
'useDefault': False,
'overrides': [
{'method': 'email', 'minutes': 24 * 60},
{'method': 'popup', 'minutes': 10},
],
},
}
link = addEvent(service,event)
print("Successful")
return HttpResponse(link)
示例12: auth_return_view
def auth_return_view(request):
user = request.user
if not xsrfutil.validate_token(settings.SECRET_KEY, str(request.GET['state']), user):
return HttpResponseBadRequest()
FLOW = FlowModel.objects.get(id=user).flow
credential = FLOW.step2_exchange(request.GET)
storage = Storage(CredentialsModel, 'id', user, 'credential')
storage.put(credential)
return HttpResponseRedirect('/oauth2')
示例13: auth_return
def auth_return(request):
user = request.user
FLOW = FlowModel.objects.get(id=user).flow
if not xsrfutil.validate_token(
settings.SECRET_KEY, FLOW.params['state'], user):
return HttpResponseBadRequest()
credential = FLOW.step2_exchange(request.GET['code'])
storage = Storage(CredentialsModel, 'id', user, 'credential')
storage.put(credential)
return HttpResponseRedirect(reverse("oauth2:index"))
示例14: test_locked_get_no_entities
def test_locked_get_no_entities(self, djangoModel):
entities = [
]
filter_mock = mock.Mock(return_value=entities)
object_mock = mock.Mock()
object_mock.filter = filter_mock
FakeCredentialsModelMock.objects = object_mock
storage = Storage(FakeCredentialsModelMock, self.key_name,
self.key_value, self.property_name)
credential = storage.locked_get()
self.assertIsNone(credential)
示例15: import_gsheet
def import_gsheet(request, id):
gsheet_endpoint = None
silo = None
read_url = request.GET.get('link', None)
file_id = request.GET.get('resource_id', None)
file_name = request.GET.get("name", "Google Sheet Import")
if read_url == None or file_id == None:
messages.error(request, "A Google Spreadsheet is not selected to import data from.")
return HttpResponseRedirect(reverse('index'))
storage = Storage(GoogleCredentialsModel, 'id', request.user, 'credential')
credential = storage.get()
if credential is None or credential.invalid == True:
FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, request.user)
authorize_url = FLOW.step1_get_authorize_url()
#FLOW.params.update({'redirect_uri_after_step2': "/export_gsheet/%s/?link=%s&resource_id=%s" % (id, read_url, file_id)})
request.session['redirect_uri_after_step2'] = "/import_gsheet/%s/?link=%s&resource_id=%s" % (id, read_url, file_id)
return HttpResponseRedirect(authorize_url)
credential_json = json.loads(credential.to_json())
user = User.objects.get(username__exact=request.user)
gsheet_endpoint = None
read_type = ReadType.objects.get(read_type="GSheet Import")
try:
silo = Silo.objects.get(id=id)
if silo.unique_fields.exists() == False:
messages.error(request, "A unique column must be specfied when importing to an existing table. <a href='%s'>Specify Unique Column</a>" % reverse_lazy('siloDetail', kwargs={"id": silo.id}))
return HttpResponseRedirect(request.META['HTTP_REFERER'])
except Silo.DoesNotExist:
silo = Silo(name=file_name, owner=request.user, public=False, description="Google Sheet Import")
silo.save()
try:
gsheet_endpoint = Read.objects.get(silos__id=id, type=read_type, silos__owner=user.id, resource_id=file_id, read_name='GSheet Import')
except Read.MultipleObjectsReturned:
messages.error(request, "There should not be multiple records for the same gsheet, silo, and owner")
except Read.DoesNotExist:
gsheet_endpoint = Read(read_name="GSheet Import", type=read_type, resource_id=file_id, owner=user)
gsheet_endpoint.read_url = read_url
gsheet_endpoint.save()
silo.reads.add(gsheet_endpoint)
silo.save()
except Exception as e:
messages.error(request, "An error occured: %" % e.message)
#print("about to export to gsheet: %s" % gsheet_endpoint.resource_id)
if import_from_google_spreadsheet(credential_json, silo, gsheet_endpoint.resource_id) == True:
link = "Your imported data is available at here. <a href='%s'>See the table</a>" % reverse_lazy('siloDetail', kwargs={"id": silo.id})
messages.success(request, link)
else:
messages.error(request, 'Something went wrong.')
#messages.success(request, "Now, it should import data from GSheet")
return HttpResponseRedirect(reverse('index'))