how can i send python a base64 str file using webdis?

You can send values to Webdis that do not fit nicely in a URL by sending them as the request body using a PUT request. This is documented in the Webdis README under the section titled “File Upload“.

Let’s say you wanted to store the value hello/world under the key greeting. As you wrote, you can’t just send /SET/greeting/hello/world, but you can send all the parameters except the last one in the URL, and then the last one as the PUT body. This means the PUT body is the exact value to set, it is not a JSON message containing the value.

To do this in Python with Requests:

>>> import requests
>>> r = requests.put('http://127.0.0.1:7379/SET/greeting', data=b'hello/world', headers={'Content-Type': 'application/octet-stream'})
>>> r.status_code
200
>>> r.text
'{"SET":[true,"OK"]}'

And we can verify that the value was sent correctly:

>>> r = requests.get('http://127.0.0.1:7379/GET/greeting')
>>> r.status_code
200
>>> r.text
'{"GET":"hello/world"}'

This should work just the same way for your PUBLISH example. I ran your JavaScript code in a browser and then used Requests to send the same value to http://127.0.0.1:7379/PUBLISH/mychannel, and the following was logged in the browser console:

{"SUBSCRIBE":["message","mychannel","hello/world"]}

You almost have it right with the PUT request code in your last block, except that in this case you don’t have to send JSON but can send the raw value directly in the data parameter – even the contents a binary file, which is why this is documented as “file upload”. In some cases you might still want to use base 64 encoding, especially if the subscriber can’t handle the raw data.

As a side note, there is yet another way to do this with Webdis: you can also fully URL-encode the value and not send hello/world but hello%2Fworld, for example with encodeURIComponent in JavaScript or urllib.parse.quote(value, safe='') in Python. Sending /SET/greeting/hello%2Fworld in a GET request will work. This is documented under “Command format” in the README.

This isn’t the first time this question has been asked, there was a recent question on GitHub that was similar. I’ve been working on adding more documentation to Webdis and will try to highlight this case since it seems common.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top