Search code examples
pythonpython-requestsetcd

Using requests to PUT <key,value> into etcd results in empty value


I'm trying to use requests to run a simple PUT and add a new pair to etcd (which I have running locally). I am able to do this just fine by directly calling etcd like so:

curl -X PUT http://127.0.0.1:2379/v2/keys/message -d value="Test Message"

However, the code below, which I thought would be equivalent to that, doesn't seem to work:

import requests
r = requests.put('http://127.0.0.1:2379/v2/keys/message', data = 'value=\"Test Message\"')
print(r.content)

The print statement above shows me this:

b'{"action":"create","node":{"key":"/message/35","value":"","modifiedIndex":35,"createdIndex":35}}\n'

So it appears that the value of value is empty for some reason. I've tried various formats for the data parameter but didn't have any luck.


Solution

  • First, you can get the sent request from r by r.request. And then you can see what's wrong with it:

    >>> r = requests.put("http://www.example.com", data="value=\"Test Message\"")
    >>> r.request
    <PreparedRequest [PUT]>
    >>> r.request.url
    'http://www.example.com/'
    >>> r.request.body
    'value="Test Message"'
    >>> r.request.headers
    {'User-Agent': 'python-requests/2.18.4', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'Content-Length': '20'}
    

    Second, I think you should use r = requests.put('http://127.0.0.1:2379/v2/keys/message', data={"value": "Test Message"})