Snippet List
This is a modification of Django 1.3's transaction.commit_on_success() decorator and context manager.
It's inspired by snippet [1343](http://djangosnippets.org/snippets/1343/) which unfortunately don't work in current Django neither as a context manager.
In my junior projects it works fine but I've not tested in critical projects yet! YMMV !
How it works: it simply counts the nesting level and does the real transaction enter/exit only on first call and last call respectively (code copied from Django's commit_on_success() ).
It use thread local storage to save the per-thread nesting level count safely.
To use it just put the code in a file (i.e. nested_commit_on_success.py) and import and use it exacly as normal commit_on_success(), both as decorator (@nested_commit_success) or context manager (with nested_commit_on_success(): ).
Any feedback is welcome!
- decorator
- nested
- transaction
- contextmanager
Overriding settings
-------------------
For testing purposes it's often useful to change a setting temporarily and revert to the original value after running the testing code. The following code doubles as a context manager and decorator. It's used like this:
from django.test import TestCase
from whatever import override_settings
class LoginTestCase(TestCase):
@override_settings(LOGIN_URL='/other/login/')
def test_login(self):
response = self.client.get('/sekrit/')
self.assertRedirects(response, '/other/login/?next=/sekrit/')
The decorator can also be applied to test case classes:
from django.test import TestCase
from whatever import override_settings
class LoginTestCase(TestCase):
def test_login(self):
response = self.client.get('/sekrit/')
self.assertRedirects(response, '/other/login/?next=/sekrit/')
LoginTestCase = override_settings(LOGIN_URL='/other/login/')(LoginTestCase)
On Python 2.6 and higher you can also use the well known decorator syntax to
decorate the class:
from django.test import TestCase
from whatever import override_settings
@override_settings(LOGIN_URL='/other/login/')
class LoginTestCase(TestCase):
def test_login(self):
response = self.client.get('/sekrit/')
self.assertRedirects(response, '/other/login/?next=/sekrit/')
Alternatively it can be used as a context manager:
from django.test import TestCase
from whatever import override_settings
class LoginTestCase(TestCase):
def test_login(self):
with override_settings(LOGIN_URL='/other/login/'):
response = self.client.get('/sekrit/')
self.assertRedirects(response, '/other/login/?next=/sekrit/')
- settings
- decorator
- contextmanager
2 snippets posted so far.