【问题标题】:how to solve this "Expecting value: line 1 column 1 (char 0)"?如何解决这个“期望值:第 1 行第 1 列(字符 0)”?
【发布时间】:2021-05-19 10:05:18
【问题描述】:

请求方法:PATCH

有一个查询字符串参数部分

【问题讨论】:

标签: python api python-requests patch


【解决方案1】:

无法运行您的代码来重现您的错误。在此处查看response 所获得的内容:

r = requests.patch(url, headers=self._construct_header(),data=body)
response = getattr(r,'_content').decode("utf-8")
response_json = json.loads(response)

如果您将无效的 json 传递给 json.loads(),则会出现错误并显示类似消息。

import json

response = b'test data'.decode("utf-8")
print(response)
response_json = json.loads(response)
print(response_json)

输出:

test data
Traceback (most recent call last):
...
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

编辑:

在您的情况下,为避免错误,您需要添加一个 if-else 块。收到回复后,您需要检查您收到的具体内容。

r = requests.patch(url, headers=self._construct_header(),data=body)

# if necessary, check content type
print(r.headers['Content-Type'])

response = getattr(r,'_content').decode("utf-8")

if r.status_code == requests.codes.ok:
    # make sure you get the string "success"
    # if necessary, do something with the string

    return response

else:
    # if necessary, check what error you have: client or server errors, etc.
    # or throw an exception to indicate that something went wrong
    # if necessary, make sure you get the error in json format
    # you may also get an error if the json is not valid

    # since your api returns json formatted error message:
    response_dict = json.loads(response)
    
    return response_dict

在这些情况下,您的函数会返回字符串“success”或带有错误描述的 dict。

用法:


data = { 
    'correct_prediction': 'funny',
    'is_accurate': 'False',
    'newLabel': 'funny',
} 
response = aiservice.update_prediction(data)

if isinstance(response, str):
    print('New Prediction Status: ', response)
else:
    # provide error information
    # you can extract error description from dict

【讨论】:

  • 是的,我已经发布了测试框架的一部分。所以它无法重现错误。您在我的代码中看到任何不正确的行吗?
  • @ShelomiPriskila 您对请求有什么期望?如果只有“成功”这一行,只需解码并打印。无需使用 json.loads()。如果响应应该包含某种 json,那就是另一个问题了。
  • @ShelomiPriskila 您可以从 API 中获得至少两种类型的响应。 1) 成功响应status code 200。 2) json 格式的错误消息(例如状态 403)。想想怎么handle different responses
  • 有查询字符串参数为 predictionId 。如何将其添加到正文中?
猜你喜欢
  • 1970-01-01
  • 2013-05-10
  • 2019-02-25
  • 2023-03-25
  • 2018-06-28
  • 2020-11-11
  • 2022-11-15
  • 1970-01-01
相关资源
最近更新 更多