Login

Dynamic SITE_ID thread-safe

Author:
jhg
Posted:
April 16, 2014
Language:
Python
Version:
1.6
Tags:
dynamic site_id thread-locals
Score:
1 (after 1 ratings)

Store in SiteID a local var store for save SITE_ID thread-safe and set it with middleware. It's base on https://djangosnippets.org/snippets/1099/ but with call to local() in SiteID and using custom models for web site and domains.

 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
# Class for thread-safe SITE_ID object
from threading import local


class SiteID(object):

    def __init__(self):
        self._site_thread_info = local()
        self._site_thread_info.SITE_ID = 1

    def __int__(self):
        return self._site_thread_info.SITE_ID

    def __hash__(self):
        return self._site_thread_info.SITE_ID

    def __str__(self):
        return str(self._site_thread_info.SITE_ID)

    def _set(self, new_id):
        self._site_thread_info.SITE_ID = new_id

# Middleware
from django.conf import settings
from sitiosweb.models import DomainDNS


class SetDynamicSites(object):
    """ Change SITE_ID dinamics with trhead safe """
    def process_request(self, request):
        try:
            current_site = DomainDNS.objects.get(domain=request.get_host()).website
            settings.SITE_ID._set(int(current_site.id))
        except:
            settings.SITE_ID._set(1)
        return None

# Settings
from sitiosweb.site_id_local import SiteID

MIDDLEWARE_CLASSES = (
    'sitiosweb.middleware.DynamicSites.SetDynamicSites',
    ...
)

SITE_ID = SiteID()

More like this

  1. localsettings by elpaso66 5 years, 6 months ago
  2. {% ifthis FOO isoneof BAR BAZ ... %} by sjl 5 years, 3 months ago
  3. GlobalRequest middleware by myq 2 years, 9 months ago
  4. nested transactions context manager and decorator by demanzano 4 years ago
  5. Custom Cache with SITE_ID in key by luke256 6 years, 3 months ago

Comments

Please login first before commenting.