我正在编写一个从Google Cloud Vision API获取标签数据的测试。
在测试中,我使用vcrpy来存储标签检索的结果。
with vcr.use_cassette(
vcr_cassette_path.as_posix(), record_mode="twice",
match_on=["uri", "method"], decode_compressed_response=True):
labels = GCloudVisionLabelsRetriever().get_labels(self.FILE_PATH.as_posix())
它最终调用了这个块,正如谷歌自己定义的那样https://cloud.google.com/vision/docs/labels#detect_labels_in_a_local_image:
def detect_labels_from_path(path: str):
client = vision.ImageAnnotatorClient(
credentials=settings.GCLOUD_CREDENTIALS)
with io.open(path, 'rb') as image_file:
content = image_file.read()
image = vision.Image(content=content)
response = client.label_detection(image=image)
labels = response.label_annotations
return labels
第一次运行测试时,这是正常的。第二次测试时,我收到一个错误,说联系谷歌的内容未经验证。
我相信这是因为VCR不支持gRPC,而gRPC正是在幕后发生的事情。
我想知道是否有某种方法可以模拟这一点,或者可能有一个包可以处理python测试的gRPC?
有必要创建一个具有愿景的新客户端。ImageAnnotatorClient每次调用API时,您都需要创建客户端,然后循环client.label_detection。此外,我认为将Google凭据作为传递
client = vision.ImageAnnotatorClient(credentials=settings.GCLOUD_CREDENTIALS)
不是正确的方式,如果您在路径中配置了GCLOUD_CREDENTIALS,则无需指定它,例如:
client = vision.ImageAnnotatorClient()
尽管如此,如果您想指定服务帐户json的路径,您可以使用以下代码:
import os
import io
from google.cloud import vision
from google.oauth2 import service_account
#Loads the service account JSON credentials from a file
credentials = service_account.Credentials.from_service_account_file('SERVICE_ACCOUNT_KEY_FILE.json')
client = vision.ImageAnnotatorClient(credentials=credentials)
#I you have configure the GCLOUD_CREDENTIALS to your path, use this instead
#client = vision.ImageAnnotatorClient()
image_path = "wakeupcat.jpg"
with io.open(image_path, 'rb') as image_file:
content = image_file.read()
image = vision.types.Image(content=content)
# Performs label detection on the image file
response = client.label_detection(image=image)
labels = response.label_annotations
print('Labels:')
for label in labels:
print(label.description)