0

我正在向PutRest Api 发送一个请求以根据用户名更新用户信息,它给出了以下错误

<!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
4

1 回答 1

2

更改以下

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调查一下。这样我就不会再这样做了。

于 2019-12-07T19:44:16.473 回答