Pickle can't store an object in django locmem cache during tests?

前端 未结 4 443
天命终不由人
天命终不由人 2021-01-25 02:27

Something that\'s puzzling me a bit...

>>> from django.core.cache import get_cache
>>>
>>> cache = get_cache(\'django.core.cache.backe         


        
4条回答
  •  情话喂你
    2021-01-25 03:07

    It happens because django LocMemCache uses cPickle instead of pickle by default. You can see it in LocMemCache class:

    try:
        from django.utils.six.moves import cPickle as pickle
    except ImportError:
        import pickle
    

    If you will try to do in shell:

    from django.utils.six.moves import cPickle as pickle
    testobj = TestObj()
    pickled = pickle.dumps(testobj, pickle.HIGHEST_PROTOCOL)
    

    It will be the same error.

    As possible solution I propose you to pack objects manually in your tests using pickle and after that do cache.set():

    a = TestObj()
    pickled = pickle.dumps(a, pickle.HIGHEST_PROTOCOL)
    cache.set('content', pickled)
    

提交回复
热议问题