March 2020
Intermediate to advanced
608 pages
17h 17m
English
Execute the following two steps to set up ThreadLocalMiddleware, which can be used to get the current HttpRequest or user in any function or method of the project's code:
# myproject/apps/core/middleware.pyfrom threading import local_thread_locals = local()def get_current_request(): """ :returns the HttpRequest object for this thread """ return getattr(_thread_locals, "request", None)def get_current_user(): """ :returns the current user if it exists or None otherwise """ request = get_current_request() if request: return getattr(request, "user", None)class ThreadLocalMiddleware(object): """ Middleware to add the HttpRequest to thread local storage """