NameError:名称'creds'未定义

时间:2018-02-12 14:19:22

标签: python google-cloud-platform google-vision

我收到错误,NameError:名称'creds'未定义。我想使用Google Cloud Vision API。我在Google Cloud中设置了各种内容,我下载了google-cloud-sdk-180.0.0-darwin-x86_64 .tar.gz,我运行命令./google-cloud-sdk/bin/gcloud init,它成功了。我写了test.py

import io
import os

# Imports the Google Cloud client library
from google.cloud import vision
from google.cloud.vision import types

# Instantiates a client
client = vision.ImageAnnotatorClient(credentials=creds,)

# The name of the image file to annotate
file_name = os.path.join(
    os.path.dirname(__file__),
    'cat.jpg')

# Loads the image into memory
with io.open(file_name, 'rb') as image_file:
    content = image_file.read()

当我运行此代码时,

Traceback (most recent call last):
    client = vision.ImageAnnotatorClient(credentials=creds,)
NameError: name 'creds' is not defined

错误发生了。 我通过看https://github.com/GoogleCloudPlatform/google-cloud-python/blob/master/docs/vision/index.rst#id8来编写代码,所以我重写了

client = vision.ImageAnnotatorClient()
发生

错误google.auth.exceptions.DefaultCredentialsError:无法自动确定凭据。请设置GOOGLE_APPLICATION_CREDENTIALS或 显式创建凭证并重新运行应用程序。更多 信息,请看 https://developers.google.com/accounts/docs/application-default-credentials。 。我真的不明白为什么会发生这个错误。我安装了config.json& index.js& package.json与test.py位于同一目录但发生同样的错误。我运行命令gcloud components update && gcloud components install beta但找不到zsh:命令:gcloud错误发生。我该如何解决这个问题?我的代码有什么问题?

1 个答案:

答案 0 :(得分:1)

要修复此错误,您需要定义变量 这是我在谷歌云上发现的可变信用卡 在客户端之前添加:

creds = mock.Mock(spec=credentials.Credentials)

并在导入行

from google.auth import credentials

import mock