當前位置: 首頁>>代碼示例>>Python>>正文


Python django_orm.Storage類代碼示例

本文整理匯總了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)
開發者ID:HelloLily,項目名稱:hellolily,代碼行數:27,代碼來源:credentials.py

示例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)
開發者ID:google,項目名稱:mirandum,代碼行數:33,代碼來源:support.py

示例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")
開發者ID:jherrr,項目名稱:DrChrono_Bday_Notifications,代碼行數:34,代碼來源:views.py

示例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
開發者ID:IEEEDTU,項目名稱:gmail-api,代碼行數:30,代碼來源:views.py

示例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) 
開發者ID:Bhasmithal,項目名稱:mirandum,代碼行數:28,代碼來源:support.py

示例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
開發者ID:Bhasmithal,項目名稱:mirandum,代碼行數:26,代碼來源:support.py

示例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)
開發者ID:Zenonquest,項目名稱:schedule,代碼行數:30,代碼來源:gCal.py

示例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/")
開發者ID:Bhasmithal,項目名稱:mirandum,代碼行數:8,代碼來源:views.py

示例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("/")
開發者ID:anabelensc,項目名稱:google-api-python-client,代碼行數:8,代碼來源:views.py

示例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)
開發者ID:mercycorps,項目名稱:TolaTables,代碼行數:9,代碼來源:gviews_v4.py

示例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)
開發者ID:vaibhavsawhney,項目名稱:Google-Gmail-API-Python-Django-1.9-Sample,代碼行數:57,代碼來源:views.py

示例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')
開發者ID:aejones89,項目名稱:calendar_app,代碼行數:9,代碼來源:views.py

示例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"))
開發者ID:david--wright,項目名稱:bookserver,代碼行數:10,代碼來源:views.py

示例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)
開發者ID:Natarajan-R,項目名稱:oauth2client,代碼行數:12,代碼來源:test_django_orm.py

示例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'))
開發者ID:mercycorps,項目名稱:TolaTables,代碼行數:53,代碼來源:google_views.py


注:本文中的oauth2client.contrib.django_orm.Storage類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。