将参数作为json对象传递

时间:2019-01-17 07:27:25

标签: json django azure api urllib

我正在尝试将Django Web应用程序链接到Azure ML API。我确实拥有Django表单,其中包含我的Azure API的所有必需输入。

def post(self,request):
    form = CommentForm(request.POST)
    url = 'https://ussouthcentral.services.azureml.net/workspaces/7061a4b24ea64942a19f74ed36e4b438/services/ae2c257d6e164dca8d433ad1a1f9feb4/execute?api-version=2.0&format=swagger'

    api_key = # Replace this with the API key for the web service

    headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}

    if form.is_valid():
        age = form.cleaned_data['age']
        bmi = form.cleaned_data['bmi']
    args = {"age":age,"bmi":bmi}
    json_data = str.encode(json.dumps(args))
    print(type(json_data))

    r= urllib.request.Request(url,json_data,headers)
    try:
        response = urllib.request.urlopen(r)
        result = response.read()
        print(result) 
    except urllib.request.HTTPError as error:
        print("The request failed with status code: " + str(error.code))
        print(json_data)
        # Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
        print(error.info())

        print(json.loads(error.read()))      
    return render(request,self.template_name)

当我尝试提交表单时,出现输入错误-

TypeError('POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.',)

获取状态码-400及以下错误

{'error': {'code': 'BadArgument', 'message': 'Invalid argument provided.', 'details': [{'code': 'RequestBodyInvalid', 'message': 'No request body provided or error in deserializing the request body.'}]}}

参数正在使用print(json_data)-

b'{"age": 0, "bmi": 22.0}'

有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

尝试使用JsonResponse:

https://docs.djangoproject.com/en/2.1/ref/request-response/#jsonresponse-objects

此外,我认为您不需要API响应模板。

return JsonResponse({'foo': 'bar'})

答案 1 :(得分:0)

谢谢。我发现错误是数据顺序不正确。