I’m currently trying to handle cookies with Brython but I’m having some trouble. I’ve found the local_storage
module in the docs. When I set a cookie using this module, the server can’t find them (using request.COOKIES
in a Django views.py
function).
What’s weird, is that the value is stored because when I reload the page, the script prints it in the console.
The code in the HTML page:
<script type="text/python">
from browser.local_storage import storage
import random
if 'test' in storage:
print(storage['test'])
storage['test'] = str(random.randint(0, 100))
print(storage['test'])
</script>
Each time I reload the page, the value I get is the one that was stored but the cookie does not exist on the server side (request.COOKIES
does not contain a key 'test'
).
Maybe there’s something I’m missing?
Edit:
So, after looking at this page (link from Brython docs) https://html.spec.whatwg.org/multipage/webstorage.html, I discovered that local storage is not the same thing as cookies but they rather are similar sytems existing side by side.
So my question now is how can I use cookies with Brython instead of local storage?
So, it turns out it was pretty simple. The code is pretty much the same as in JavaScript.
Here is some sample code for creating a cookie named foo
with the value bar
:
from browser import document
document.cookie = 'foo=bar; Path=/'
And that’s it!