Django cache.set() causing duplicate key error

后端 未结 3 1138
粉色の甜心
粉色の甜心 2020-12-19 16:02

My Django site recently started throwing errors from my caching code and I can\'t figure out why...

I call:

from django.core.cache import cache
cache         


        
3条回答
  •  醉酒成梦
    2020-12-19 16:32

    I solved this problem by creating a custom cache backend, overriding the _base_set() function and changing the INSERT INTO statement like this. This SQL trick prevents the INSERT from happening in the case the cache_key already exists.

    cursor.execute("INSERT INTO %s (cache_key, value, expires) SELECT %%s, %%s, %%s WHERE NOT EXISTS (SELECT 1 FROM %s WHERE cache_key = %%s)" % (table, table),
                   [key, encoded, connections[db].ops.value_to_db_datetime(exp), key])
    

提交回复
热议问题