You implement a request preprocessor by defining a process_request(self, request) function in the middleware class. The process_request() function is called after the request has been received but before the URL gets resolved to determine which view function to run.
The process_request() function is passed the HttpRequest object of the request. Any changes you make to the HttpRequest object are also passed down to the view function.
The process_request() function can return either None or an HttpResponse object. If None is returned, Django continues processing the request. However, if you return an HttpResponse object, the request immediately returns that response.
The SetRemoteAddrFromForwardedFor application uses the following code snippet to replace the REMOTE_ADDR attribute of the request with the HTTP_X_FORWARDED_FOR attribute for requests coming through a proxy:
def process_request(self, request): try: real_ip = request.META['HTTP_X_FORWARDED_FOR'] except KeyError: pass else: real_ip = real_ip.split(",")[0] request.META[REMOTE_ADDR'] = real_ip
Try It Yourself: Create and Install a Request Preprocessor Middleware ApplicationIn this section, you will create and install a view preprocessor application, called CustomViewLogger, that logs information about view functions before they are run. You will also create a new application called Log in the database, and then you will define a new RequestEvent model in the Log application to store information about requests. You will also implement a new view_log() view function and template that will render the RequestEvent objects. By the Way The examples in this hour are just meant to illustrate data that can be accessed in the middleware. If you want to implement a logging system for a large website that has numerous requests, you will probably want to use another method, such as a buffered file, for storage than the site database. Follow these steps to implement a request preprocessor middleware application:
Listing 19.1. The Imports and RequestEvent Definition of the iFriends/Log/models.py File
Listing 19.2. The Imports and CustomRequestLogger Definition of the django/middleware/custom.py File
Listing 19.3. Full Contents of the iFriends/templates/Custom/view_request_log.py File
Listing 19.4. The view_log() View Function of the iFriends/Custom/views.py File
|