A middleware which will protect from page hammering using flexible spanning time windows using the cache backend.
Please read the Docstring of the class for details.
Other approach of making middleware. Advantage of is to specify, which middleware is used for which view function and in what order. Middleware function gets all arguments, that are passed to view function.
**Example usage**
@RequestMiddleware
def print_params_middleware(request, *args, **kwargs):
print 'GET params:', request.GET
@ResponseMiddleware
def modify_headers_middleware(request, response, *args, **kwargs):
response['Content-Type'] = 'text/html'
@ExceptionMiddleware
def catch_error_middleware(request, e, *args, **kwargs):
return HttpResponse('catched error %s' % e )
@modify_headers_middleware
@catch_error_middleware
@print_params_middleware
def some_view(request, *args, **kwargs):
print 'someview'
return HttpResponse()
This is an improvement of [joshua](http://djangosnippets.org/users/joshua/)'s [SQL Log Middleware](http://djangosnippets.org/snippets/61/).
If you have more than one database connection, then all queries are logged, grouped by connection.
If a connection has no queries, then it's not shown.
Due to compliance requirements in the financials industry we needed to log every request a user made to our system, the action taken (view function) and response from the server.
I found a lot of other logging solution bit most revolved around debugging and DB query logging. I needed to be able to tell what a user did while being logged in as much detail as I could with out tracking the mouse pointer position on screen.
So I created this (, *my first* ,) middleware. Its very simple really. keeping track of a request, view_func and response object in a single model called Record (models.py file included in the code).
The fields I used are optimized to what I intend to show in the UI I am planning for this model. Depending on how you use the doc string of your views they can be tapped to explain to the user what each request/func/responce group in a session is meant to do.
There were a few gotcha's:
1. I only care about authenticated requests. So I added the 'quest.user.is_authenticated()' test.
2. I did not care about the favicon request so I skipped them.
2. The actual login request is not authenticated while the response is. This caused the process_response/view to look for a record that is not there. So I added the 'except ObjectDoesNotExist' to skip this case.
I added one bell: Logging a full HTML reply is wasteful and mostly useless. I added two values in the setting files. LOGALL_LOG_HTML_RESPONSE to toggle if we want to log them or not. And LOGALL_HTML_START to describe what a full HTML starts with. Personally I use the first few characters of my base.html template that all the rest of my templates expend. I simplified the code to the left for readability.
Allows url patterns to include a boolean indicating whether a view requires
TLS(SSL). The accompanying middleware handles the redirects needed to make
sure that it upholds this requirement.
**WARNING**: this monkey-patches some Django internals and is difficult to test
since Django's TestClient does not support TLS. If you use this make sure you
test it thouroughly.
Add this to your Django settings
USE_TLS = True # The default for this setting is False.
URL pattern usage
url(r'^login$', 'myproject.login.index',
{'require_tls': True}, name='login-index'),
Use `require_tls` True to force the middleware to perform redirects needed to
make sure your are serving this view using https.
Use `require_tls` False to force the middleware to redirect to http. Be
careful with this setting, this may not behave as you expect. If you don't
care if the view is served via https or http then do not include
`require_tls` in the pattern.
If you wish to have every view in the site served with TLS then specify the
following Django setting
ALWAYS_USE_TLS = True # Django setting, use TLS for every view
An accept middleware, which is based on the code of http://djangosnippets.org/snippets/1042/ but adds a workaround for the buggy accept header, sent from webkit browsers such as safari and chrome.
The workaround affects any accept header, that has xml and (x)html in the best q, but also the xml mediatype at first place in the list.
If this is the case, the header is rearanged, by shifting the xml mediatype to become the last element of the best quality entries in the header.
If the workaround did manipulate the header, and there is a html entry in the list with lower quality as an xhtml entry that is also in the list (with best q), then the html entry is also raised in q to be one entry in front of xml.
Mechanism to obtain a `request.user` object without the `request` object itself. Requires `LocalUserMiddleware` in `MIDDLEWARE_CLASSES` settings variable.
**Important**: works under assumption that within a web server each request is handled by a separate thread (as for example in the Apache HTTP server).
**Beware**: [security threat](http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser), although ["thread locals only appears to be a security threat if a system has already been seriously compromised, at which point there'd be easier attacks to execute"](http://groups.google.com/group/django-users/browse_thread/thread/e7af359d7d183e04).
**Dev note**: works fine with one-threaded Django's development server, each request resets current user; no worries 'bout many media requests - they won't (at least shouldn't) be using Django on the production server.
**Ref**: originally found in the gatekeeper app.
Based on [Extended Profiling Middleware](http://djangosnippets.org/snippets/605/), this version allows interactive sorting of functions and inspection of SQL queries.
The middleware assigns a unique identifier for session. The session id doesn't depend of session or whatever else. It only need cookies to be turned on.
The session id is reassigned after client close a browser. Identifier of the session could be read from request: request.current_session_id.
You can setup name of the cookie in yours settings module (FLASH_SESSION_COOKIE_NAME).
request.current_session_id is lazy. It means the ID will be assigned and cookie will be returned to client after first usage.
Add it to MIDDLEWARE_CLASSES and you will get request.current_view getting values like "connection.views.index" or "django.views.static.serve" - one example usage is to show different help text based on current view name.
EDIT: actually, you can use process_view middleware function where you automatically get current_view as first parameter.
This middleware will prevent access to the admin if the users IP isn't in the INTERNAL_IPS setting, by comparing the request path with the reversed index URL of the default admin site, ultimately raising a 404 (unless DEBUG = True).
This module provides a middleware that implements a mechanism to
highlight a link pointing to the current URL.
Every link on the rendered page matching the current URL will be highlighted with a 'current_page' CSS class.
The name of the CSS class can be changed by setting `CURRENT_PAGE_CLASS` in the project settings.
Originally done by Martin Pieuchot and Bruno Renié, thanks @davidbgk and @samueladam for improvements & optimizations.
Middleware class that checks the user agent against a known list of strings found in mobile devices, and if matched it then tries to determine the name of the template being rendered based on the convention of having every view use a keyword arg called "template". It then adds "mobile" to the template name and if the mobile template exists, it will override the "template" arg for the view with the mobile template name.