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


Python client.OAuth2WebServerFlow方法代碼示例

本文整理匯總了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)) 
開發者ID:praveendath92,項目名稱:fitbit-googlefit,代碼行數:22,代碼來源:auth_google.py

示例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) 
開發者ID:mortcanty,項目名稱:earthengine,代碼行數:22,代碼來源:appengine.py

示例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 
開發者ID:splunk,項目名稱:splunk-ref-pas-code,代碼行數:22,代碼來源:configure_oauth.py

示例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 
開發者ID:Deltares,項目名稱:aqua-monitor,代碼行數:25,代碼來源:views.py

示例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) 
開發者ID:Deltares,項目名稱:aqua-monitor,代碼行數:20,代碼來源:appengine.py

示例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,
    ) 
開發者ID:getsentry,項目名稱:freight,代碼行數:20,代碼來源:auth.py

示例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) 
開發者ID:fniephaus,項目名稱:alfred-gmail,代碼行數:20,代碼來源:appengine.py

示例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 
開發者ID:cfbao,項目名稱:google-drive-trash-cleaner,代碼行數:20,代碼來源:cleaner.py

示例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 
開發者ID:mkaraniya,項目名稱:BotHub,代碼行數:23,代碼來源:gdrivenew.py

示例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 
開發者ID:Dark-Princ3,項目名稱:X-tra-Telegram,代碼行數:23,代碼來源:gDrive.py

示例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) 
開發者ID:elsigh,項目名稱:browserscope,代碼行數:41,代碼來源:appengine_rpc_httplib2.py

示例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.' 
開發者ID:mortcanty,項目名稱:earthengine,代碼行數:39,代碼來源:appengine.py

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


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