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


Python file.Storage方法代碼示例

本文整理匯總了Python中oauth2client.file.Storage方法的典型用法代碼示例。如果您正苦於以下問題:Python file.Storage方法的具體用法?Python file.Storage怎麽用?Python file.Storage使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在oauth2client.file的用法示例。


在下文中一共展示了file.Storage方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: main

# 需要導入模塊: from oauth2client import file [as 別名]
# 或者: from oauth2client.file import Storage [as 別名]
def main():
    # Arguments parsing
    parser = argparse.ArgumentParser("Client ID and Secret are mandatory arguments")
    parser.add_argument("-i", "--id", required=True, help="Client id", metavar='<client-id>')
    parser.add_argument("-s", "--secret", required=True, help="Client secret", 
        metavar='<client-secret>')
    parser.add_argument("-c", "--console", default=False, 
        help="Authenticate only using console (for headless systems)", action="store_true")
    args = parser.parse_args()

    # Scopes of authorization
    activity = "https://www.googleapis.com/auth/fitness.activity.write"
    body = "https://www.googleapis.com/auth/fitness.body.write"
    location = "https://www.googleapis.com/auth/fitness.location.write"
    scopes = activity + " " + body + " " + location

    flow = OAuth2WebServerFlow(args.id, args.secret, scopes)
    storage = Storage('google.json')
    flags = ['--noauth_local_webserver'] if args.console else []
    run_flow(flow, storage, argparser.parse_args(flags)) 
開發者ID:praveendath92,項目名稱:fitbit-googlefit,代碼行數:22,代碼來源:auth_google.py

示例2: get_credentials

# 需要導入模塊: from oauth2client import file [as 別名]
# 或者: from oauth2client.file import Storage [as 別名]
def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    credential_path = settings.creds_path + ".youtube-upload-credentials.json"
    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(settings.google_cred_upload, 'https://www.googleapis.com/auth/youtube.upload')
        flow.user_agent = 'youtube-upload'
        credentials = tools.run_flow(flow, store)
    return credentials 
開發者ID:HA6Bots,項目名稱:Automatic-Youtube-Reddit-Text-To-Speech-Video-Generator-and-Uploader,代碼行數:19,代碼來源:videouploader.py

示例3: _get_credentials

# 需要導入模塊: from oauth2client import file [as 別名]
# 或者: from oauth2client.file import Storage [as 別名]
def _get_credentials(self):
        """Get OAuth credentials

        :return: OAuth credentials
        :rtype: :class:`oauth2client.client.Credentials`
        """
        credential_dir = join(self.var_dir, 'cached_oauth_credentials')
        if not exists(credential_dir):
            makedirs(credential_dir)
        credential_path = join(credential_dir, 'googleapis.json')

        store = Storage(credential_path)
        credentials = store.get()
        if not credentials or credentials.invalid:
            flow = client.flow_from_clientsecrets(self.config['creds'],
                                                  self.config['scope'])
            flow.user_agent = 'Iris Gmail Integration'
            credentials = tools.run_flow(
                flow,
                store,
                tools.argparser.parse_args(args=['--noauth_local_webserver']))
            logger.info('Storing credentials to %s', credential_path)
        else:
            credentials.refresh(self.http)
        return credentials 
開發者ID:linkedin,項目名稱:iris-relay,代碼行數:27,代碼來源:gmail.py

示例4: get_oauth2_creds

# 需要導入模塊: from oauth2client import file [as 別名]
# 或者: from oauth2client.file import Storage [as 別名]
def get_oauth2_creds():
  '''Generates user credentials.
  
  Will prompt the user to authorize the client when run the first time.
  Saves the credentials in ~/bigquery_credentials.dat.
  '''
  flow  = flow_from_clientsecrets('edx2bigquery-client-key.json',
                                  scope=BIGQUERY_SCOPE)
  storage = Storage(os.path.expanduser('~/bigquery_credentials.dat'))
  credentials = storage.get()
  if credentials is None or credentials.invalid:
    flags = tools.argparser.parse_args([])
    credentials = tools.run_flow(flow, storage, flags)
  else:
    # Make sure we have an up-to-date copy of the creds.
    credentials.refresh(httplib2.Http())
  return credentials 
開發者ID:mitodl,項目名稱:edx2bigquery,代碼行數:19,代碼來源:auth.py

示例5: build_service

# 需要導入模塊: from oauth2client import file [as 別名]
# 或者: from oauth2client.file import Storage [as 別名]
def build_service(secret, credentials):
    """
    Build reference to a BigQuery service / API.
    
    Parameters
    ----------
    secret : string
        Path to the secret files
    credentials : string
        Path to the credentials files

    Returns
    -------
    out : object
        The service reference
    """
    flow = flow_from_clientsecrets(secret, scope="https://www.googleapis.com/auth/bigquery")
    storage = Storage(credentials)
    credentials = storage.get()

    if credentials is None or credentials.invalid:
        credentials = tools.run_flow(flow, storage, tools.argparser.parse_args([]))

    http = credentials.authorize(httplib2.Http())
    return build("bigquery", "v2", http=http) 
開發者ID:apassant,項目名稱:deezer-bigquery,代碼行數:27,代碼來源:bigquery.py

示例6: get_credentials

# 需要導入模塊: from oauth2client import file [as 別名]
# 或者: from oauth2client.file import Storage [as 別名]
def get_credentials():
    """
    credentialsファイルを生成する
    """
    dirname = os.path.dirname(__file__)
    credential_path = os.path.join(dirname, CREDENTIAL_FILE)
    client_secret_file = os.path.join(dirname, CLIENT_SECRET_FILE)

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(client_secret_file, SCOPES)
        flow.user_agent = APPLICATION_NAME
        credentials = tools.run_flow(flow, store)
        print('credentialsを{}に保存しました'.format(credential_path))
    return credentials 
開發者ID:pyconjp,項目名稱:pyconjpbot,代碼行數:18,代碼來源:google_api.py

示例7: _get_credentials

# 需要導入模塊: from oauth2client import file [as 別名]
# 或者: from oauth2client.file import Storage [as 別名]
def _get_credentials(conf):
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    store = Storage(conf.CREDENTIAL_FILE)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(conf.CLIENT_SECRET_FILE, conf.SCOPES)
        flow.user_agent = conf.APPLICATION_NAME
        # avoid mess with argparse
        sys.argv = [sys.argv[0]]
        credentials = tools.run_flow(flow, store)
        print('Storing Google Calendar credentials to', conf.CREDENTIAL_FILE)
    return credentials 
開發者ID:mrts,項目名稱:ask-jira,代碼行數:21,代碼來源:google_calendar.py

示例8: handle_POST

# 需要導入模塊: from oauth2client import file [as 別名]
# 或者: from oauth2client.file import Storage [as 別名]
def handle_POST(self):
        redirect_uri = 'urn:ietf:wg:oauth:2.0:oob'
        oauth_scope = 'https://www.googleapis.com/auth/admin.reports.audit.readonly'

        try:
            client_id = self.args.get('client_id')
            client_secret = self.args.get('client_secret')
            auth_code = self.args.get('auth_code')

            storage = Storage(app_dir + os.path.sep + 'google_drive_creds')

            flow = OAuth2WebServerFlow(client_id, client_secret, oauth_scope, redirect_uri)
            credentials = flow.step2_exchange(auth_code)
            logger.debug("Obtained OAuth2 credentials!")
            storage.put(credentials)
        except Exception, e:
                logger.exception(e)
                self.response.write(e)

    # listen to all verbs 
開發者ID:splunk,項目名稱:splunk-ref-pas-code,代碼行數:22,代碼來源:configure_oauth.py

示例9: test_imap_old

# 需要導入模塊: from oauth2client import file [as 別名]
# 或者: from oauth2client.file import Storage [as 別名]
def test_imap_old(user):
    storage = Storage('credentials_file')
    credentials = storage.get()
    xoauth = xoauth2_str(user, credentials.access_token)
    conn = imaplib.IMAP4_SSL('imap.googlemail.com')
    conn.debug = 4

    conn.authenticate('XOAUTH2', lambda x: xoauth)

    status, labels = conn.list()

    conn.select("[Gmail]/All Mail")
    # Once authenticated everything from the impalib.IMAP4_SSL class will
    # work as per usual without any modification to your code.
    typ, msgnums = conn.search(None, 'X-GM-RAW', 'vget')

    print 'typ', typ
    print 'num', msgnums
    # conn.select('INBOX')
    # print conn.list() 
開發者ID:Schibum,項目名稱:sndlatr,代碼行數:22,代碼來源:cli.py

示例10: main

# 需要導入模塊: from oauth2client import file [as 別名]
# 或者: from oauth2client.file import Storage [as 別名]
def main():
    description = (
            'Obtain a Google Spreadsheets authorization token using credentials.json.'
            'To obtain the credentials.json file, follow instructions on this page:'
            'https://developers.google.com/sheets/api/quickstart/python'
            'Save credentials.json in the same directory with this script.'
            )

    parser = argparse.ArgumentParser(
                description=description,
                formatter_class=argparse.RawDescriptionHelpFormatter,
                parents=[tools.argparser])
    flags = parser.parse_args()

    home = str(Path.home())
    cachedir = os.path.join(home, '.cache', 'ingress-fieldmap')
    Path(cachedir).mkdir(parents=True, exist_ok=True)
    tokenfile = os.path.join(cachedir, 'token.json')

    store = file.Storage(tokenfile)
    flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
    creds = tools.run_flow(flow, store, flags)

    if creds:
        print('Token saved in %s' % tokenfile) 
開發者ID:mricon,項目名稱:ingress-fieldplan,代碼行數:27,代碼來源:obtainGSToken.py

示例11: reauth

# 需要導入模塊: from oauth2client import file [as 別名]
# 或者: from oauth2client.file import Storage [as 別名]
def reauth(self):
        # Set up the Drive v3 API
        SCOPES = ["https://www.googleapis.com/auth/drive"]
        store = file.Storage('credentials.json')
        credentials = store.get()
        if not credentials or credentials.invalid:
            try:
                flow = client.flow_from_clientsecrets(GoogleAPI.CLIENT_SECRET, SCOPES)
                credentials = tools.run_flow(flow, store)
            except ConnectionRefusedError:
                print("{!s} Make sure you've saved your OAuth credentials as {!s}".format(
                      GoogleAPI.ERROR_OUTPUT, GoogleAPI.CLIENT_SECRET))
                sys.exit(
                    "If you've already done that, then run uds.py without any arguments first.")

        self.service = build('drive', 'v3', http=credentials.authorize(Http()))
        return self.service 
開發者ID:stewartmcgown,項目名稱:uds,代碼行數:19,代碼來源:api.py

示例12: main

# 需要導入模塊: from oauth2client import file [as 別名]
# 或者: from oauth2client.file import Storage [as 別名]
def main():
    
    store = file.Storage('token.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
        creds = tools.run_flow(flow, store)
    service = build('gmail', 'v1', http=creds.authorize(Http()))

  
    results = service.users().labels().list(userId='me').execute()
    labels = results.get('labels', [])

    if not labels:
        print('No labels found.')
    else:
        print('Labels:')
        for label in labels:
            print(label['name']) 
開發者ID:DedSecInside,項目名稱:Awesome-Scripts,代碼行數:21,代碼來源:main.py

示例13: get_credentials

# 需要導入模塊: from oauth2client import file [as 別名]
# 或者: from oauth2client.file import Storage [as 別名]
def get_credentials(scope):
    credentials_file = get_credentials_filename(*sorted(scope.split(' ')))
    if not os.path.exists(credentials_file):
        raise RuntimeError(('Credentials file {} not found. Generate it through:\n' +
                           '\tpython -m platypush.plugins.google.credentials "{}" ' +
                           '<path to client_secret.json>\n' +
                           '\t\t[--auth_host_name AUTH_HOST_NAME]\n' +
                           '\t\t[--noauth_local_webserver]\n' +
                           '\t\t[--auth_host_port [AUTH_HOST_PORT [AUTH_HOST_PORT ...]]]\n' +
                           '\t\t[--logging_level [DEBUG,INFO,WARNING,ERROR,CRITICAL]]\n').
                           format(credentials_file, scope))

    store = Storage(credentials_file)
    credentials = store.get()

    if not credentials or credentials.invalid:
        credentials.refresh(httplib2.Http())

    return credentials 
開發者ID:BlackLight,項目名稱:platypush,代碼行數:21,代碼來源:credentials.py

示例14: _get_credentials

# 需要導入模塊: from oauth2client import file [as 別名]
# 或者: from oauth2client.file import Storage [as 別名]
def _get_credentials(self):
        """Get OAuth credentials

        :return: OAuth credentials
        :rtype: :class:`oauth2client.client.Credentials`
        """
        credential_dir = join(self.config['creds_cache_dir'], 'cached_oauth_credentials')
        if not exists(credential_dir):
            makedirs(credential_dir)
        credential_path = join(credential_dir, 'googleapis.json')

        store = Storage(credential_path)
        credentials = store.get()
        if not credentials or credentials.invalid:
            flow = client.flow_from_clientsecrets(self.config['creds'],
                                                  self.config['scope'])
            flow.user_agent = 'Iris Gmail Integration'
            credentials = tools.run_flow(
                flow, store, tools.argparser.parse_args(args=['--noauth_local_webserver']))
            logger.info('Storing credentials to %s' % credential_path)
        else:
            credentials.refresh(self.http)
        return credentials 
開發者ID:linkedin,項目名稱:iris,代碼行數:25,代碼來源:gmail.py

示例15: OAuth2Login

# 需要導入模塊: from oauth2client import file [as 別名]
# 或者: from oauth2client.file import Storage [as 別名]
def OAuth2Login(client_secrets, credential_store, email):
    scope='https://picasaweb.google.com/data/'
    user_agent='myapp'

    storage = Storage(credential_store)
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        flow = flow_from_clientsecrets(client_secrets, scope=scope, redirect_uri='urn:ietf:wg:oauth:2.0:oob')
        uri = flow.step1_get_authorize_url()
        webbrowser.open(uri)
        code = raw_input('Enter the authentication code: ').strip()
        credentials = flow.step2_exchange(code)
        storage.put(credentials)

    if (credentials.token_expiry - datetime.utcnow()) < timedelta(minutes=5):
        http = httplib2.Http()
        http = credentials.authorize(http)
        credentials.refresh(http)

    gd_client = gdata.photos.service.PhotosService(source=user_agent,
                                               email=email,
                                               additional_headers={'Authorization' : 'Bearer %s' % credentials.access_token})

    return gd_client 
開發者ID:wavemaking,項目名稱:GooglePhotosSync,代碼行數:26,代碼來源:gd_client_oauth.py


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