【问题标题】:Passing arguments as json object将参数作为 json 对象传递
【发布时间】:2019-01-17 07:27:25
【问题描述】:

我正在尝试将我的 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}'

有人可以帮我解决这个问题吗?

【问题讨论】:

  • 您能否将您的代码与 Json 响应共享,另外,在发送 POST 请求之前,使用 JSON.stringify() 方法将 postData 值转换为 JSON 字符串。
  • 此外,当表单因 bmi 和年龄变量而无效时,您也会收到异常。
  • @JosefKorbel 你是对的.. 但我猜这里的参数没有以所需的 json 格式传递。

标签: json django azure api urllib


【解决方案1】:

尝试使用 JsonResponse:

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

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

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

【讨论】:

  • 感谢您的快速浏览。我使用了 JsonResponse 但我仍然得到状态代码 400,原因为 'code': 'RequestBodyInvalid', 'message': 'No request body provided or error in deserializing the request body.'
  • 在发送 POST 请求之前使用 JSON.stringify() 方法将 postData 值转换为 JSON 字符串。
  • 我是 API 新手...正如您建议的那样,我使用了 json_data = JsonResponse(args)...如果我错了请纠正我...
  • 尝试 JSON.stringify() 但由于 JSON 未定义而出现错误。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2017-03-04
    • 1970-01-01
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 2016-08-28
    • 2012-07-13
    • 2023-04-02
    • 2019-08-01
    相关资源
    最近更新 更多