Login

GlobalRequest middleware

Author:
myq
Posted:
November 26, 2012
Language:
Python
Version:
1.4
Tags:
middleware request
Score:
0 (after 0 ratings)

Thread-safe middleware that makes the current request object available globally.

 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
from threading import current_thread

class GlobalRequest(object):
    _requests = {}

    @staticmethod
    def get_request():
	try:
            return GlobalRequest._requests[current_thread()]
	except KeyError:
            return None

    def process_request(self, request):
        GlobalRequest._requests[current_thread()] = request

    def process_response(self, request, response):
        # Cleanup                                                               
        thread = current_thread()
        try:
            del GlobalRequest._requests[thread]
        except KeyError:
            pass
        return response

def get_request():
    return GlobalRequest.get_request()

More like this

  1. another request logging middleware with request time and extra info by yoav 3 years, 7 months ago
  2. Accept Header Middleware by kioopi 7 years, 3 months ago
  3. logging tastypie middleware by lalutium 8 months, 3 weeks ago
  4. Middleware to reload translation for each request by asksol 5 years, 11 months ago
  5. Cookieless Session Middleware by juliocarlos 6 years, 7 months ago

Comments

Please login first before commenting.