Skip to content

Commit

Permalink
Fixed #11 -- Support Django 1.6's ATOMIC_REQUESTS
Browse files Browse the repository at this point in the history
In Django 1.6 `TransactionMiddleware` was deprecated in favor of
`ATOMIC_REQUESTS`. With this setting activated, all views will be
wrapped in `transaction.atomic`. However the `SessionStore` was
saving sessions within a `transaction.commit_on_success`
wrapper. Mixing old-style and new-style is not supported in all
scenarios, so this resulted in an error.
  • Loading branch information
Bouke committed May 15, 2014
1 parent 0a527a7 commit 92e886f
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 3 deletions.
1 change: 1 addition & 0 deletions example/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'ATOMIC_REQUESTS': True,
}
}

Expand Down
1 change: 1 addition & 0 deletions tests/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'ATOMIC_REQUESTS': True,
}
}

Expand Down
11 changes: 8 additions & 3 deletions user_sessions/backends/db.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import logging
from django.contrib import auth

import django
from django.contrib import auth
from django.contrib.sessions.backends.base import SessionBase, CreateError
from django.core.exceptions import SuspiciousOperation
from django.db import IntegrityError, transaction, router
Expand Down Expand Up @@ -74,8 +75,12 @@ def save(self, must_create=False):
)
using = router.db_for_write(Session, instance=obj)
try:
with transaction.commit_on_success(using):
obj.save(force_insert=must_create, using=using)
if django.VERSION >= (1, 6):
with transaction.atomic(using):
obj.save(force_insert=must_create, using=using)
else:
with transaction.commit_on_success(using):
obj.save(force_insert=must_create, using=using)
except IntegrityError as e:
if must_create and 'session_key' in str(e):
raise CreateError
Expand Down

0 comments on commit 92e886f

Please sign in to comment.