¿Cómo actualizar el diccionario almacenado en el caché de Django?

So I am storing youtube videos metadata uploaded by logged user in django's cache. The metadata looks something like this:

{'user': {'channels': [{'id': 1, 'etag': '2', 'videos': [{'id': '1', 'etag': '2'},]},]}

Each different user has its own metadata. Now I want to update this data stored in cache (updating some channels videos for instance). Can I do something like?

cache.set('user', channels[0]['videos']=[new list], 30)?

Gracias de antemano.

preguntado el 23 de abril de 13 a las 13:04

what if you just get the cache for 'user' via cache.get, then update channels and set it via cache.set? Or, consider storing channels per user under different cache key. -

1 Respuestas

Given that Django's cache framework supports a wide variety of backends, I doubt it's possible to manipulate the internals of a Python object directly in the cache, since it would require the backends to understand Python objects. The closest you could get would be...

value = cache.get('user')
value['channels'][0]['videos'] = <new list>
cache.set('user', value)

If you need finer granularity of updates, you'll have to use multiple keys per user, e.g....

username = 'user'
videos_key_name = '%s/videos' % username
channels_key_name = '%s/channels' % username
cache.set(videos_key_name) = whatever
cache.set(channels_key_name) = whatever

...although this will require changing the design of your structure.

Respondido 23 Abr '13, 14:04

Thanks for the answer. The problem with the first approach is that I may have fairly long dictionary for 100 of users, wouldn't it be an overhead updating such a big dictionary? The problem with the second approach is that it will thwart the design of app, for example I crawl the tree presented in my question to check which videos are changed and which not and update accordingly. I think it will be possible with this technique too but will take a bit more effort. I think I will give it a go. Thanks. - tejinderss

@tejinderss Regarding update overhead: depends how often you're likely to be doing it. If it's less than, say, 100 times per second, then you're probably optimizing prematurely. Try a few tests to see how many updates you can do per second before the cache becomes unresponsive. - Aya

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.