首页 > 解决方案 > 从未托管在谷歌云平台上的本地项目访问谷歌云 API

问题描述

我想从本地 python 代码中使用谷歌云自然语言 API。由于项目限制,我无法在 GCP 平台上运行我的代码。我有谷歌云帐户和积分来启用和使用 API。google 是否允许使用 API 在本地平台上运行。任何示例代码都会有所帮助。

标签: pythongoogle-cloud-platformnlp

解决方案


1.创建或选择一个项目。

gcloud projects create nat-lan-api
gcloud config set project nat-lan-api

2.启用计费。

gcloud alpha billing projects link  nat-lan-api  --billing-account XXXXXX-XXXXXX-XXXXXX

3.为该项目启用 Google Natural Language API。

gcloud services enable  language.googleapis.com

3.创建一个服务帐户。

gcloud iam service-accounts create natural-language-api  --description "natural-language-api"  --display-name "natural-language-api"
gcloud iam service-accounts list

4.以 JSON 格式下载私钥。

gcloud iam service-accounts keys create key.json   --iam-account natural-language-api@nat-lan-api.iam.gserviceaccount.com 

5. 将环境变量 GOOGLE_APPLICATION_CREDENTIALS 设置为包含您的服务帐户密钥的 JSON 文件的路径。此变量仅适用于您当前的 shell 会话,因此如果您打开一个新会话,请再次设置该变量。

export GOOGLE_APPLICATION_CREDENTIALS="/Users/user/folder/key.json"

6.安装客户端库。

pip install --upgrade google-cloud-language

7.分析一些文本。

cat natural.py
# Imports the Google Cloud client library
from google.cloud import language
from google.cloud.language import enums
from google.cloud.language import types

# Instantiates a client
client = language.LanguageServiceClient()

# The text to analyze
text = u'Hello, world!'
document = types.Document(
    content=text,
    type=enums.Document.Type.PLAIN_TEXT)

# Detects the sentiment of the text
sentiment = client.analyze_sentiment(document=document).document_sentiment

print('Text: {}'.format(text))
print('Sentiment: {}, {}'.format(sentiment.score, sentiment.magnitude))

8.测试。

python natural.py 
#Text: Hello, world!
#Sentiment: 0.30000001192092896, 0.30000001192092896

推荐阅读