Python:将请求置于休息 api 发送 Bad request 400 错误

标签 python rest python-requests python-responses

我正在向 Rest Api 发送 Put 请求,以根据用户名更新用户信息,但出现以下错误

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server could not understand.</p>

API简介如下

/api/users/username GET, PUT    Token

我创建我的请求如下,

headers = {'Content-Type': 'application/json',
'Token': token}

datap = [{'firstname': 'aaa1',
'lastname': 'aaa1',
'phone': '222222'}]

r = requests.put('http://127.0.0.1:8080/api/users/user1a', data=datap, headers=headers)
print(r.text)

如果需要更多信息,我可以提供,这里是其余 api 的代码片段

@bp.route('/users/<username>', methods=(['GET', 'PUT']))
@token_required
def username(username):
    if request.method == 'GET':
        return get_specific_user(username)
    if request.method == 'PUT':
        return put_specific_user(username, request)

def put_specific_user(username, request):
    allowed_fields = ('firstname', 'lastname', 'phone')
    if not request.is_json:
        return jsonify({'status': 'FAILURE',
                        'message': 'Bad Request'}), 400

将 json 封装到 [] 后,现在我收到以下错误,因此它不再是错误的请求

File "C:\Python27\lib\site-packages\requests\api.py", line 131, in put
    return request('put', url, data=data, **kwargs)
  File "C:\Python27\lib\site-packages\requests\api.py", line 60, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Python27\lib\site-packages\requests\sessions.py", line 519, in request
    prep = self.prepare_request(req)
  File "C:\Python27\lib\site-packages\requests\sessions.py", line 462, in prepare_request
    hooks=merge_hooks(request.hooks, self.hooks),
  File "C:\Python27\lib\site-packages\requests\models.py", line 316, in prepare
    self.prepare_body(data, files, json)
  File "C:\Python27\lib\site-packages\requests\models.py", line 507, in prepare_body
    body = self._encode_params(data)
  File "C:\Python27\lib\site-packages\requests\models.py", line 97, in _encode_params
    for k, vs in to_key_val_list(data):
ValueError: too many values to unpack

最佳答案

更改如下

requests.put('http://127.0.0.1:8080/api/users/user1a', data=datap, headers=headers)

requests.put('http://127.0.0.1:8080/api/users/user1a', data=json.dumps(datap), headers=headers)

PS:我不知道为什么有人会给我-1 这个问题可以请一些mod 看看它。这样我就不会再这样做了。

关于Python:将请求置于休息 api 发送 Bad request 400 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59228676/

相关文章:

python - 如何将列表写入txt文件,其中每个项目在一行中不带 "\n"

powershell - Invoke-WebRequest,带参数的 POST

java - 使用 Jersey 添加 header 授权

json - 通过 Jenkins REST API 获取 IP 地址?

Python requests_toolbelt MultipartEncoder 文件名

Python刷新请求和json

python - 如何将字典转换为关键字参数字符串?

python - AWS Boto3 s3 put_object错误处理/测试

python - 在 Windows 上构建 pjsua python

python - Steam FileUploader 发布请求 : Missing SteamID