Login

Tag "middleware"

Snippet List

Middleware to detect visitors who arrived from a search engine

Sometimes it's nice to know if your visitors came from a search engine such as Google or Yahoo. I use this as a component in determining the popularity of blog articles for search keywords, so I know which articles to automatically feature or suggest. Maybe you'd like to use it to highlight the visitor's search terms on the page. This isn't actually middleware in the sense that it defines any of the middleware interfaces. It's intended to be the base for a middleware method that you write, depending on what you want to happen when you detect that the visitor came from a search engine. In the example `process_view` method, I detect when the request is going to use the `object_detail` view and log the search query for that object in the database.

  • middleware
  • search-engine
  • referrer
Read More

Profiling Middlware

Displays hotshot profiling for any view. http://yoursite.com/yourview/?prof Add the "prof" key to query string by appending ?prof (or &prof=) and you'll see the profiling results in your browser. It's set up to only be available in django's debug mode, but you really shouldn't add this middleware to any production configuration. * Only tested on Linux * You should probably use this one instead: http://djangosnippets.org/snippets/2126/

  • middleware
  • profile
  • debug
  • stats
  • performance
  • hotshot
Read More

HttpMethodsMiddleware

This middleware allows developers to "fake" browser support for HTTP methods. Even though most modern browsers only support GET and POST, the HTTP standard defines others. In the context of REST, PUT and DELETE are used for client interaction with the server. For forms with a PUT or DELETE method, this middleware will change them to go through POST, and will include an invisible field called "method_middleware_transform" that carries the originally intended method. So, `<form method="PUT" ...>...</form>` More or less becomes `<form method="POST" ...><input type=hidden name="method_middleware_transform" value="PUT"></form>` (with a few other minor HTML modifications) The process is completely transparent to the developer... you never have to deal with the fact that browsers don't support the standard methods. **One caveat** is that server interaction via `XMLHttpRequest` (AJAX) requires special attention... this middleware won't properly setup your XMLHttpRequest to take advantage of this functionality. This is a combination of the work of Jesse Lovelace and the Django CSRF middleware.

  • middleware
  • rest
Read More

Avoid IE Brokenness When using Vary and Attachments

Apparently Internet Explorer (6 and 7) have a bug whereby if you blindly attach a PDF or some other file, it will choke. The problem lies in the Vary header (bug described in http://support.microsoft.com/kb/824847/en-us?spid=8722&sid=global). To use, just add to the beginning of your middleware classes.

  • middleware
  • ie
  • vary
Read More

Strip html comments middleware

Middleware for stripping all html comments from the response content before returning it to the client. This will also strip inline javascript with htmlcomments put around it!

  • middleware
  • comments
Read More

AppendSlashMiddleware

**I won't be able to debug this until tonight... so if you see this message there may still be bugs in this** This Middleware replaces the behavior of the APPEND_SLASH in the CommonMiddleware. Please set APPEND_SLASH = False if you are going to use this Middleware. Add the key defined by APPENDSLASH to the view_kwargs and a True or False to determine the behaivor of the appended slashes. For instance I set my DEFAULTBEHAVIOR to the default of True, then to override that behaivor I add 'AppendSlash':False to the URLs that I wish to have no slash. **Example** ` urlpatterns = patterns('some_site.some_app.views', (r'^test/no_append$','test_no_append',{'AppendSlash':False}), (r'^test/append/$','test_append'), ) `

  • middleware
Read More

SSL Middleware

**SSL Middleware** This middleware answers the problem of redirecting to (and from) a SSL secured path by stating what paths should be secured in urls.py file. To secure a path, add the additional view_kwarg 'SSL':True to the view_kwargs. For example ` urlpatterns = patterns('some_site.some_app.views', (r'^test/secure/$','test_secure',{'SSL':True}), ) ` All paths where 'SSL':False or where the kwarg of 'SSL' is not specified are routed to an unsecure path. For example ` urlpatterns = patterns('some_site.some_app.views', (r'^test/unsecure1/$','test_unsecure',{'SSL':False}), (r'^test/unsecure2/$','test_unsecure'), ) ` **Gotcha's** Redirects should only occur during GETs; this is due to the fact that POST data will get lost in the redirect. **Benefits/Reasoning** A major benefit of this approach is that it allows you to secure django.contrib views and generic views without having to modify the base code or wrapping the view. This method is also better than the two alternative approaches of adding to the settings file or using a decorator. It is better than the tactic of creating a list of paths to secure in the settings file, because you DRY. You are also not forced to consider all paths in a single location. Instead you can address the security of a path in the urls file that it is resolved in. It is better than the tactic of using a @secure or @unsecure decorator, because it prevents decorator build up on your view methods. Having a bunch of decorators makes views cumbersome to read and looks pretty redundant. Also because the all views pass through the middleware you can specify the only secure paths and the remaining paths can be assumed to be unsecure and handled by the middleware. This package is inspired by Antonio Cavedoni's SSL Middleware Notes: Updated per Jay Parlar at http://www.djangosnippets.org/snippets/240/ - Added a test for the way webfaction handles forwarded SSL requests.

  • middleware
  • ssl
Read More

Url filter middleware

How to config it ------------------ You can treat it as a micro url filter framework. Before you using it, you should setup some options about it. The option entry shoud be like this: FILTERS = ( (r'^user/(?P<user_id>\d+)/', 'apps.users.filter.check_valid_user'), ) FILTERS should be a list or tuple with two elements tuple item. The format should be like: (url_patterns, function) And url_patterns could be a single regex expression or a list/tuple regex expressions, So you can set multi regex expression in it. And the regulation is just like url dispatch, as above example, the url pattern is: r'^user/(?P<user_id>\d+)/' So you can see, you can set parameter name `user_id`, then it'll be passed to the function behind. Function can be a string format, just like above example, and it can be also a real function object. It'll only impact request. How to write filter function ------------------------------- According above example, I define a url pattern, and what to check if the user is a valid user, and if the user is visiting his own urls, so the filter function could be: from django.contrib.auth.models import User from utils.common import render_template def check_valid_user(request, user_id): if request.user.is_anonymous(): return render_template(request, 'users/user_login.html', {'next':'%s' % request.path}) try: person = User.objects.get(pk=int(user_id)) except User.DoesNotExist: return render_template(request, 'error.html', {'message':_("User ID (%s) is not existed!") % user_id}) if person.id != request.user.id: return render_template(request, 'error.html', {'message':_('You have no right to view the page!')}) I think the code is very clear. And you can use it filtermiddleware to do like user authentication check, and other checking for url. BTW, render_template is comes from [Snippets #4](http://www.djangosnippets.org/snippets/4/)

  • middleware
  • filter
  • url
Read More

Browser Verification

A page we used on Curse to stop users who are new, who are using old browsers (ones who usually have extreme issues with CSS handling) and recommend they update. Can easily be modified to suit your needs.

  • middleware
  • browsers
  • validation
Read More

Format transition middleware

Note: This is a testing middleware. This snippets may be changed frequently later. What's it ----------- Sometimes I thought thow to easy the output data into another format, except html format. One way, you can use decorator, just like: @render_template(template='xxx') def viewfunc(request,...): And the output data of viewfunc should be pure data. And if want to output json format, you should change the decorator to: @json_response def viewfunc(request,...): I think it's not difficult. But if we can make it easier? Of cause, using middleware. So you can see the code of `process_response`, it'll judge the response object first, if it's an instance of HttpResponse, then directly return it. If it's not, then get the format of requst, if it's `json` format, then use json_response() to render the result. How to setup `request.format`? In `process_request` you and see, if the `request.REQUEST` has a `format` (you can setup it in settings.py with FORMAT_STRING option), then the `request.format` will be set as it. If there is not a such key, then the default will be `json`. So in your view code, you can just return a python variable, this middleware will automatically render this python variable into json format data and return. For 0.2 it support xml-rpc. But it's very different from common implementation. For server url, you just need put the same url as the normal url, for example: http://localhost:8000/booklist/ajax_list/?format=xmlrpc Notice that the format is 'xmlrpc'. A text client program is: from xmlrpclib import ServerProxy server = ServerProxy("http://localhost:8000/booklist/ajax_list/?format=xmlrpc", verbose=True) print server.booklist({'name':'limodou'}) And the method 'booklist' of server is useless, because the url has include the really view function, so you can use any name after `server`. And for parameters of the method, you should use a dict, and this dict will automatically convert into request.POST item. For above example, `{'name':'limodou'}`, you can visit it via `request.POST['name']` . For `html` format, you can register a `format_processor` callable object in `request` object. And middleware will use this callable object if the format is `html`. Intall --------- Because the view function may return non-HttpResponse object, so this middleware should be installed at the end of MIDDLEWARE_CLASSES sections, so that the `process_response` of this middleware can be invoked at the first time before others middlewares. And I also think this mechanism can be extended later, for example support xml-rpc, template render later, etc, but I have not implemented them, just a thought. Options --------- FORMAT_STRING used for specify the key name of format variable pair in QUERY_STRING or POST data, if you don't set it in settings.py, default is 'format'. DEFAYLT_FORMAT used for default format, if you don't set it in settings.py, default is 'json'. Reference ----------- Snippets 8 [ajax protocol for data](http://www.djangosnippets.org/snippets/8/) for json_response

  • middleware
  • format
  • json
Read More

Simple profile middleware

Intall -------- In your settings.py, set it in MIDDLEWARE_CLASSES. Default all the profile files will be save in ./profile folder(if there is no this directory, it'll automatically create one), and you can set a PROFILE_DATA_DIR option in settings.py, so that the profile files can be saved in this folder. How does it works ------------------- Record every request in a profile file. As you can see in the code: profname = "%s.prof" % (request.path.strip("/").replace('/', '.')) so if you request an url multi-times, only the last request will be saved, because previous profile files will be overriden. And you can find a commentted line, it'll save each request in different file according the time, so if you like that you can change the code. # profname = "%s.%.3f.prof" % (request.path.strip("/").replace('/', '.'), time.time()) and if you want to see the output, you can run below code, but you should change the filename value: import hotshot, hotshot.stats stats = hotshot.stats.load(filename) #stats.strip_dirs() #stats.sort_stats('time', 'calls') stats.print_stats()

  • middleware
  • profile
Read More

SQL Log Middleware

This middleware will add a log of the SQL queries executed at the bottom of every page. You can (should) use BeautifulSoup to place this in a specific location. Note: If you serve non-html content, it would be wise to do a mimetype check.

  • sql
  • middleware
  • log
Read More

Basic HTTP Authentication

A patch (against django svn trunk [4649](http://code.djangoproject.com/browser/django/trunk/?rev=4649)) that allows users to log in with Basic HTTP Authentication i.s.o. login forms using some simple middleware (entire patch is ~50 lines). I was unaware of http://code.djangoproject.com/wiki/GenericAuthorization so I'm not sure about its usefulness in the long run. You can enable it by including 'django.contrib.auth.middleware.BasicAuthenticationMiddleware' in your MIDDLEWARE_CLASSES and then adding the following lines in your settings.py: BASIC_WWW_AUTHENTICATION = True WWW_AUTHENTICATION_REALM = "djangolures.com" Updated: See also http://code.djangoproject.com/ticket/3609 (patch now availble here as well).

  • middleware
  • django
  • http
  • basic
  • authentication
Read More

181 snippets posted so far.