本文整理汇总了Python中oauth2client.client.OAuth2WebServerFlow方法的典型用法代码示例。如果您正苦于以下问题:Python client.OAuth2WebServerFlow方法的具体用法?Python client.OAuth2WebServerFlow怎么用?Python client.OAuth2WebServerFlow使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类oauth2client.client
的用法示例。
在下文中一共展示了client.OAuth2WebServerFlow方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from oauth2client import client [as 别名]
# 或者: from oauth2client.client import OAuth2WebServerFlow [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: _create_flow
# 需要导入模块: from oauth2client import client [as 别名]
# 或者: from oauth2client.client import OAuth2WebServerFlow [as 别名]
def _create_flow(self, request_handler):
"""Create the Flow object.
The Flow is calculated lazily since we don't know where this app is
running until it receives a request, at which point redirect_uri can be
calculated and then the Flow object can be constructed.
Args:
request_handler: webapp.RequestHandler, the request handler.
"""
if self.flow is None:
redirect_uri = request_handler.request.relative_url(
self._callback_path) # Usually /oauth2callback
self.flow = OAuth2WebServerFlow(self._client_id, self._client_secret,
self._scope, redirect_uri=redirect_uri,
user_agent=self._user_agent,
auth_uri=self._auth_uri,
token_uri=self._token_uri,
revoke_uri=self._revoke_uri,
**self._kwargs)
示例3: handle_POST
# 需要导入模块: from oauth2client import client [as 别名]
# 或者: from oauth2client.client import OAuth2WebServerFlow [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
示例4: _make_flow
# 需要导入模块: from oauth2client import client [as 别名]
# 或者: from oauth2client.client import OAuth2WebServerFlow [as 别名]
def _make_flow(request, scopes, return_url=None):
"""Creates a Web Server Flow"""
# Generate a CSRF token to prevent malicious requests.
csrf_token = hashlib.sha256(os.urandom(1024)).hexdigest()
request.session[_CSRF_KEY] = csrf_token
state = json.dumps({
'csrf_token': csrf_token,
'return_url': return_url,
})
flow = client.OAuth2WebServerFlow(
client_id=django_util.oauth2_settings.client_id,
client_secret=django_util.oauth2_settings.client_secret,
scope=scopes,
state=state,
redirect_uri=request.build_absolute_uri(
urlresolvers.reverse("google_oauth:callback")))
flow_key = _FLOW_KEY.format(csrf_token)
request.session[flow_key] = pickle.dumps(flow)
return flow
示例5: _create_flow
# 需要导入模块: from oauth2client import client [as 别名]
# 或者: from oauth2client.client import OAuth2WebServerFlow [as 别名]
def _create_flow(self, request_handler):
"""Create the Flow object.
The Flow is calculated lazily since we don't know where this app is
running until it receives a request, at which point redirect_uri can be
calculated and then the Flow object can be constructed.
Args:
request_handler: webapp.RequestHandler, the request handler.
"""
if self.flow is None:
redirect_uri = request_handler.request.relative_url(
self._callback_path) # Usually /oauth2callback
self.flow = OAuth2WebServerFlow(
self._client_id, self._client_secret, self._scope,
redirect_uri=redirect_uri, user_agent=self._user_agent,
auth_uri=self._auth_uri, token_uri=self._token_uri,
revoke_uri=self._revoke_uri, **self._kwargs)
示例6: get_auth_flow
# 需要导入模块: from oauth2client import client [as 别名]
# 或者: from oauth2client.client import OAuth2WebServerFlow [as 别名]
def get_auth_flow(redirect_uri=None):
# XXX(dcramer): we have to generate this each request because oauth2client
# doesn't want you to set redirect_uri as part of the request, which causes
# a lot of runtime issues.
auth_uri = GOOGLE_AUTH_URI
if current_app.config["GOOGLE_DOMAIN"]:
auth_uri = auth_uri + "?hd=" + current_app.config["GOOGLE_DOMAIN"]
return OAuth2WebServerFlow(
client_id=current_app.config["GOOGLE_CLIENT_ID"],
client_secret=current_app.config["GOOGLE_CLIENT_SECRET"],
scope="https://www.googleapis.com/auth/userinfo.email",
redirect_uri=redirect_uri,
user_agent=f"freight/{freight.VERSION} (python {PYTHON_VERSION})",
auth_uri=auth_uri,
token_uri=GOOGLE_TOKEN_URI,
revoke_uri=GOOGLE_REVOKE_URI,
)
示例7: _create_flow
# 需要导入模块: from oauth2client import client [as 别名]
# 或者: from oauth2client.client import OAuth2WebServerFlow [as 别名]
def _create_flow(self, request_handler):
"""Create the Flow object.
The Flow is calculated lazily since we don't know where this app is
running until it receives a request, at which point redirect_uri can be
calculated and then the Flow object can be constructed.
Args:
request_handler: webapp.RequestHandler, the request handler.
"""
if self.flow is None:
redirect_uri = request_handler.request.relative_url(
self._callback_path) # Usually /oauth2callback
self.flow = client.OAuth2WebServerFlow(
self._client_id, self._client_secret, self._scope,
redirect_uri=redirect_uri, user_agent=self._user_agent,
auth_uri=self._auth_uri, token_uri=self._token_uri,
revoke_uri=self._revoke_uri, **self._kwargs)
示例8: get_credentials
# 需要导入模块: from oauth2client import client [as 别名]
# 或者: from oauth2client.client import OAuth2WebServerFlow [as 别名]
def get_credentials(flags):
"""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(flags.credfile)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.OAuth2WebServerFlow(**CLIENT_CREDENTIAL)
credentials = tools.run_flow(flow, store, flags)
print('credential file saved at\n\t' + flags.credfile)
return credentials
示例9: create_token_file
# 需要导入模块: from oauth2client import client [as 别名]
# 或者: from oauth2client.client import OAuth2WebServerFlow [as 别名]
def create_token_file(token_file, event):
# Run through the OAuth flow and retrieve credentials
flow = OAuth2WebServerFlow(
CLIENT_ID,
CLIENT_SECRET,
OAUTH_SCOPE,
redirect_uri=REDIRECT_URI
)
authorize_url = flow.step1_get_authorize_url()
async with event.client.conversation(Config.PRIVATE_GROUP_BOT_API_ID) as conv:
await conv.send_message(f"Go to the following link in your browser: {authorize_url} and reply the code")
response = conv.wait_event(events.NewMessage(
outgoing=True,
chats=Config.PRIVATE_GROUP_BOT_API_ID
))
response = await response
code = response.message.message.strip()
credentials = flow.step2_exchange(code)
storage = Storage(token_file)
storage.put(credentials)
return storage
示例10: create_token_file
# 需要导入模块: from oauth2client import client [as 别名]
# 或者: from oauth2client.client import OAuth2WebServerFlow [as 别名]
def create_token_file(token_file, event):
# Run through the OAuth flow and retrieve credentials
flow = OAuth2WebServerFlow(
CLIENT_ID,
CLIENT_SECRET,
OAUTH_SCOPE,
redirect_uri=REDIRECT_URI
)
authorize_url = flow.step1_get_authorize_url()
async with bot.conversation(int(Var.PRIVATE_GROUP_ID)) as conv:
await conv.send_message(f"Go to the following link in your browser: {authorize_url} and reply the code")
response = conv.wait_event(events.NewMessage(
outgoing=True,
chats=int(Var.PRIVATE_GROUP_ID)
))
response = await response
code = response.message.message.strip()
credentials = flow.step2_exchange(code)
storage = Storage(token_file)
storage.put(credentials)
return storage
示例11: _Authenticate
# 需要导入模块: from oauth2client import client [as 别名]
# 或者: from oauth2client.client import OAuth2WebServerFlow [as 别名]
def _Authenticate(self, http, needs_auth):
"""Pre or Re-auth stuff...
This will attempt to avoid making any OAuth related HTTP connections or
user interactions unless it's needed.
Args:
http: An 'Http' object from httplib2.
needs_auth: If the user has already tried to contact the server.
If they have, it's OK to prompt them. If not, we should not be asking
them for auth info--it's possible it'll suceed w/o auth, but if we have
some credentials we'll use them anyway.
Raises:
AuthPermanentFail: The user has requested non-interactive auth but
the token is invalid.
"""
if needs_auth and (not self.credentials or self.credentials.invalid):
if self.refresh_token:
logger.debug('_Authenticate and skipping auth because user explicitly '
'supplied a refresh token.')
raise AuthPermanentFail('Refresh token is invalid.')
logger.debug('_Authenticate and requesting auth')
flow = client.OAuth2WebServerFlow(
client_id=self.client_id,
client_secret=self.client_secret,
scope=self.scope,
user_agent=self.user_agent)
self.credentials = tools.run(flow, self.storage)
if self.credentials and not self.credentials.invalid:
if not self.credentials.access_token_expired or needs_auth:
logger.debug('_Authenticate configuring auth; needs_auth=%s',
needs_auth)
self.credentials.authorize(http)
return
logger.debug('_Authenticate skipped auth; needs_auth=%s', needs_auth)
示例12: __init__
# 需要导入模块: from oauth2client import client [as 别名]
# 或者: from oauth2client.client import OAuth2WebServerFlow [as 别名]
def __init__(self, filename, scope, message=None, cache=None, **kwargs):
"""Constructor
Args:
filename: string, File name of client secrets.
scope: string or iterable of strings, scope(s) of the credentials being
requested.
message: string, A friendly string to display to the user if the
clientsecrets file is missing or invalid. The message may contain HTML
and will be presented on the web interface for any method that uses the
decorator.
cache: An optional cache service client that implements get() and set()
methods. See clientsecrets.loadfile() for details.
**kwargs: dict, Keyword arguments are passed along as kwargs to
the OAuth2WebServerFlow constructor.
"""
client_type, client_info = clientsecrets.loadfile(filename, cache=cache)
if client_type not in [
clientsecrets.TYPE_WEB, clientsecrets.TYPE_INSTALLED]:
raise InvalidClientSecretsError(
"OAuth2Decorator doesn't support this OAuth 2.0 flow.")
constructor_kwargs = dict(kwargs)
constructor_kwargs.update({
'auth_uri': client_info['auth_uri'],
'token_uri': client_info['token_uri'],
'message': message,
})
revoke_uri = client_info.get('revoke_uri')
if revoke_uri is not None:
constructor_kwargs['revoke_uri'] = revoke_uri
super(OAuth2DecoratorFromClientSecrets, self).__init__(
client_info['client_id'], client_info['client_secret'],
scope, **constructor_kwargs)
if message is not None:
self._message = message
else:
self._message = 'Please configure your application for OAuth 2.0.'
示例13: main
# 需要导入模块: from oauth2client import client [as 别名]
# 或者: from oauth2client.client import OAuth2WebServerFlow [as 别名]
def main():
DIR_NAME = path.dirname(path.abspath(__file__))
CODE_FILE = path.join(DIR_NAME, "code")
storage = Storage(path.join(DIR_NAME, "credentials"))
credentials = storage.get()
flow = OAuth2WebServerFlow(
client_id=conf.client_id,
client_secret=conf.client_secret,
scope="https://www.googleapis.com/auth/calendar",
redirect_uri="https://legacy.clist.by/api/google-calendar/exchange-code.php",
access_type="offline",
prompt="consent",
)
auth_uri = flow.step1_get_authorize_url()
code = None
if path.exists(CODE_FILE):
with open(CODE_FILE, "r") as fo:
code = fo.read().strip()
open(CODE_FILE, "w").close()
if code:
credentials = flow.step2_exchange(code)
storage.put(credentials)
remove(CODE_FILE)
else:
print(auth_uri)