Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

request: Maintain a thread-local of the current request.

Alex Vandiver6323218a0e0f
diff --git a/zerver/lib/request.py b/zerver/lib/request.py
index 892dea5edd0..099a1b390fe 100644
--- a/zerver/lib/request.py
+++ b/zerver/lib/request.py
@@ -1,3 +1,4 @@
+import threading
from collections import defaultdict
from functools import wraps
from types import FunctionType
@@ -366,3 +367,22 @@ def has_request_variables(view_func: ViewFuncT) -> ViewFuncT:
return view_func(request, *args, **kwargs)
return cast(ViewFuncT, _wrapped_view_func) # https://github.com/python/mypy/issues/1927
+
+
+local = threading.local()
+
+def get_current_request() -> Optional[HttpRequest]:
+ """Returns the current HttpRequest object; this should only be used by
+ logging frameworks, which have no other access to the current
+ request. All other codepaths should pass through the current
+ request object, rather than rely on this thread-local global.
+
+ """
+ return getattr(local, 'request', None)
+
+def set_request(req: HttpRequest) -> None:
+ setattr(local, 'request', req)
+
+def unset_request() -> None:
+ if hasattr(local, 'request'):
+ delattr(local, 'request')
diff --git a/zerver/middleware.py b/zerver/middleware.py
index f23f8c7038d..e137bd36356 100644
--- a/zerver/middleware.py
+++ b/zerver/middleware.py
@@ -23,6 +23,7 @@ from zerver.lib.exceptions import ErrorCode, JsonableError, MissingAuthenticatio
from zerver.lib.html_to_text import get_content_description
from zerver.lib.markdown import get_markdown_requests, get_markdown_time
from zerver.lib.rate_limiter import RateLimitResult
+from zerver.lib.request import set_request, unset_request
from zerver.lib.response import json_error, json_response_from_error, json_unauthorized
from zerver.lib.subdomains import get_subdomain
from zerver.lib.types import ViewFuncT
@@ -224,6 +225,14 @@ def write_log_line(log_data: MutableMapping[str, Any], path: str, method: str, r
error_data = "[content more than 200 characters]"
logger.info('status=%3d, data=%s, uid=%s', status_code, error_data, requestor_for_logs)
+class RequestContext(MiddlewareMixin):
+ def __call__(self, request: HttpRequest) -> HttpResponse:
+ set_request(request)
+ try:
+ return self.get_response(request)
+ finally:
+ unset_request()
+
class LogRequests(MiddlewareMixin):
# We primarily are doing logging using the process_view hook, but
# for some views, process_view isn't run, so we call the start
diff --git a/zproject/computed_settings.py b/zproject/computed_settings.py
index d6a32b6ae64..1b3a29dfb6c 100644
--- a/zproject/computed_settings.py
+++ b/zproject/computed_settings.py
@@ -178,6 +178,7 @@ MIDDLEWARE = (
# our logging middleware should be the top middleware item.
'zerver.middleware.TagRequests',
'zerver.middleware.SetRemoteAddrFromForwardedFor',
+ 'zerver.middleware.RequestContext',
'zerver.middleware.LogRequests',
'zerver.middleware.JsonErrorHandler',
'zerver.middleware.RateLimitMiddleware',