简体   繁体   中英

Facing issue while POST when it has no payload (python code)

The code called by my script is (this is code in api.py)

def post(url, data=None, **kwargs):
    """Sends a POST request. Returns :class:`Response` object.

    :param url: URL for the new :class:`Request` object.
    :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    """
    return request('post', url, data=data, **kwargs)

Now I need to POST a request which has no payload, as the info which I need to post is in url itself. I have tried following combinations but failed:

1) requests.post(url, auth, data=None)

Fails saying:

result = requests.post(api, auth, data=None)
TypeError: post() got multiple values for keyword argument 'data'   

2) requests.post(api, auth, data=payload) where payload is empty json.

Please suggest..

The issue is the incompatibility between the method signature and how you call it.

def post(url, data=None, **kwargs):
result = requests.post(api, auth, data=None)

First of all, based on the error, its save to assume requests is a library you've written (and not the Python requests module), and not a class because you'd get a completely different error otherwise.

Your post method has 2 arguments, url and data .

Your call has three arguments, which python has to unpack: the variables api and auth and a named argument of data=None .

Python assigns api to the url variable in the methods scope, and auth to the data variable. This leaves an extra named data variable in the methods scope, which now is attempting to be assigned again.

Hence the error:

post() got multiple values for keyword argument 'data'   

Passed auth param is accepted by function as data one. Then you passed data again, as keyword argument.

result = requests.post(api, auth, data=None)
TypeError: post() got multiple values for keyword argument 'data'   

Try this:

result = requests.post(api, auth=auth)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM