Login

localsettings

Author:
elpaso66
Posted:
February 28, 2010
Language:
Python
Version:
1.1
Tags:
settings
Score:
0 (after 0 ratings)

I'm using this to store settings in a thread-safe manner on mod_wsgi multithread deployment.

The idea is to import from localsettings import localsettings instead of doing from django.conf import settings and use it as you would use normal settings, with the difference that you can alter settings for the current thread with a middleware (think of altering SITE_ID).

Warning: altering settings is not officially supported and can lead to thread problems.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#################################
#
# Thread local settings storage
#
# Use threading.local() to store thread
# specific settings
#
# Reads from threading.local first and
# from settings as a fall-back
#


from django.conf import settings
import threading


DISABLE_LOGGING = True

if not DISABLE_LOGGING and settings.DEBUG:
    import logging


class LocalSettings():
    """
    Singleton interface to threading.local() settings override
    """
    __instance = None

    def __init__(self):
        if LocalSettings.__instance is None:
            if not DISABLE_LOGGING and settings.DEBUG:
                logging.warn('LocalSettings : CREATE SINGLETON')

            LocalSettings.__instance = threading.local()
            # Store __instance reference as the only member in the handle
            self.__dict__['_LocalSettings__instance'] = LocalSettings.__instance

    def __getattr__(self, key):
        if not DISABLE_LOGGING and settings.DEBUG :
            logging.warn('%s LocalSettings : GET key %s - thread %s' % (getattr(LocalSettings.__instance, 'SITE_ID', getattr(settings, 'SITE_ID')), key, threading.currentThread()))
        try:
            return getattr(LocalSettings.__instance, key)
        except:
            return getattr(settings, key)

    def __setattr__(self, key, value):
        if not DISABLE_LOGGING and settings.DEBUG:
            logging.warn('%s LocalSettings : SET %s = %s - thread %s' % (getattr(LocalSettings.__instance, 'SITE_ID', getattr(settings, 'SITE_ID')), key, value , threading.currentThread()))
        setattr(LocalSettings.__instance, key, value)

localsettings = LocalSettings()

More like this

  1. Default settings for a app by phxx 6 years, 10 months ago
  2. Scoped Cache Compatible with Django Caching Helpers by axiak 7 years, 1 month ago
  3. Clean Reversion History: Remove unimportant Changes by guettli 3 years, 2 months ago
  4. Save image in field by grillermo 3 years, 3 months ago
  5. Persistent connection to PostgreSQL database by mike_tk 5 years, 8 months ago

Comments

Please login first before commenting.