我在 Bluemix 中的何处指定 AlchemyAPI 密钥?

Where do I specify the AlchemyAPI key in Bluemix?

我已将 AlchemyAPI 服务添加到我在 Bluemix 上的 Python 应用程序。我可以在 AlchemyAPI 服务的服务凭证中看到 API 密钥。我应该在应用程序代码或文件中的什么地方指定此密钥,以便我可以调用该服务?代码运行良好并执行所有操作 除了 我调用 AlchemyAPI.

的部分

我遵循了 Getting started tutorial here,但它只是在 "Get the key" 处停止并且没有告诉我如何处理它。

一些我尝试过但没有用的东西:

services:
- the_alchemy-service_name
applications:
- path: .
  env:
     ALCHEMY_KEY: the_actual_key
VCAP_SERVICES = os.getenv('VCAP_SERVICES')
key = (VCAP_SERVICES['alchemy_api'][0]['credentials']['apikey'])
from alchemyapi import AlchemyAPI    
alchemyapi = AlchemyAPI()

您正在使用的 Python API 要求将 AlchemyAPI 密钥作为参数传递给脚本或存储在文件中。您可以在代码 https://github.com/AlchemyAPI/alchemyapi_python/blob/master/alchemyapi.py

中看到这一点

如果您想在 https://github.com/AlchemyAPI/alchemyapi_python 坚持使用 AlchemyAPI SDK,它希望 API 密钥存储在当前文件中名为 "api_key.txt" 的文件中工作目录。如果您想在 Bluemix 中使用此 SDK,并且假设您从环境中检索 API 键的值,如 German 所示,您应该在代码中创建 "api_key.txt" 文件:

# write the key to the file
f = open('api_key.txt', 'w')
f.write(alchemy_key)
f.close()

https://github.com/watson-developer-cloud/python-sdk 上有更新的 Python SDK,我强烈建议改用此 SDK。它支持 AlchemyAPI.

的更多功能

基于您要使用的炼金术API,您可以查看各种示例。这是一个使用炼金术语言的:https://github.com/watson-developer-cloud/python-sdk/blob/master/examples/alchemy_language_v1.py

如果您将 AlchemyAPI 服务绑定到您的应用程序,此 SDK 将自动从 VCAP_SERVICES 中找到 AlchemyAPI 密钥。

只要您不将代码推送到其他人可以看到您的密钥的 public 存储库,您就可以使用 manifest.yml。否则,我建议您使用 Bluemix UI 来编辑环境变量。

manifest.yml:

- applications:
  path: .
  env:
     ALCHEMY_KEY: the_actual_key

节点:

var alchemyKey = process.env.ALCHEMY_KEY || '<default-key>';

Python:

alchemy_key = os.getenv('ALCHEMY_KEY', '<default-key>')

Java:

String alchemyKey = System.getenv("VCAP_SERVICES");
alchemyKey = alchemyKey != null ? alchemyKey || "<default-key>"

您还可以将 Alchemy 服务绑定到您的 Bluemix 应用程序,并在您的环境中获取密钥以及其他环境变量。在这种情况下,密钥将成为 VCAP_SERVICES 对象的一部分。

"alchemy_api": [{
  "name": "alchemy_api_free_docs",
  "label": "alchemy_api",
  "plan": "free",
  "credentials": {
    "url": "https://gateway-a.watsonplatform.net/calls",
    "apikey": "THE-API-KEY"
  }
}]

在这种情况下,代码将类似,但如果您使用其中一种 SDK,如他的回答中提到的 @Frederic Lavigne,密钥将自动提取。

感谢@Frederic 和@German 共享的资源,我能够通过更多研究找到答案。我没有按原样使用建议的 SDK,因为 SDK 包含 一切,我正在尝试创建一个 简单 演示应用程序。

简答

不要调用 AlchemyAPI 模块。改为调用 Watson Developer Cloud 模块。

长答案

对于 Bluemix 上的 Python 应用程序,依赖项必须列在 requirements.txt 文件中。 Bluemix 将自动 pip 安装这些模块,您无需执行任何操作。

因为我使用的是 AlchemyAPI 服务(并遵循了他们的入门指南),所以我将 AlchemyAPI 列为 requirements.txt 中的依赖项。我假设 Bluemix 会 pip 安装它。在我的 Python 代码中,我通过 from alchemyapi import AlchemyAPI.

调用了该模块

假设错误。 alchemyapi 无法通过 Bluemix 安装 pip。要调用的模块是 watson-developer-cloud

调用后,您可以指定 api 键,这样:

from watson_developer_cloud import AlchemyLanguageV1
alchemy_language = AlchemyLanguageV1(api_key='THE_API_KEY')

所以,这里是问题的答案:你使用 api_key 变量来保存键的值,你调用 watson-developer-cloud 模块,NOT alchemyapi 模块。当您将 Alchemy 服务绑定到应用程序时,您可以通过编程方式从服务凭证中提取 API 密钥。