Django.fun

Why does django cache.set() store weird characters

When I save the string via django's cache framework

from django.core.cache import cache

cache.set('host_cache_key_81e44325-c046-44c6-88d7-bad7cd91ec13', ""brown.example.com:8006")

And try to get the value out:

127.0.0.1:6379> get :1:host_cache_key_81e44325-c046-44c6-88d7-bad7cd91ec13
"\x80\x05\x95&\x00\x00\x00\x00\x00\x00\x00\x8c\"brown.example.com:8006\x94."

I get some weird characters around it, why is that and how to make it not do it?

Answers: 1

Answered by Iain Shelvington, Sept. 17, 2021, 7:17 a.m.

Django uses pickle to store the data that is stored in the cache, what you are seeing is the string serialised in the pickle format.

As an example here is the output I get when I pickle that example string

>>> import pickle
>>> pickle.dumps("brown.example.com:8006")
b'\x80\x04\x95\x1a\x00\x00\x00\x00\x00\x00\x00\x8c\x16brown.example.com:8006\x94.'