本文整理汇总了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))
示例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
示例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
示例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)
示例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
示例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
示例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
示例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()
示例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)
示例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
示例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'])
示例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
示例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
示例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