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
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 8 months ago
Comments
Please login first before commenting.