使用CURL通过Python调用API

时间:2016-07-10 06:11:08

标签: python curl

我正在使用API​​进行车牌识别;我得到这个卷曲命令:

如何在PYTHON中用curl实现这样的调用?

curl "https://api.havenondemand.com/1/api/async/recognizelicenseplates/v1?url=https%3A%2F%2Fwww.havenondemand.com%2Fsample-content%2Fvideos%2Fgb-plates.mp4&source_location=GB&apikey=695e513c-xxxx-xxxx-xxxx-xxxxxxxxxx"

curl -X POST --form "url=https://www.havenondemand.com/sample-content/videos/gb-plates.mp4" --form "source_location=GB" --form "apikey=695e513c-xxxx-xxxx-a666-xxxxxxxxxx" https://api.havenondemand.com/1/api/async/recognizelicenseplates/v1

3 个答案:

答案 0 :(得分:0)

在Python中,使用requests模块是一个更好的选择。首先安装它:

pip install requests

然后这样做:

import requests

API_URL = "https://api.havenondemand.com/1/api/async/recognizelicenseplates/v1"

data = {
    "url": "https://www.havenondemand.com/sample-content/videos/gb-plates.mp4",
    "source_location": "GB",
    "apikey": "695e513c-xxxx-xxxx-a666-xxxxxxxxxx"
 }

response = requests.post(API_URL, data)
print(response.json())

基本上,任何表单字段都应作为键值对进入data字典。我们在这里使用requests.post()函数。该函数将目标URL作为第一个参数。并且表单值作为第二个参数。

我们得到一个响应对象。您可以通过打印response.content的值来查看原始响应。但是,如果您知道响应是JSON,则可以使用json()方法来解析响应并获取Python数据类型(字典)。

答案 1 :(得分:0)

有多种选择。您可以从urllib2(或任何其他HTTP库,如请求)开始。更好的选择可能是直接使用havenondemand

的python客户端库

答案 2 :(得分:0)

调用Haven OnDemand API的最快方法是使用HPE官方库。您可以安装HOD Python lib并按如下方式使用它:

安装lib

pip install havenondemand

# put these in your file
from havenondemand.hodclient import *
from havenondemand.hodresponseparser import *

client = HODClient("API_KEY", version="v1")
parser = HODResponseParser()

# callback function
def asyncRequestCompleted(response):
    jobID = parser.parse_jobid(response)
    if jobID is None:
        errorObj = hodParser.get_last_error()
        for err in errorObj.errors:
            print ("Error code: %d \nReason: %s \nDetails: %s\n" % (err.error,err.reason, err.detail))
    else:
        client.get_job_status(jobID, requestCompleted)

def requestCompleted(response):
    payloadObj = parser.parse_payload(response)
    resp = ""
    if payloadObj is None:
        errorObj = parser.get_last_error()
        for err in errorObj.errors:
            if err.error == ErrorCode.QUEUED:
                time.sleep(2)
                client.get_job_status(err.jobID, requestCompleted)
                return
            elif err.error == ErrorCode.IN_PROGRESS:
                time.sleep(10)
                client.get_job_status(err.jobID, requestCompleted)
                return
            else:
                resp += "Error code: %d \nReason: %s \nDetails: %s\n" % (err.error,err.reason)
    else:
        print(payloadObj)

params = {}
params['url'] = 'https://www.havenondemand.com/sample-content/videos/gb-plates.mp4'
params['source_location'] = 'GB'
hodApp = HODApps.RECOGNIZE_LICENSE_PLATE
client.post_request(params, hodApp, True, callback=asyncRequestCompleted)