Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Command for migrating existing sessions to the new session store #33

Merged
merged 5 commits into from
Nov 25, 2017
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,5 @@

/docs/_build/
/GeoLite2-City.mmdb
.idea/
*.pyc
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need for adding these ignores, I prefer to have these in my global gitignore.

25 changes: 24 additions & 1 deletion tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from django.contrib.sessions.backends.base import CreateError
from django.core.management import call_command
from django.test import TestCase
from django.test.utils import override_settings
from django.test.utils import override_settings, modify_settings
from django.utils.timezone import now

from user_sessions.backends.db import SessionStore
Expand Down Expand Up @@ -454,3 +454,26 @@ def test_can_call(self):
ip='127.0.0.1')
call_command('clearsessions')
self.assertEqual(Session.objects.count(), 0)


class MigratesessionsCommandTest(TestCase):
@modify_settings(INSTALLED_APPS={'append': 'django.contrib.sessions'})
def test_migrate_from_login(self):
from django.contrib.sessions.models import Session as DjangoSession
from django.contrib.sessions.backends.db import SessionStore as DjangoSessionStore
try:
call_command('migrate', 'sessions')
call_command('clearsessions')
user = User.objects.create_user('bouke', '', 'secret')
session = DjangoSessionStore()
session['_auth_user_id'] = user.id
session.save()
self.assertEqual(Session.objects.count(), 0)
self.assertEqual(DjangoSession.objects.count(), 1)
call_command('migratesessions')
new_sessions = list(Session.objects.all())
self.assertEqual(len(new_sessions), 1)
self.assertEqual(new_sessions[0].user, user)
self.assertEqual(new_sessions[0].ip, '127.0.0.1')
finally:
call_command('migrate', 'sessions', 'zero')
49 changes: 49 additions & 0 deletions user_sessions/management/commands/migratesessions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# -*- coding: UTF-8 -*-
from django.core.management.base import BaseCommand
from user_sessions.models import Session as UserSession
from django.contrib.auth import get_user_model
import logging
import importlib

logger = logging.getLogger(__name__)


def get_model_class(full_model_name):
old_model_package, old_model_class_name = full_model_name.rsplit('.', 1)
package = importlib.import_module(old_model_package)
return getattr(package, old_model_class_name)


class Command(BaseCommand):
"""
Convert existing (old) sessions to the new session store.
"""
def add_arguments(self, parser):
parser.add_argument(
'--oldmodel',
dest='oldmodel',
default='django.contrib.sessions.models.Session',
help='Existing session model to migrate to the new UserSessions database table'
)

def handle(self, *args, **options):
User = get_user_model()
old_sessions = get_model_class(options['oldmodel']).objects.all()
logger.info("Processing %d session objects" % old_sessions.count())
conversion_count = 0
for old_session in old_sessions:
if not UserSession.objects.filter(session_key=old_session.session_key).exists():
data = old_session.get_decoded()
user = None
if '_auth_user_id' in data:
user = User.objects.filter(pk=data['_auth_user_id']).first()
UserSession.objects.create(
session_key=old_session.session_key,
session_data=old_session.session_data,
expire_date=old_session.expire_date,
user=user,
ip='127.0.0.1'
)
conversion_count += 1

logger.info("Created %d new session objects" % conversion_count)
4 changes: 2 additions & 2 deletions user_sessions/templatetags/user_sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
# Django 1.9 and above
from django.contrib.gis.geoip2 import HAS_GEOIP2
HAS_GEOIP = False
except:
except ImportError:
# Django 1.8
from django.contrib.gis.geoip import HAS_GEOIP
HAS_GEOIP2 = False
Expand Down Expand Up @@ -98,7 +98,7 @@ def location(value):
"""
try:
location = geoip() and geoip().city(value)
except:
except Exception as e:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This variable isn't used, no need to assign it.

try:
location = geoip() and geoip().country(value)
except Exception as e:
Expand Down