Login

Dynamic SITE_ID thread-safe

Author:
jhg
Posted:
April 16, 2014
Language:
Python
Version:
1.6
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. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.