django cache key naming

956 views Asked by At

I want to store some items using Django cache API. Are there are best practices to follow while naming the key. I know some people just give user name as the key. But I am going to cache various items in different views and having the same key every where is not feasible. I was thinking on may be giving a key with username+ 'some view specific' so that the key can be unique.

Does any one have any other good suggestions for generating keys?

1

There are 1 answers

0
AKS On BEST ANSWER

Generation of keys can depend on what you are tying to achieve.

  1. Is what the user is trying to access for that user only?
  2. Is what the user is trying to access generic for all the users?

e.g.

let's say you are trying to access a url:

http://yourserver/endpoint/?filter1=value1&filter2=value2

In the above case, you can use the query params filter1=value1&filter2=value2 to create a cached key (by generating the md5 hash).

Considering the two options earlier, if the view should return some data specific to the user then you can also append the user id to create a unique key for the user.

Another example could be a url like this, where one is trying to access all the articles from source 1:

http://yourserver/source/1/articles/?filter1=value1&filter2=value2 

In this case it might also be useful to append the cache key with the source id (so this uses the context data for the views in generating the keys).