Skip to content

Instantly share code, notes, and snippets.

@alexpirine
Created September 4, 2016 05:22
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save alexpirine/7357232ecf3aab8beb5565b89c587e6d to your computer and use it in GitHub Desktop.
Django (1.10-compatible) thread local (TLS) middleware
# coding: utf-8
# Copyright (c) Alexandre Syenchuk (alexpirine), 2016
try:
from threading import local
except ImportError:
from django.utils._threading_local import local
_thread_locals = local()
def get_current_request():
return getattr(_thread_locals, 'request', None)
def get_current_user():
request = get_current_request()
if request:
return getattr(request, 'user', None)
class ThreadLocalMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
_thread_locals.request = request
return self.get_response(request)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment