本文整理汇总了Python中oauth2client.contrib.django_orm.Storage.get方法的典型用法代码示例。如果您正苦于以下问题:Python Storage.get方法的具体用法?Python Storage.get怎么用?Python Storage.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类oauth2client.contrib.django_orm.Storage
的用法示例。
在下文中一共展示了Storage.get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run_fan_funding
# 需要导入模块: from oauth2client.contrib.django_orm import Storage [as 别名]
# 或者: from oauth2client.contrib.django_orm.Storage import get [as 别名]
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
示例2: events_get
# 需要导入模块: from oauth2client.contrib.django_orm import Storage [as 别名]
# 或者: from oauth2client.contrib.django_orm.Storage import get [as 别名]
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)
示例3: run_subs
# 需要导入模块: from oauth2client.contrib.django_orm import Storage [as 别名]
# 或者: from oauth2client.contrib.django_orm.Storage import get [as 别名]
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)
示例4: get_credentials
# 需要导入模块: from oauth2client.contrib.django_orm import Storage [as 别名]
# 或者: from oauth2client.contrib.django_orm.Storage import get [as 别名]
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)
示例5: index
# 需要导入模块: from oauth2client.contrib.django_orm import Storage [as 别名]
# 或者: from oauth2client.contrib.django_orm.Storage import get [as 别名]
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
示例6: run_youtubesubs
# 需要导入模块: from oauth2client.contrib.django_orm import Storage [as 别名]
# 或者: from oauth2client.contrib.django_orm.Storage import get [as 别名]
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)
示例7: index
# 需要导入模块: from oauth2client.contrib.django_orm import Storage [as 别名]
# 或者: from oauth2client.contrib.django_orm.Storage import get [as 别名]
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)
示例8: import_gsheet
# 需要导入模块: from oauth2client.contrib.django_orm import Storage [as 别名]
# 或者: from oauth2client.contrib.django_orm.Storage import get [as 别名]
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'))
示例9: get_credential_object
# 需要导入模块: from oauth2client.contrib.django_orm import Storage [as 别名]
# 或者: from oauth2client.contrib.django_orm.Storage import get [as 别名]
def get_credential_object(user, prompt=None):
storage = Storage(GoogleCredentialsModel, 'id', user, 'credential')
credential_obj = storage.get()
if credential_obj is None or credential_obj.invalid == True or prompt:
FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY, user)
FLOW.params['access_type'] = 'offline'
FLOW.params['approval_prompt'] = 'force'
authorize_url = FLOW.step1_get_authorize_url()
return {"level": messages.ERROR,
"msg": "Requires Google Authorization Setup",
"redirect": authorize_url,
"redirect_uri_after_step2": True}
#print(json.loads(credential_obj.to_json()))
return credential_obj
示例10: export_gsheet
# 需要导入模块: from oauth2client.contrib.django_orm import Storage [as 别名]
# 或者: from oauth2client.contrib.django_orm.Storage import get [as 别名]
def export_gsheet(request, id):
gsheet_endpoint = None
read_url = request.GET.get('link', None)
file_id = request.GET.get('resource_id', None)
if read_url == None or file_id == None:
messages.error(request, "A Google Spreadsheet is not selected to import data to it.")
return HttpResponseRedirect(reverse('listSilos'))
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'] = "/export_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="Google Spreadsheet")
try:
gsheet_endpoint = Read.objects.get(silos__id=id, type=read_type, silos__owner=user.id, read_name='Google')
except Read.MultipleObjectsReturned:
gsheet_endpoints = Read.objects.get(silos__id=id, type=read_type, silos__owner=user.id, read_name='Google')
for endpoint in gsheet_endpoints:
if endpoint.resource_id:
gsheet_endpoint = endpoint
except Read.DoesNotExist:
gsheet_endpoint = Read(read_name="Google", type=read_type, owner=user)
gsheet_endpoint.save()
silo = Silo.objects.get(id=id)
silo.reads.add(gsheet_endpoint)
silo.save()
except Exception as e:
messages.error(request, "An error occured: %" % e.message)
if gsheet_endpoint.resource_id == "None" or gsheet_endpoint.resource_id == None:
gsheet_endpoint.resource_id = file_id
gsheet_endpoint.read_url = read_url
gsheet_endpoint.save()
#print("about to export to gsheet: %s" % gsheet_endpoint.resource_id)
if export_to_google_spreadsheet(credential_json, id, gsheet_endpoint.resource_id) == True:
link = "Your exported data is available at <a href=" + gsheet_endpoint.read_url + " target='_blank'>Google Spreadsheet</a>"
messages.success(request, link)
else:
messages.error(request, 'Something went wrong.')
return HttpResponseRedirect(reverse('listSilos'))
示例11: inner
# 需要导入模块: from oauth2client.contrib.django_orm import Storage [as 别名]
# 或者: from oauth2client.contrib.django_orm.Storage import get [as 别名]
def inner(request, *args, **kwargs):
# Try grabbing credential from storage
storage = Storage(CredentialsModel, 'id',
request.user, 'credential')
credential = storage.get()
# Begin process of getting a new credential
if credential is None or credential.invalid:
request.session['next_view'] = request.path
request.session['gauth_scope'] = scope
return (HttpResponse('Unauthorized', status=401)
if ajax else redirect('gauth_index'))
# Everything went well, call wrapped view and give credential to it
kwargs['credential'] = credential
return func(request, *args, **kwargs)
示例12: ytapicall
# 需要导入模块: from oauth2client.contrib.django_orm import Storage [as 别名]
# 或者: from oauth2client.contrib.django_orm.Storage import get [as 别名]
def ytapicall(appcreds, url, post_json=None):
storage = Storage(CredentialsModel, 'id', appcreds, 'credential')
credential = storage.get()
if credential is None or credential.invalid == True:
raise CredentialsException("bad creds")
http = httplib2.Http()
http = credential.authorize(http)
if post_json:
resp, data = http.request(url, "POST", json.dumps(post_json), headers = {'content-type': 'application/json'})
else:
resp, data = http.request(url)
data = json.loads(data)
if 'error' in data:
e = YouTubeAPIException("YouTube API Error: %s" % data['error']['message'])
e.data = data
raise e
return data
示例13: get_channel
# 需要导入模块: from oauth2client.contrib.django_orm import Storage [as 别名]
# 或者: from oauth2client.contrib.django_orm.Storage import get [as 别名]
def get_channel(appcreds, force=False):
if force == False and appcreds.channel_id:
return appcreds.channel_id
storage = Storage(CredentialsModel, 'id', appcreds, 'credential')
credential = storage.get()
if credential is None or credential.invalid == True:
raise Exception("bad creds")
http = httplib2.Http()
http = credential.authorize(http)
resp, data = http.request("%schannels?part=id&mine=true" % BASE_URL)
data = json.loads(data)
if data['pageInfo']['totalResults'] != 1:
raise Exception("Bad returned channel list: %s" % data)
channel_id = data['items'][0]['id']
appcreds.channel_id = channel_id
appcreds.save()
return channel_id
示例14: get_api_data
# 需要导入模块: from oauth2client.contrib.django_orm import Storage [as 别名]
# 或者: from oauth2client.contrib.django_orm.Storage import get [as 别名]
def get_api_data():
all_data = {}
for doctor in Doctor.objects.all():
storage = Storage(CredentialsModel, 'doctor_id', doctor.id, 'credential')
credentials = storage.get()
http = httplib2.Http()
http = credentials.authorize(http)
storage.put(credentials)
(resp, content) = http.request("https://drchrono.com/api/patients",
"GET")
data = json.loads(content.decode("utf-8"))
all_data[doctor.id] = data
return all_data
示例15: index
# 需要导入模块: from oauth2client.contrib.django_orm import Storage [as 别名]
# 或者: from oauth2client.contrib.django_orm.Storage import get [as 别名]
def index(request):
storage = Storage(CredentialsModel, '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()
return HttpResponseRedirect(authorize_url)
else:
http = httplib2.Http()
http = credential.authorize(http)
service = build("plus", "v1", http=http)
activities = service.activities()
activitylist = activities.list(collection='public',
userId='me').execute()
logging.info(activitylist)
return render(request, 'plus/welcome.html', {
'activitylist': activitylist,
})