使用 API 管理以管理 Azure 机器学习工作室(经典)Web 服务Manage Azure Machine Learning Studio (classic) web services using API Management

适用对象: 适用于.机器学习工作室(经典) 不适用于.Azure 机器学习APPLIES TO: Applies to.Machine Learning Studio (classic) Does not apply to.Azure Machine Learning

概述Overview

本指南介绍如何快速入门,即使用 API 管理来管理 Azure 机器学习工作室(经典)Web 服务。This guide shows you how to quickly get started using API Management to manage your Azure Machine Learning Studio (classic) web services.

什么是 Azure API 管理?What is Azure API Management?

Azure API 管理是一项 Azure 服务,支持通过定义用户访问权限、使用限制和仪表板监视管理 REST API 终结点。Azure API Management is an Azure service that lets you manage your REST API endpoints by defining user access, usage throttling, and dashboard monitoring. 有关更多详细信息,请参阅 Azure API 管理站点See the Azure API management site for more details. 若要开始使用 Azure API 管理,请参阅导入和发布指南To get started with Azure API Management, see the import and publish guide. 这份额外指南(作为本指南的依据)涵盖更多主题,包括通知配置、层定价、响应处理、用户身份验证、创建产品、开发人员订阅和使用仪表板。This other guide, which this guide is based on, covers more topics, including notification configurations, tier pricing, response handling, user authentication, creating products, developer subscriptions, and usage dashboarding.

先决条件Prerequisites

若要完成本指南,需要:To complete this guide, you need:

  • 一个 Azure 帐户。An Azure account.
  • AzureML 帐户。An AzureML account.
  • AzureML 实验的工作区、服务和 api_key 均部署为 Web 服务。The workspace, service, and api_key for an AzureML experiment deployed as a web service. 有关如何创建 AzureML 实验的详细信息,请参阅工作室快速入门For details on how to create an AzureML experiment, see the Studio quickstart. 若要了解如何将工作室(经典)试验部署为 Web 服务,请参阅工作室部署操作说明,以了解有关如何将 AzureML 试验部署为 Web 服务的详细信息。For information on how to deploy a Studio (classic) experiment as a web service, see the Studio deployment how-to for details on how to deploy an AzureML experiment as a web service. 另外,附录 A 说明了如何创建并测试简单 AzureML 实验并将其部署为 Web 服务。Alternately, Appendix A has instructions for how to create and test a simple AzureML experiment and deploy it as a web service.

创建 API 管理实例Create an API Management instance

可以使用 API 管理实例来管理 Azure 机器学习 Web 服务。You can manage your Azure Machine Learning web service with an API Management instance.

  1. 登录 Azure 门户Sign in to the Azure portal.
  2. 选择“+ 创建资源”。Select + Create a resource.
  3. 在搜索框中键入“API 管理”,然后选择“API 管理”资源。In the search box, type "API management", then select the "API management" resource.
  4. 单击“创建”。Click Create.
  5. “名称”值用于创建唯一 URL(本示例使用“demoazureml”)。The Name value will be used to create a unique URL (this example uses "demoazureml").
  6. 为服务实例选择 订阅资源组位置Select a Subscription, Resource group, and Location for your service instance.
  7. 指定“组织名称”的值(本示例使用“demoazureml”)。Specify a value for Organization name (this example uses "demoazureml").
  8. 输入“管理员电子邮件”- 此电子邮件用于接收 API 管理系统发出的通知。Enter your Administrator email - this email will be used for notifications from the API Management system.
  9. 单击“创建”。Click Create.

创建新服务最多可能需要 30 分钟。It may take up to 30 minutes for a new service to be created.

create-service

创建 APICreate the API

创建服务实例后,下一步是创建 API。Once the service instance is created, the next step is to create the API. API 包含一组可以从客户端应用程序调用的操作。An API consists of a set of operations that can be invoked from a client application. API 操作代理到现有的 web 服务。API operations are proxied to existing web services. 本指南创建成为现有 AzureML RRS 和 BES Web 服务代理的 API。This guide creates APIs that proxy to the existing AzureML RRS and BES web services.

创建 API:To create the API:

  1. 在 Azure 门户中,打开创建的服务实例。In the Azure portal, open the service instance you created.

  2. 在左侧导航窗格中,选择“API”。In the left navigation pane, select APIs.

    api-management-menu

  3. 单击“添加 API”。Click Add API.

  4. 输入“Web API 名称”(本示例使用“AzureML 演示 API”)。Enter a Web API name (this example uses "AzureML Demo API").

  5. 对于“Web 服务 URL”,请输入“https://ussouthcentral.services.azureml.net”。For Web service URL, enter "https://ussouthcentral.services.azureml.net".

  6. 输入“Web API URL 后缀”。Enter a Web API URL suffix". 这是客户向服务实例发送请求时使用的 URL 的最后一个部分(本示例使用“azureml-demo”)。This will become the last part of the URL that customers will use for sending requests to the service instance (this example uses "azureml-demo").

  7. 对于“Web API URL 方案”,请选择“HTTPS”。 For Web API URL scheme, select HTTPS.

  8. 对于“产品”,请选择“初学者”。 For Products, select Starter.

  9. 单击“ 保存”。Click Save.

添加操作Add the operations

在发布者门户中将操作添加并配置到 API。Operations are added and configured to an API in the publisher portal. 若要访问发布者门户,请在 API 管理服务的 Azure 门户中单击“发布者门户”,依次选择“API”、“操作”,然后单击“添加操作”。 To access the publisher portal, click Publisher portal in the Azure portal for your API Management service, select APIs, Operations, then click Add operation.

add-operation

将显示“新建操作”窗口,并且在默认情况下将选择“签名”选项卡。The New operation window will be displayed and the Signature tab will be selected by default.

添加 RRS 操作Add RRS Operation

首先为 AzureML RRS 服务创建一个操作:First create an operation for the AzureML RRS service:

  1. 对于“HTTP 谓词”,请选择“POST”。 For the HTTP verb, select POST.

  2. 对于“URL 模板”,请键入“/workspaces/{workspace}/services/{service}/execute?api-version={apiversion}&details={details}”。For the URL template, type "/workspaces/{workspace}/services/{service}/execute?api-version={apiversion}&details={details}".

  3. 输入“显示名称”(本示例使用“RRS 执行”)。Enter a Display name (this example uses "RRS Execute").

    add-rrs-operation-signature

  4. 在左侧依次单击“响应” > “添加”,并选择“200 正常”。Click Responses > ADD on the left and select 200 OK.

  5. 单词“保存”,保存此操作。Click Save to save this operation.

    add-rrs-operation-response

添加 BES 操作Add BES Operations

备注

BES 操作不包括屏幕截图,因为这些屏幕截图与添加 RRS 操作的屏幕截图类似。Screenshots are not included here for the BES operations as they are very similar to those for adding the RRS operation.

提交(但不启动)批处理执行作业Submit (but not start) a Batch Execution job

  1. 单击“添加操作”,将一个 BES 操作添加到 API。Click add operation to add a BES operation to the API.
  2. 对于“HTTP 谓词”,请选择“POST”。 For the HTTP verb, select POST.
  3. 对于“URL 模板”,请键入“/workspaces/{workspace}/services/{service}/jobs?api-version={apiversion}”。For the URL template, type "/workspaces/{workspace}/services/{service}/jobs?api-version={apiversion}".
  4. 输入“显示名称”(本示例使用“BES 提交”)。Enter a Display name (this example uses "BES Submit").
  5. 在左侧依次单击“响应” > “添加”,并选择“200 正常”。Click Responses > ADD on the left and select 200 OK.
  6. 单击“ 保存”。Click Save.

启动批处理执行作业Start a Batch Execution job

  1. 单击“添加操作”,将一个 BES 操作添加到 API。Click add operation to add a BES operation to the API.
  2. 对于“HTTP 谓词”,请选择“POST”。 For the HTTP verb, select POST.
  3. 对于“HTTP 谓词”,请键入“/workspaces/{workspace}/services/{service}/jobs/{jobid}/start?api-version={apiversion}”。For the HTTP verb, type "/workspaces/{workspace}/services/{service}/jobs/{jobid}/start?api-version={apiversion}".
  4. 输入“显示名称”(本示例使用“BES 启动”)。Enter a Display name (this example uses "BES Start").
  5. 在左侧依次单击“响应” > “添加”,并选择“200 正常”。Click Responses > ADD on the left and select 200 OK.
  6. 单击“ 保存”。Click Save.

获取批处理执行作业的状态或结果Get the status or result of a Batch Execution job

  1. 单击“添加操作”,将一个 BES 操作添加到 API。Click add operation to add a BES operation to the API.
  2. 对于“HTTP 谓词”,请选择“GET”。 For the HTTP verb, select GET.
  3. 对于“URL 模板”,请键入“/workspaces/{workspace}/services/{service}/jobs/{jobid}?api-version={apiversion}”。For the URL template, type "/workspaces/{workspace}/services/{service}/jobs/{jobid}?api-version={apiversion}".
  4. 输入“显示名称”(本示例使用“BES 状态”)。Enter a Display name (this example uses "BES Status").
  5. 在左侧依次单击“响应” > “添加”,并选择“200 正常”。Click Responses > ADD on the left and select 200 OK.
  6. 单击“ 保存”。Click Save.

删除批处理执行作业Delete a Batch Execution job

  1. 单击“添加操作”,将一个 BES 操作添加到 API。Click add operation to add a BES operation to the API.
  2. 对于“HTTP 谓词”,请选择“DELETE”。 For the HTTP verb, select DELETE.
  3. 对于“URL 模板”,请键入“/workspaces/{workspace}/services/{service}/jobs/{jobid}?api-version={apiversion}”。For the URL template, type "/workspaces/{workspace}/services/{service}/jobs/{jobid}?api-version={apiversion}".
  4. 输入“显示名称”(本示例使用“BES 删除”)。Enter a Display name (this example uses "BES Delete").
  5. 在左侧依次单击“响应” > “添加”,并选择“200 正常”。Click Responses > ADD on the left and select 200 OK.
  6. 单击“ 保存”。Click Save.

从开发人员门户调用操作Call an operation from the Developer portal

可以直接从开发人员门户调用操作,这样可以方便地查看和测试 API 的操作。Operations can be called directly from the Developer portal, which provides a convenient way to view and test the operations of an API. 此步骤将调用已添加到“AzureML 演示 API”的“RRS 执行”方法。 In this step, you will call the RRS Execute method that was added to the AzureML Demo API.

  1. 单击“开发人员门户”。Click Developer portal.

    developer-portal

  2. 单击顶部菜单的“API”,并单击“AzureML 演示 API”,查看可用操作。Click APIs from the top menu, and then click AzureML Demo API to see the operations available.

    demoazureml-api

  3. 为操作选择“RRS 执行”。Select RRS Execute for the operation. 单击“试用”。Click Try It.

    try-it

  4. 对于“请求参数”,请键入自己的 工作区服务,为 apiversion 键入“2.0”,为 details 键入“true”。For Request parameters, type your workspace and service, type "2.0 for the apiversion, and "true" for the details. 可在 AzureML Web 服务仪表板中查找“工作区”和“服务”(请参阅附录 A 中的 测试 Web 服务)。You can find your workspace and service in the AzureML web service dashboard (see Test the web service in Appendix A).

    对于“请求标头”,请单击“添加标头”,并键入“Content-Type”和“application/json”。 For Request headers, click Add header and type "Content-Type" and "application/json". 再次单击“添加标头”,键入“Authorization”和“Bearer <your service API-KEY>”。Click Add header again and type "Authorization" and "Bearer <your service API-KEY>". 可在 AzureML Web 服务仪表板中找到 API-KEY(请参阅附录 A 中的 测试 Web 服务)。You can find your API-KEY in the AzureML web service dashboard (see Test the web service in Appendix A).

    对于“请求正文”,请键入 {"Inputs": {"input1": {"ColumnNames": ["Col2"], "Values": [["This is a good day"]]}}, "GlobalParameters": {}}For Request body, type {"Inputs": {"input1": {"ColumnNames": ["Col2"], "Values": [["This is a good day"]]}}, "GlobalParameters": {}}.

    azureml-demo-api

  5. 单击“Send”。Click Send.

    发送

调用操作后,开发人员门户将从后端服务显示“请求的 URL”、“响应状态”、“响应标头”以及任何“响应内容”。After an operation is invoked, the developer portal displays the Requested URL from the back-end service, the Response status, the Response headers, and any Response content.

response-status

附录 A:创建并测试简单 AzureML Web 服务Appendix A - Creating and testing a simple AzureML web service

创建实验Creating the experiment

下面是创建简单 AzureML 实验并将其部署为 Web 服务的步骤。Below are the steps for creating a simple AzureML experiment and deploying it as a web service. 采用任意文本列作为输入,并返回以整数形式表示的功能集。The web service takes as input a column of arbitrary text and returns a set of features represented as integers. 例如:For example:

文本Text 经过哈希处理的文本Hashed Text
今天天气不错This is a good day 1 1 2 2 0 2 0 11 1 2 2 0 2 0 1

首先,使用所选浏览器导航到 https://studio.ml.azure.cn/,并输入凭据以登录。First, using a browser of your choice, navigate to: https://studio.ml.azure.cn/ and enter your credentials to log in. 接下来,创建新的空白实验。Next, create a new blank experiment.

搜索实验模板

将其重命名为“SimpleFeatureHashingExperiment”。Rename it to SimpleFeatureHashingExperiment. 展开“保存的数据集”,并将“Amazon 中的书评”拖动至实验。Expand Saved Datasets and drag Book Reviews from Amazon onto your experiment.

simple-feature-hashing-experiment

展开“数据转换”和“操作”,并将“选择数据集中的列”拖动至实验。Expand Data Transformation and Manipulation and drag Select Columns in Dataset onto your experiment. 将“Amazon 中的书评”连接到“选择数据集中的列”。Connect Book Reviews from Amazon to Select Columns in Dataset.

将书评数据集模块连接到项目列模块

单击“选择数据集中的列”,并单击“启动列选择器”并选择“Col2”。Click Select Columns in Dataset and then click Launch column selector and select Col2. 单击复选标记应用这些更改。Click the checkmark to apply these changes.

使用列名称选择列

展开“文本分析”,并将“功能哈希”拖动至实验。Expand Text Analytics and drag Feature Hashing onto the experiment. 将“选择数据集中的列”连接到“功能哈希”。Connect Select Columns in Dataset to Feature Hashing.

connect-project-columns

键入“3”作为“哈希位大小”。Type 3 for the Hashing bitsize. 这会创建 8 (23) 个列。This will create 8 (23) columns.

hashing-bitsize

此时你可能想要单击“运行”测试试验。At this point, you may want to click Run to test the experiment.

run

创建 Web 服务Create a web service

现在创建 Web 服务。Now create a web service. 展开“Web 服务”,并将“输入”拖动至实验。Expand Web Service and drag Input onto your experiment. 将“输入”连接到“功能哈希”。Connect Input to Feature Hashing. 另将“输出”拖动至实验。Also drag output onto your experiment. 将“输出”连接到“功能哈希”。Connect Output to Feature Hashing.

output-to-feature-hashing

单击“发布 Web 服务”。Click Publish web service.

publish-web-service

单击“是”发布实验。Click Yes to publish the experiment.

yes-to-publish

测试 Web 服务Test the web service

AzureML Web 服务包含 RSS(请求/响应服务)和 BES(批处理执行服务)终结点。An AzureML web service consists of RSS (request/response service) and BES (batch execution service) endpoints. RSS 适用于同步执行。RSS is for synchronous execution. BES 适用于异步作业执行。BES is for asynchronous job execution. 若要通过下面的示例 Python 源测试 Web 服务,可能需要下载并安装 Azure SDK for Python(请参阅:如何安装 Python)。To test your web service with the sample Python source below, you may need to download and install the Azure SDK for Python (see: How to install Python).

还需要下面源示例实验的“工作区”、“服务”和“api_key”。You will also need the workspace, service, and api_key of your experiment for the sample source below. 在 Web 服务仪表板中单击实验的“请求/响应”或“批处理执行”,查找工作区和服务。You can find the workspace and service by clicking either Request/Response or Batch Execution for your experiment in the web service dashboard.

find-workspace-and-service

在 Web 服务仪表板中单击实验,查找“api_key”。You can find the api_key by clicking your experiment in the web service dashboard.

find-api-key

测试 RRS 终结点Test RRS endpoint

“测试”按钮Test button

测试 RRS 终结点的简单方法是在 Web 服务仪表板上单击“测试”。An easy way to test the RRS endpoint is to click Test on the web service dashboard.

测试

为“col2”键入“今天天气不错”。Type This is a good day for col2. 单击复选标记。Click the checkmark.

enter-data

会看到类似于下面的内容You will see something like

sample-output

代码示例Sample Code

测试 RRS 的另一种方法是从客户端代码入手。Another way to test your RRS is from your client code. 如果在仪表板上单击“请求/响应”,并滚动到底部,会看到 C#、Python 和 R 的示例代码。还将看到 RRS 请求的语法,包括请求 URI、标头和正文。If you click Request/response on the dashboard and scroll to the bottom, you will see sample code for C#, Python, and R. You will also see the syntax of the RRS request, including the request URI, headers, and body.

本指南介绍了运行中的 Python 示例。This guide shows a working Python example. 将使用实验的“工作区”、“服务”和“api_key”修改该示例。You will need to modify it with the workspace, service, and api_key of your experiment.

import urllib2
import json
workspace = "<REPLACE WITH YOUR EXPERIMENT'S WEB SERVICE WORKSPACE ID>"
service = "<REPLACE WITH YOUR EXPERIMENT'S WEB SERVICE SERVICE ID>"
api_key = "<REPLACE WITH YOUR EXPERIMENT'S WEB SERVICE API KEY>"
data = {
"Inputs": {
    "input1": {
        "ColumnNames": ["Col2"],
        "Values": [ [ "This is a good day" ] ]
    },
},
"GlobalParameters": { }
}
url = "https://ussouthcentral.services.azureml.net/workspaces/" + workspace + "/services/" + service + "/execute?api-version=2.0&details=true"
headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}
body = str.encode(json.dumps(data))
try:
    req = urllib2.Request(url, body, headers)
    response = urllib2.urlopen(req)
    result = response.read()
    print "result:" + result
        except urllib2.HTTPError, error:
    print("The request failed with status code: " + str(error.code))
    print(error.info())
    print(json.loads(error.read()))

测试 BES 终结点Test BES endpoint

在仪表板上单击“批处理执行”并滚动到底部。Click Batch execution on the dashboard and scroll to the bottom. 会看到 C#、Python 和 R 的示例代码。还将看到提交作业、启动作业、获取作业状态或结果以及删除作业的 BES 请求语法。You will see sample code for C#, Python, and R. You will also see the syntax of the BES requests to submit a job, start a job, get the status or results of a job, and delete a job.

本指南介绍了运行中的 Python 示例。This guide shows a working Python example. 需要使用实验的“工作区”、“服务”和“api_key”修改该示例。You need to modify it with the workspace, service, and api_key of your experiment. 此外,还需要修改“存储帐户名称”、“存储帐户密钥”和“存储容器名称”。Additionally, you need to modify the storage account name, storage account key, and storage container name. 最后,需要修改“输入文件”和“输出文件”的位置。Lastly, you will need to modify the location of the input file and the location of the output file.

import urllib2
import json
import time
from azure.storage import *
workspace = "<REPLACE WITH YOUR WORKSPACE ID>"
service = "<REPLACE WITH YOUR SERVICE ID>"
api_key = "<REPLACE WITH THE API KEY FOR YOUR WEB SERVICE>"
storage_account_name = "<REPLACE WITH YOUR AZURE STORAGE ACCOUNT NAME>"
storage_account_key = "<REPLACE WITH YOUR AZURE STORAGE KEY>"
storage_container_name = "<REPLACE WITH YOUR AZURE STORAGE CONTAINER NAME>"
input_file = "<REPLACE WITH THE LOCATION OF YOUR INPUT FILE>" # Example: C:\\mydata.csv
output_file = "<REPLACE WITH THE LOCATION OF YOUR OUTPUT FILE>" # Example: C:\\myresults.csv
input_blob_name = "mydatablob.csv"
output_blob_name = "myresultsblob.csv"
def printHttpError(httpError):
print("The request failed with status code: " + str(httpError.code))
print(httpError.info())
print(json.loads(httpError.read()))
return
def saveBlobToFile(blobUrl, resultsLabel):
print("Reading the result from " + blobUrl)
try:
    response = urllib2.urlopen(blobUrl)
except urllib2.HTTPError, error:
    printHttpError(error)
    return
with open(output_file, "wb+") as f:
    f.write(response.read())
print(resultsLabel + " have been written to the file " + output_file)
return
def processResults(result):
first = True
results = result["Results"]
for outputName in results:
    result_blob_location = results[outputName]
    sas_token = result_blob_location["SasBlobToken"]
    base_url = result_blob_location["BaseLocation"]
    relative_url = result_blob_location["RelativeLocation"]
    print("The results for " + outputName + " are available at the following Azure Storage location:")
    print("BaseLocation: " + base_url)
    print("RelativeLocation: " + relative_url)
    print("SasBlobToken: " + sas_token)
    if (first):
        first = False
        url3 = base_url + relative_url + sas_token
        saveBlobToFile(url3, "The results for " + outputName)
return

def invokeBatchExecutionService():
url = "https://ussouthcentral.services.azureml.net/workspaces/" + workspace +"/services/" + service +"/jobs"
blob_service = BlobService(account_name=storage_account_name, account_key=storage_account_key)
print("Uploading the input to blob storage...")
data_to_upload = open(input_file, "r").read()
blob_service.put_blob(storage_container_name, input_blob_name, data_to_upload, x_ms_blob_type="BlockBlob")
print "Uploaded the input to blob storage"
input_blob_path = "/" + storage_container_name + "/" + input_blob_name
connection_string = "DefaultEndpointsProtocol=https;AccountName=" + storage_account_name + ";AccountKey=" + storage_account_key
payload =  {
    "Input": {
        "ConnectionString": connection_string,
        "RelativeLocation": input_blob_path
    },
    "Outputs": {
        "output1": { "ConnectionString": connection_string, "RelativeLocation": "/" + storage_container_name + "/" + output_blob_name },
    },
    "GlobalParameters": {
    }
}
    body = str.encode(json.dumps(payload))
headers = { "Content-Type":"application/json", "Authorization":("Bearer " + api_key)}
print("Submitting the job...")
# submit the job
req = urllib2.Request(url + "?api-version=2.0", body, headers)
try:
    response = urllib2.urlopen(req)
except urllib2.HTTPError, error:
    printHttpError(error)
    return
result = response.read()
job_id = result[1:-1] # remove the enclosing double-quotes
print("Job ID: " + job_id)
# start the job
print("Starting the job...")
req = urllib2.Request(url + "/" + job_id + "/start?api-version=2.0", "", headers)
try:
    response = urllib2.urlopen(req)
except urllib2.HTTPError, error:
    printHttpError(error)
    return
url2 = url + "/" + job_id + "?api-version=2.0"

while True:
    print("Checking the job status...")
    # If you are using Python 3+, replace urllib2 with urllib.request in the following code
    req = urllib2.Request(url2, headers = { "Authorization":("Bearer " + api_key) })
    try:
        response = urllib2.urlopen(req)
    except urllib2.HTTPError, error:
        printHttpError(error)
        return
    result = json.loads(response.read())
    status = result["StatusCode"]
    print "status:" + status
    if (status == 0 or status == "NotStarted"):
        print("Job " + job_id + " not yet started...")
    elif (status == 1 or status == "Running"):
        print("Job " + job_id + " running...")
    elif (status == 2 or status == "Failed"):
        print("Job " + job_id + " failed!")
        print("Error details: " + result["Details"])
        break
    elif (status == 3 or status == "Cancelled"):
        print("Job " + job_id + " cancelled!")
        break
    elif (status == 4 or status == "Finished"):
        print("Job " + job_id + " finished!")
        processResults(result)
        break
    time.sleep(1) # wait one second
return
invokeBatchExecutionService()