Connect to Microsoft Azure Machine Learning Studio Api with ruby instead of python use net/http gem instead of urllib2

断了今生、忘了曾经 提交于 2019-12-12 02:39:05

问题


I need to connect to the Microsoft Azure Machine Learning Studio Api with ruby instead of python. Can someone help me translate this python code into ruby using the net/http gem.

import urllib2
# If you are using Python 3+, import urllib instead of urllib2

import json 

data =  {
        "Id": "score00001",
        "Instance": {
            "FeatureVector": {
                "value_1"= "1",
                "value_2"= "2",
                "value_3"= "3",
                "value_4"= "4",
                "value_5"= "5",
                "value_6"= "6",
                "value_7"= "7",
                "value_8"= "8",
                "value_9"= "9",
                "value_10"= "10",
            },
            "GlobalParameters": 
                    {
                                            }
        }
    }

body = str.encode(json.dumps(data))

url = 'https://appurl/score'
api_key = 'some_api_key_abc123' # Replace this with the API key for the web service
headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}

req = urllib2.Request(url, body, headers) 
response = urllib2.urlopen(req)

# If you are using Python 3+, replace urllib2 with urllib.request in the above code:
# req = urllib.request.Request(url, body, headers) 
# response = urllib.request.urlopen(req)

result = response.read()
print(result)

How do I sent a request with net/http with three fields (url, body, headers) in ruby?


回答1:


Perhaps Unirest is a better tool for the task, its very intuitive.

require 'unirest'

data =  {
        "Id" => "score00001",
        "Instance" => {
            "FeatureVector" => {
                "value_1" => "1",
                "value_2" => "2",
                "value_3" => "3",
                "value_4" => "4",
                "value_5" => "5",
                "value_6" => "6",
                "value_7" => "7",
                "value_8" => "8",
                "value_9" => "9",
                "value_10"=> "10",
            },
            "GlobalParameters" => {}
        }
    }

url = 'https://appurl/score'
api_key = 'some_key'
headers = { 'Content-Type' => 'application/json', 'Authorization' => 'Bearer ' + api_key }


response = Unirest.post url, headers: headers, parameters: data

response.code
response.headers
response.body
response.raw_body


来源:https://stackoverflow.com/questions/27576426/connect-to-microsoft-azure-machine-learning-studio-api-with-ruby-instead-of-pyth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!