Login

Tag "middleware"

Snippet List

Smart append slash middleware

This middleware replaces the behavior of the APPEND_SLASH setting in the CommonMiddleware. Please set `APPEND_SLASH = False` and `SMART_APPEND_SLASH = True` if you are going to use this middleware. In your URL patterns, omit the trailing slash for URLs you want accessible without the slash. Include the slash for those URLs you wish to be automatically redirected from an URL with the slash missing. If a URL pattern exists both with and without a slash, they are treated as two distinct URLs and no redirection is done. Example urlpatterns = patterns('some_site.some_app.views', (r'^test/no_append$','test_no_append'), (r'^test/append/$','test_append'), (r'^test/distinct_url$', 'view_one'), (r'^test/distinct_url/$', 'view_two'), ) Behavior of URLs against the above patterns with SMART_APPEND_SLASH enabled: http://some_site/test/no_append → test_no_append() http://some_site/test/no_append/ → 404 http://some_site/test/append → http://some_site/test/append/ http://some_site/test/append/ → test_append() http://some_site/test/distinct_url → view_one() http://some_site/test/distinct_url/ → view_two() This module is also available [in our SVN repository](http://trac.ambitone.com/ambidjangolib/browser/trunk/middleware/common.py).

  • middleware
  • url
  • slash
Read More

Logging and statistic middleware

Reviewing some statistic-middleware-classes I think you might need one wich is working correct and high-performant. Please comment it and have fun with it!

  • middleware
  • stats
  • logging
  • statistic
  • user-activities
Read More

AjaxCheckMiddleware

Simply adds an attribute `is_ajax` to a request object, indicating if the request was made via Ajax. Allows you to reuse a lot of POST processing view code to which you'd like to progressively add Ajax: `if request.is_ajax: return JsonResponse(some_json)` `else: return render_to_response('some_template.html')`

  • middleware
  • ajax
  • request
Read More

Color SQL logging middleware

Yet another SQL logger, this time with color and tresholds. By default it will only print a summary line (total time, query count) unless one of the tresholds (total time, query count, individual query time) was exceeded. You may use LOG_COLORSQL_VERBOSE = True to get the raw SQL for all requests regardless of any configured tresholds. In either case the middleware will highlight problematic areas in yellow or red. If you don't like the colors you can either set your tresholds to really high values, edit the code, or use a different middleware. :-)

  • sql
  • middleware
  • log
Read More
Author: moe
  • 4
  • 13

SQLLoggerMidleware + infobar

This middleware will add a log of the SQL queries executed at the top of every page, in the form of an IE-like 'infobar'. It also includes a query count and total and per-query execution times. This snippet is based on snippet #344 "SQL Log Middleware + duplicates" by guettli. I did some adjustments to the code, to also add support for the application/xhtml+xml mime type, aswell as add the code for the infobar. Need DEBUG on, aswell as DEBUG_SQL, should not be used on production sites. It also expects a 16x16 png image called infobar_icon.png, which it is looking for in the /media/images folder (or /static/images, depending on your MEDIA_URL setting). I used a little light bulb icon from the Tango icon set, but am unable to attach the image. Any 16x16 png will do off course. Update 0.1.1: In the initial version of this middleware, the path to /media/images was hard-coded, and you had to adjust this middleware accordingly. Now, it correctly uses the MEDIA_URL setting from your settings.py file, so you no longer have to edit this middleware. 0.1.2: Made some adjustments to the CSS to get rid of a padding bug when the bar was displayed on a Django error page. Also if a page contains no queries, it won't bother printing an 'empty' table, with just column headers. 0.1.3: More tweaks to the CSS, odd/even row shading on queries table. 0.1.4: More CSS tweaks again 0.1.5: Minor tweaks 0.1.6: Sorry, I just realised that after some time, this snippet broke in the latest SVN of Django with a Unicode error, as arthur78 mentioned. I have managed to fix it, by wrapping line 258 and 259 in an str() function.

  • sql
  • middleware
  • logger
Read More

Little middleware that create a facebook user

**How to use**: 1. Install [**PyFacebook** package](http://wiki.developers.facebook.com/index.php/PythonPyFacebookTutorial). 2. After make all steps in tutorial above, put this code in your app's models.py module (you maybe prefer split it and put the middleware class in some other file). 3. Put the FacebookUserMiddleware python-path in the MIDDLEWARE_CLASSES in your settings.py (after facebook.djangofb.FacebookMiddleware). You probably will add some fields to FacebookUser model class :)

  • middleware
  • user
  • facebook
Read More

URL redirects middleware

Sometimes you need to make redirects that involve domains, you can't define those on the site urls, this middleware lets you define multiple redirects on your site settings. Note: *You also can use the web server to do this, but I have found this middleware a useful tool to quickly or temporarily define redirects*. Depending on your needs you may also find useful [snippet 434](http://www.djangosnippets.org/snippets/434/).

  • middleware
  • url
  • redirect
  • domain
Read More

PreSaveMiddleware

With this middleware in place (add it to the MIDDLEWARE_CLASSES in your settings) you can pass a request to the model via a pre_save method on the model. I'm not sure if it is an improvement over the [threadlocals method] (http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser) but it may be an alternative that can be improved upon? class MyModel(models.Model): name = models.CharField(max_length=50) created = models.DateTimeField() created_by = models.ForeignKey(User, null=True, blank=True) def pre_save(self, request): if not self.id: self.created_by = request.user

  • middleware
  • pre_save
  • signals
Read More

Sessions and authentication without cookies

[The Session documentation](http://www.djangoproject.com/documentation/sessions/) rightly warns of the dangers of putting a session ID into a query string. Sometimes, however, you have to do it - perhaps your client has mandated support for browsers with cookies disabled, or perhaps (as in my case) you're just dealing with a slightly broken client browser. This middleware pulls a session ID out of the query string an inserts it into the cookies collection. You'll need to include it in your MIDDLEWARE_CLASSES tuple in settings.py, *before* the SessionMiddleware. *Please* read my [full blog post](http://www.stereoplex.com/two-voices/cookieless-django-sessions-and-authentication-without-cookies) about for the dangers of doing this, and for full instructions and examples.

  • middleware
  • cookie
  • session
  • authentication
  • string
  • query
  • cookieless
  • querystring
Read More

Auto Logout Middleware

This Middleware is to log users out after a certain amount of time has passed. You'll want to add AUTO_LOGOUT_DELAY to your settings.py, set to a number of minutes after which a user should be logged out. It adds the key 'last_touch' to the session, you'll want to change that if you happen to be using that already.

  • middleware
  • auth
  • logout
Read More

Per-site vary cache on language

I like the per-site caching offered by Django (it's simple) and I like the cache to be dependent on the chosen language. Unfortunately with the current `CacheMiddleware` you can either have the one or the other but not both at the same time. `VaryOnLangCacheMiddleware` is a small wrapper around `CacheMiddleware`. It looks at the `request.LANGUAGE_CODE` (set by `LocaleMiddleware`) and appends it to your `CACHE_MIDDLEWARE_KEY_PREFIX`. So "mysiteprefix" becomes "mysiteprefix_en" or "mysiteprefix_de-AT" depending on the user's chosen language. Site-wide, so no messing with per-view decorators and stuff. To use this, make sure `VaryOnLangCacheMiddleware` comes below `LocaleMiddleware` in your settings.py. If you haven't set your `CACHE_MIDDLEWARE_KEY_PREFIX`, it's works, too. **Update:** Replaced `super()` calls with `CacheMiddleware.xxx(self, ...)`.

  • middleware
  • i18n
  • cache
  • language
Read More

Redirect Multiple Domains to a Single Domain

Often, you may register more than one domain name for your website, which may have a primary domain of *mysite.com.au*: 1. mysite.com 2. my-site.com 3. mysite.net 4. mysite.co.uk For SEO and brand awareness reasons, (remember: every page should have exactly one URL) you want every visitor to end up on your primary domain, *mysite.com.au*. This middleware checks the HTTP_HOST for all incoming requests, and sends the user to http://www.mysite.com.au/ if they've managed to hit another domain.

  • middleware
  • redirect
  • domains
Read More

Logging Middleware

This is a simple Logging Middleware that uses the python logging functions. Simply drop this snippet in a file in your project such as `logmw.py` (don't try to call it `logging.py` though), then add the class to MIDDLEWARE_CLASSES in your settings file. (for instance, `'mysite.logmw.LoggingMiddleware'`) Updated 8/25/08: added PhonyLogger class that swallows log messages when logging is disabled, so code doesn't have to care if it's on or not (thanks to goodness for suggesting the idea, though I missed it before)

  • middleware
  • logging
Read More

181 snippets posted so far.