【问题标题】:Static gcloud token?静态 gcloud 令牌?
【发布时间】:2020-07-15 10:11:40
【问题描述】:

我是使用 Google Cloud 套件的新手,我正在尝试构建一个简单的 Python 脚本,该脚本调用 Vision API 以提取一组文件的文档文本。为此,我复制了此处的说明:

https://cloud.google.com/vision/docs/ocr#vision_text_detection-drest

目前我的 python 脚本看起来像这样:

key = <my_api_key>
url = 'https://vision.googleapis.com/v1/images:annotate?key=' + key
access_token = <my_access_token>
headers = {'Authorization': 'Bearer ' + access_token,
           'Content-Type': 'application/json; charset=utf-8'}

access_token 由哪里决定

$ gcloud auth application-default print-access-token

(通常,在 bash 中使用 curl 运行时,我会将 access_token 替换为 $(gcloud auth ...)。)接下来,

import base64
import json
import requests
with open(file, 'rb') as f : 
    encoding = base64.b64encode(f.read()).decode('ascii')
    request = {'requests': [{'features': [{'type': 'DOCUMENT_TEXT_DETECTION'}],
                             'image': {'content': encoding},
                             'imageContext': {'languageHints': ['en']}}]}
    with open('request.json', 'w') as r :
        r.write(json.dumps(request))
    with open('request.json') as d : 
        response = requests.post(url = url, data = d, headers = headers)

即我将“文件”转换为 base64,创建 requests.json 文件然后发布它。

我对身份验证不是很熟悉,所以这是我的问题:据我所知,目前我拥有的唯一身份验证是 API 密钥和服务帐户。我使用服务帐户 json 文件来设置 GOOGLE_APPLICATION_CREDENTIALS 并允许我调用

$ gcloud auth application-default print-access-token

我面临的唯一问题是令牌似乎已过期。所以我必须 (a) 回到 bash,设置 GOOGLE_APPLICATION_CREDENTIALS,再次调用上述命令,然后将令牌复制并粘贴到我的代码中。是否有开箱即用的类型解决方案,允许我使用静态令牌或静态方式来运行我的脚本?

【问题讨论】:

  • 你有什么理由使用请求和其他 api 而不是谷歌提供的wrapper library?该库负责所有的身份验证,并添加了一些抽象,使使用视觉 api 变得更加容易。
  • 没有特别的原因 - 如果有必要我会使用它,但我通常只是将我成功的测试(例如使用 api)翻译成 python 以避免依赖库的任何麻烦并且(通常)具有更大的灵活性.我想我没有预料到将我的测试迁移到 python 中会出现任何问题。不过感谢您的建议 - 如果在这里找不到解决方案,我将使用该库。
  • 他们还有一个专门用于身份验证的模块google-auth。如果您想将第三方要求降到最低,您可以尝试使用那个。
  • @swenzel 的推荐不错。请不要重新实现身份验证,特别是当 Google 为您提供此功能并使其变得非常容易时。见:cloud.google.com/docs/authentication/…
  • 如果您真的想自己实现身份验证,请查看this doc,了解如何从您的应用中请求访问令牌以便稍后刷新它。

标签: python google-cloud-platform gcloud


【解决方案1】:

感谢评论的人 - 似乎最简单的身份验证方法是使用服务帐户和关联的 .json 文件,而不是将 GOOGLE_APPLICATION_CREDENTIALS 添加到路径。

from google.cloud import vision
service_account_json = <my_service_account_json>
client = vision.ImageAnnotatorClient.from_service_account_json(service_account_json)

仍然可以通过将请求作为 dict(相当于通常的 json)发送到请求中来传递参数。

def annotate (filename) :
    with open(filename, 'rb') as f :
        encoding = f.read()
    request = {'image': {'content': encoding},
               'features': [{'type': 'DOCUMENT_TEXT_DETECTION'}],
               'image_context': {'language_hints': ['en']}}
    response = client.annotate_image(request=request)
    return response

【讨论】:

    猜你喜欢
    • 2016-01-21
    • 2021-10-09
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-03
    • 2020-05-06
    • 2018-12-04
    相关资源
    最近更新 更多