【发布时间】: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