【问题标题】:How to add client_secret without using argparser?如何在不使用 argparse 的情况下添加 client_secret?
【发布时间】:2015-04-17 13:57:14
【问题描述】:

我想测试 Google Genomics。我有一个项目,我可以从getting started with the api 运行main.py。但是这个文件隐藏在 oauth2client 的底层是如何生成凭据的:

import argparse
import httplib2
from apiclient.discovery import build
from collections import Counter
from oauth2client import tools
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import run_flow

# For these examples, the client id and client secret are command-line arguments
parser = argparse.ArgumentParser(description=__doc__,
    formatter_class=argparse.RawDescriptionHelpFormatter,
    parents=[tools.argparser])
parser.add_argument('--client_secrets_filename',
                    default='client_secrets.json',
                    help='The filename of a client_secrets.json file from a '
                         'Google "Client ID for native application" that '
                         'has the Genomics API enabled.')
flags = parser.parse_args()

# Authorization
storage = Storage('credentials.dat')
credentials = storage.get()
if credentials is None or credentials.invalid:
  flow = flow_from_clientsecrets(
    flags.client_secrets_filename,
    scope='https://www.googleapis.com/auth/genomics',
    message='You need to copy a client_secrets.json file into this directory, '
            'or pass in the --client_secrets_filename option to specify where '
            'one exists. See the README for more help.')
  credentials = run_flow(flow, storage, flags)

# Create a genomics API service
http = httplib2.Http()
http = credentials.authorize(http)

有人可以解释一下代码是什么吗?我怎么能把它转换成没有 argparse 的东西?

我尝试了 google-api 文档的其他解决方案,但主要是我不明白正在做什么,所以我不明白我应该做什么。 (我也不完全了解 OAuth2client) This answer 建议 argparse 是强制性的。但是this 其他使用 google-api-python-client 的方式不要使用它...

【问题讨论】:

    标签: python google-api-python-client oauth2client google-genomics


    【解决方案1】:

    如果您愿意,您可以改用 API 密钥,这在实现服务器时更实用 - 尽管您不想与任何人共享它。下面是两个很好的链接,它们描述了 Oauth2 协议在提供对 Google API 的访问方面的工作原理:

    https://developers.google.com/identity/protocols/OAuth2

    https://developers.google.com/identity/protocols/OAuth2WebServer

    希望对你有帮助,

    保罗

    【讨论】:

    • 感谢 Paul,我最终使用了 service = build('genomics', 'v1beta2', developerKey=api_key) 的 API 密钥
    • 太棒了 - 你不会后悔的 :) 是的,使用 API 密钥让我通常更专注于分析或代码。
    【解决方案2】:

    argparse 的目的是解析命令行选项。如果您打算在命令行中接受参数,那么使用 argparse 比不使用要容易得多。

    如果您想硬编码参数(或以其他方式检索它们),您可以删除所有 parser 行,并将 flags 变量替换为适当的值(例如,对于客户端秘密文件名)。

    【讨论】:

    • 我想对参数进行硬编码,但您能告诉我如何正确替换 flags 变量吗?感谢您的回答
    • 用硬编码的值替换flags.client_secrets_filename
    猜你喜欢
    • 2019-07-03
    • 2018-05-21
    • 2019-04-22
    • 2021-10-17
    • 2011-07-12
    • 2022-07-01
    • 2013-05-27
    • 2022-01-08
    • 1970-01-01
    相关资源
    最近更新 更多