1# Copyright 2017 Google LLC All Rights Reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15"""Django middleware helper to capture a request.
16
17The request is stored on a thread-local so that it can be
18inspected by other helpers.
19"""
20
21import threading
22
23
24_thread_locals = threading.local()
25
26
27def _get_django_request():
28 """Get Django request from thread local.
29
30 Returns:
31 str: Django request
32 """
33 return getattr(_thread_locals, "request", None)
34
35
36def RequestMiddleware(get_response):
37 """Saves the request in thread local"""
38
39 def middleware(request):
40 """Called on each request, before Django decides which view to execute.
41
42 Args:
43 request(django.http.request.HttpRequest):
44 Django http request.
45 """
46 _thread_locals.request = request
47 if get_response:
48 return get_response(request)
49 else:
50 return None
51
52 return middleware