Snippet List
A decorator that restricts the tags and filters available to template loading and parsing within a function.
This is mainly meant to be used when granting users the power of the DTL. You obviously don't want users to be able to do things that could be potentially malicious.
The {% ssi %} tag, for example, could be used to display sensitive data if improperly configured.
{% load %} gives them access to all the unlimited python code you wrote in your templatetags. {% load sudo %}{% sudo rm -rf / %} o_0
Note that the "load" tag (among others) is not listed in the default tag whitelist. If you parse a template (however indirectly) in a function decorated with this, unlisted builtin tags will behave like undefined tags (ie, they will result in a TemplateSyntaxError).
Since {% load %} is not whitelisted, you may want to include some custom tags or filters as "builtins" for convenience. Simply put the module paths to the libraries to include in the `extra` kwarg or the `extra_libraries` list. Generally, this is not recommended, as these libraries need to be carefully and defensively programmed.
**NOTE**: This **does not** do anything about cleaning your rendering context! That's completely up to you! This merely restricts what tags and filters are allowed in the templates.
Examples:
from django.template.loader import get_template
safe_get_template = use_safe_templates(get_template)
tmpl = safe_get_template('myapp/some_template.html')
from django.template import Template
use_safe_templates(Template)('{% load sudo %}')
# TemplateSyntaxError: Invalid block tag 'load'
- template
- clean
- safe
- restrict
An HttpResponse for giving the user a file download, taking advantage of X-Sendfile if it's available, using FileWrapper if not.
Usage:
HttpResponseSendfile('/path/to/file.ext')
To bypass the fallback:
HttpResponseSendfile('/path/to/file.ext', fallback=False)
This has been tested working with Lighttpd 1.4.28's mod_fastcgi.
- download
- sendfile
- x-sendfile
The django admin (as of 1.3) doesn't allow for short_description (and other ModelAdmin function attributes) to be a callable. Until that happens, this handy snippet allows you to return dynamic descriptions.
Note, I haven't actually tested this yet -- but I plan to when I have the free time.
**NOTE: This is modified from 1.0's test runner and has only been tested on Django 1.0 + Python 2.5**
This is a test runner that searches inside any app-level "tests" packages for django unit tests. Modules to be searched must have names that start with "test_" (this can be changed by modifying `get_multi_tests()`, [`mod.startswith('test_') and mod.endswith('.py')`]).
It also allows for arbitrarily nested test packages, with no restrictions on naming, so you could have:
myapp/
+- tests/
+- __init__.py
+- test_set1.py
+- category1/
+- __init__.py
+- test_something.py
+- subcat/
+- __init__.py
+- test_foobar.py
+- category2/
+- __init__.py
+- test_other.py
and "manage.py test myapp" would pick up tests in all four test_*.py test modules.
Searching the modules in this way, instead of importing them all into the top-level `__init__.py`, allows you to have "name collisions" with TestCase names -- two modules can each have a TestFooBar class, and they will both be run. Unfortunately, this snippet doesn't allow you to specify a full path to a specific test case or test module ("manage.py test myapp.category1.test_something" and "manage.py test myapp.test_set1.TestFooBar" won't work); using "manage.py test myapp.TestFooBar" will search out all test cases named "TestFooBar" and run them. "manage.py test myapp.TestFooBar.test_baz" will work similarly, returning the test_baz method of each TestFooBar class.
To use, put this code in "`testrunner.py`" in your project, and add `TEST_RUNNER = 'myproject.testrunner.run_tests'` to your `settings.py`.
- tests
- test-runner
- package
More a proof of concept than anything, this mixin addresses a perceived "shortcoming" of django forms: the inability to interact with the current request, and specifically the "current user".
Usage:
class SomeForm(forms.Form, RequestFetchingMixin):
# fields...
def __init__(self, *args, **kwargs):
if self.request:
# interact with self.request?
super(SomeForm, self).__init__(*args, **kwargs)
if self.request:
# more interaction
def clean(self):
if self.request:
# blah blah self.request.user blah
Notes:
* This reaches "into the past" to pull an existing HttpRequest object, regardless of what name it was bound to, into "the present".
* If multiple requests are found (what on earth are you doing??), the one bound to "request" (or the first one found, if that's not available) will be used.
* By default it goes up to 5 frames back before giving up, but that can obviously be changed if you think you need it.
* This won't work everywhere. self.request is guaranteed to be present, but may be None.
* Just because you have a self.request doesn't mean self.request.user will be a valid user. This is subject to all the rules that a regular view's request is subject to (because it *is* a regular view's request!)
* This isn't magic; it's just python.
- forms
- request
- mixin
- request.user
A quick-and-dirty, and extremely simple, decorator to turn a simple function into a management command.
This still requires you to have the management directory structure, but allows you to name your primary method whatever you want, and encapsulates the basic functionality of an argument-accepting management commmand.
The function's docstring will be used for the command's help text if the `help` arg is not passed to the decorator.
Simple usage:
from myapp.utils import command
@command()
def my_command():
print "Hello, world"
I'm not too familiar with the intricacies of decorators and management commands, so this could probably (most likely) be improved upon, but it's a start.
**Update**:
I've taken this a bit farther and put my work up on bitbucket: https://bitbucket.org/eternicode/django-management-decorators/src
- decorator
- management
- command
eternicode has posted 6 snippets.