Merge lp:~ronnie.vd.c/loco-team-portal/611304 into lp:loco-team-portal

Proposed by Ronnie
Status: Merged
Approved by: Michael Hall
Approved revision: 352
Merged at revision: 352
Proposed branch: lp:~ronnie.vd.c/loco-team-portal/611304
Merge into: lp:loco-team-portal
Diff against target: 159 lines (+131/-13)
2 files modified
loco_directory/teams/management/commands/import-live-data.py (+116/-0)
loco_directory/venues/models.py (+15/-13)
To merge this branch: bzr merge lp:~ronnie.vd.c/loco-team-portal/611304
Reviewer Review Type Date Requested Status
Chris Johnston Approve
Review via email: mp+44267@code.launchpad.net

Description of the change

Importing data from the Live (loco.ubuntu.com) server and put it in the local database

To post a comment you must log in.
350. By Ronnie

Using the same id as the server, and solved Venue.save()

351. By Ronnie

Fixed super user collision and missing super user

Revision history for this message
Chris Johnston (cjohnston) wrote :

Looks good to me. Would like a second opinion before merging though please.

review: Approve
Revision history for this message
Michael Hall (mhall119) wrote :

Getting attendees ...
Traceback (most recent call last):
  File "./manage.py", line 11, in <module>
    execute_manager(settings)
  File "/home/mhall/projects/Ubuntu/locodir/loco-directory/loco_directory/django/core/management/__init__.py", line 362, in execute_manager
    utility.execute()
  File "/home/mhall/projects/Ubuntu/locodir/loco-directory/loco_directory/django/core/management/__init__.py", line 303, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/mhall/projects/Ubuntu/locodir/loco-directory/loco_directory/django/core/management/base.py", line 195, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/home/mhall/projects/Ubuntu/locodir/loco-directory/loco_directory/django/core/management/base.py", line 222, in execute
    output = self.handle(*args, **options)
  File "/home/mhall/projects/Ubuntu/locodir/loco-directory/loco_directory/django/core/management/base.py", line 351, in handle
    return self.handle_noargs(**options)
  File "/home/mhall/projects/Ubuntu/locodir/loco-directory/loco_directory/teams/management/commands/import-live-data.py", line 110, in handle_noargs
    del old_su['_state']
KeyError: '_state'

Revision history for this message
Ronnie (ronnie.vd.c) wrote :

it could be that not every user has a '_state' key. I included a check for the key, before deleting it.

It should work now

352. By Ronnie

added check for key '_state' in user object

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== added file 'loco_directory/teams/management/commands/import-live-data.py'
2--- loco_directory/teams/management/commands/import-live-data.py 1970-01-01 00:00:00 +0000
3+++ loco_directory/teams/management/commands/import-live-data.py 2010-12-30 13:28:10 +0000
4@@ -0,0 +1,116 @@
5+#!/usr/bin/python
6+
7+from django.core.management.base import NoArgsCommand
8+from django.contrib.auth.models import User, Group
9+from events.models import GlobalEvent, TeamEvent, TeamEventComment, Attendee
10+from teams.models import Language, Continent, Country, Team
11+from venues.models import Venue
12+from userprofiles.models import UserProfile
13+
14+import sys
15+import urllib2
16+import json
17+import datetime
18+import re
19+
20+ORDER = [('languages', Language),
21+ ('continents', Continent),
22+ ('countries', Country),
23+ ('venues', Venue),
24+ ('global', GlobalEvent),
25+ ('groups', Group),
26+ ('users', User),
27+ ('profiles', UserProfile),
28+ ('teams', Team),
29+ ('events', TeamEvent),
30+ ('comments', TeamEventComment),
31+ ('attendees', Attendee),]
32+
33+
34+class Command(NoArgsCommand):
35+ help = "Copy the live data to the local instance"
36+
37+ def handle_noargs(self, **options):
38+ # Save the super user, so it can be restored later
39+ super_user = None
40+ try:
41+ super_user = User.objects.get(pk=1)
42+ except:
43+ pass
44+
45+ # Delete all old data, so the id's do not conflict when linking
46+ print 'Removing local data from database...'
47+ for service, Model in ORDER:
48+ Model.objects.all().delete()
49+
50+ services_url = 'http://loco.ubuntu.com/services/'
51+ date_pattern1 = re.compile('^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$')
52+ date_pattern2 = re.compile('^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}.\d+$')
53+
54+ for service, Model in ORDER:
55+ # Get the json data from the server
56+ print 'Getting', service, '...'
57+ json_data = urllib2.urlopen(services_url+service).read()
58+
59+ # Find out what fields are normal, and which many_to_many
60+ local_fields = Model._meta.fields
61+ many_to_many = Model._meta.many_to_many
62+
63+ for entry in json.loads(json_data):
64+ # Create the model without the many_to_many fields
65+ params = {}
66+ for field in local_fields:
67+ if entry.has_key(field.name):
68+ field_value = entry[field.name]
69+ if field_value == None:
70+ if field.null == True:
71+ # If field on the server is None, but None is not allowed, get the default value
72+ field_value = field.get_default()
73+ else:
74+ # If the field is a related, grab the object with that id
75+ if field.rel:
76+ rel_model = field.rel.to
77+ try:
78+ params[field.name] = rel_model.objects.get(pk=field_value)
79+ except rel_model.DoesNotExist:
80+ print '%(model)s with pk=%(pk)s does not exists' % ({'model':rel_model._meta.object_name, 'pk':field_value})
81+ # Else if it is a date, create a date object
82+ elif isinstance(field_value, unicode) and date_pattern1.match(field_value):
83+ params[field.name] = datetime.datetime.strptime(field_value, '%Y-%m-%d %H:%M:%S')
84+ elif isinstance(field_value, unicode) and date_pattern2.match(field_value):
85+ params[field.name] = datetime.datetime.strptime(field_value, '%Y-%m-%d %H:%M:%S.%f')
86+ # Else: copy the info
87+ else:
88+ params[field.name] = field_value
89+
90+ model_instance = Model(**params)
91+ model_instance.save()
92+
93+ # Add the related object to the model
94+ for field in many_to_many:
95+ if entry.has_key(field.name):
96+ for object_id in entry[field.name]:
97+ many_related_manager = getattr(model_instance, field.name)
98+ rel_model = many_related_manager.model
99+ try:
100+ related_object = rel_model.objects.get(pk=object_id)
101+ except rel_model.DoesNotExist:
102+ print '%(model)s with pk=%(pk)s does not exists' % ({'model':rel_model, 'pk':object_id})
103+ else:
104+ many_related_manager.add(related_object)
105+
106+ # Save the model to the database, if changed by many to many fields
107+ if many_to_many:
108+ model_instance.save()
109+
110+ # Restore the super user
111+ if super_user:
112+ old_su = super_user.__dict__
113+ del old_su['id']
114+ if old_su.__contains__('_state'):
115+ del old_su['_state']
116+ new_su, created = User.objects.get_or_create(username=old_su['username'])
117+ new_su.__dict__.update(old_su)
118+ new_su.save()
119+
120+
121
122=== modified file 'loco_directory/venues/models.py'
123--- loco_directory/venues/models.py 2010-11-27 03:36:17 +0000
124+++ loco_directory/venues/models.py 2010-12-30 13:28:10 +0000
125@@ -64,19 +64,21 @@
126 def save(self, *args, **kargs):
127 if self.id:
128 from events.models import TeamEvent
129- old = Venue.objects.get(id=self.id)
130- retval = super(Venue, self).save(*args, **kargs)
131- if old.tz != self.tz:
132- events = TeamEvent.objects.filter(venue=self)
133- for e in events:
134- old_offset = old.tolocaltime(e.date_begin).utcoffset()
135- new_offset = self.tolocaltime(e.date_begin).utcoffset()
136- e.date_begin = e.date_begin + (old_offset - new_offset)
137- e.date_end = e.date_end + (old_offset - new_offset)
138- e.save()
139- else:
140- retval = super(Venue, self).save(*args, **kargs)
141- return retval
142+ try:
143+ old = Venue.objects.get(id=self.id)
144+ except Venue.DoesNotExist:
145+ # Object is new, but has a fixed id'
146+ pass
147+ else:
148+ if old.tz != self.tz:
149+ events = TeamEvent.objects.filter(venue=self)
150+ for e in events:
151+ old_offset = old.tolocaltime(e.date_begin).utcoffset()
152+ new_offset = self.tolocaltime(e.date_begin).utcoffset()
153+ e.date_begin = e.date_begin + (old_offset - new_offset)
154+ e.date_end = e.date_end + (old_offset - new_offset)
155+ e.save()
156+ return super(Venue, self).save(*args, **kargs)
157
158 def venues_without_country():
159 return Venue.objects.filter(country__isnull=True)

Subscribers

People subscribed via source and target branches