开发者

What's a good way to load and store data in global constants for caching in Django?

开发者 https://www.devze.com 2023-02-15 09:05 出处:网络
How do you normally load and store stuff from the DB in global constants for caching during initialisation? The global constants will not change again later.

How do you normally load and store stuff from the DB in global constants for caching during initialisation? The global constants will not change again later. Do you just make the DB query during load time and put it in a constant, or use a lazy loading mechanism of some sort?

What I have in mind is code in the global scope like this:

SPECIAL_USER_GROUP = Group.objects.get(name='very special users')
OTHER_THING_THAT_DOESNT_CHANGE = SomeDbEnum.objects.filter(is_enabled=True)
# several more items like this

I ran into issues doing that when running tests using an empty test database. An option would be to put all the needed data in fixtures, but I want to avoid coupling each individual test with irrelevant data they don't need.

Would the following be considered good style?

@memoize
def get_special_user_group():
  开发者_开发技巧  return Group.objects.get(name='very special users')

Or would a generic reusable mechanism be preferred?


Django has a cache framework that you could use.

http://docs.djangoproject.com/en/dev/topics/cache/

It's got a low level caching api that does what you want.

from django.core.cache import cache
cache.set('my_key', 'hello, world!', 30)
cache.get('my_key')

To use it, you'd do something like

if cache.get("key"):
    return cache.get("key")
else:
    value = some_expensive_operation()
    cache.set("key",value)
    return value

Using something like this will give you more flexibility in the future.


An option would be to put all the needed data in fixtures,

Good thinking.

but I want to avoid coupling each individual test with irrelevant data they don't need.

Then define smaller fixtures.

If necessary, use the TestCase setUp method to create the necessary database row.

0

精彩评论

暂无评论...
验证码 换一张
取 消