source: waeup_product/trunk/exportimport.py @ 238

Last change on this file since 238 was 238, checked in by joachim, 18 years ago

=import csv

File size: 11.6 KB
Line 
1#-*- mode: python; mode: fold -*-
2# $Id: exportimport.py 31640 2006-01-15 19:22:29Z ogrisel $
3"""WAeUP Tool XML Adapter.
4
5An XML adapter tells the GenericSetup machinery howto im- / export persistent
6configuration that is relative to a specific CMF component such as our WAeUP
7Tool.
8
9GenericSetup uses the Zope3 interfaces and components machinery to find the
10right XML adapter for the right object. This is why we flagged our waeup tool
11with the `implements(IWAeUPTool)` class attribute and made an adapter
12association in the `configure.zcml` file.
13"""
14import csv,re
15
16# Zope3 component architecture
17from zope.component import adapts
18from zope.interface import implements
19
20# Standard GenericSetup base classes and functions
21from Products.GenericSetup.utils import exportObjects
22from Products.GenericSetup.utils import importObjects
23from Products.GenericSetup.utils import XMLAdapterBase
24from Products.GenericSetup.utils import PropertyManagerHelpers
25
26from Products.CMFCore.utils import getToolByName
27
28# GenericSetup multi adapts a class that implement IWAeUP and a particular
29# ISetupEnvironment to and IBody (piece of XML configuration).
30from Products.GenericSetup.interfaces import IBody
31from Products.GenericSetup.interfaces import ISetupEnviron
32from Products.WAeUP.interfaces import IWAeUPTool
33import Globals
34p_home = Globals.package_home(globals())
35i_home = Globals.INSTANCE_HOME
36
37TOOL = 'portal_waeup'
38NAME = 'waeup'
39
40# The exportWAeUP and importWAeUP methods are called by the specific
41# im- / export steps defined in the corresponding XML files in the
42# WAeUP/profiles/default/ directory.
43
44def installFaculties( academics): ###(
45    """install Universityspecific Faculies with Departments"""
46    faculties = [ ###(
47                  {'id': 'agriculture', ###(
48                      'Title': 'Agriculture',
49                      'departments': [
50##                                     { 'id': 'dep1', ###(
51##                                       'Title': 'One',
52##                                     },
53                                     ],
54                      },###)
55                  ###)
56                  {'id': 'arts', ###(
57                      'Title': 'Arts',
58                      'departments': [
59##                                     { 'id': 'dep1', ###(
60##                                       'Title': 'One',
61##                                     },
62                                     ],
63                      },###)
64                  ###)
65                  {'id': 'BasicMedicalSciences', ###(
66                      'Title': 'Basic Medical Sciences',
67                      'departments': [
68##                                     { 'id': 'dep1', ###(
69##                                       'Title': 'One',
70##                                     },
71                                     ],
72                      },###)
73                  ###)
74                  {'id': 'science', ###(
75                  'Title': 'Science',
76                  'departments': [
77                                 { 'id': 'bio', ###(
78                                   'Title': 'Biochemistry',
79                                 },
80                                 { 'id': 'bot',
81                                   'Title': 'Botany',
82                                 },
83                                 { 'id': 'che',
84                                   'Title': 'Chemistry',
85                                 },
86                                 { 'id': 'com',
87                                   'Title': 'Computer Science',
88                                 },
89                                 { 'id': 'geo',
90                                   'Title': 'Geologie',
91                                 },
92                                 { 'id': 'mat',
93                                   'Title': 'Mathematics',
94                                 },
95                                 { 'id': 'mic',
96                                   'Title': 'Microbiology',
97                                 },
98                                 { 'id': 'opt',
99                                   'Title': 'Optometry',
100                                 },
101                                 { 'id': 'phy',
102                                   'Title': 'Physics',
103                                 },
104                                 { 'id': 'zoo',
105                                   'Title': 'Zoology',
106                                 },
107                                 ],
108                  },###)
109                 ]###)
110                 
111                ###)
112
113    for faculty in faculties:
114        fid = faculty['id']
115        f = getattr(academics,fid,None)
116        if f is None:
117            #self.log('Creating Faculty %(id)s = %(Title)s' % faculty)
118            academics.invokeFactory('Faculty', fid)
119            f = getattr(academics,fid)
120            f.getContent().edit(mapping=faculty)
121        for department in faculty['departments']:
122            #self.log('Checking Department %(id)s = %(Title)s' % department)
123            did = department['id']
124            d = getattr(f,did,None)
125            if d is None:
126                #self.log('Creating Department %(id)s = %(Title)s' % department)
127                f.invokeFactory('Department', did)
128                d = getattr(f,did)
129                d.getContent().edit(mapping=department)
130###)
131
132def loadFacultiesFromCSV(academics,site,context): ###(
133    """install Universityspecific Faculies from CSV values"""
134    logger = context.getLogger('loadfaculties')
135    faculties = csv.DictReader(open("%s/import/faculty.csv" % i_home,"rb"))
136    for faculty in faculties:
137        fid = faculty['FacultyKey']
138        f = getattr(academics,fid,None)
139        if f is None:
140            #self.log('Creating Faculty %(id)s = %(Title)s' % faculty)
141            logger.info('Creating Faculty %(FacultyKey)s = %(Description)s' % faculty)
142            academics.invokeFactory('Faculty', fid)
143            f = getattr(academics,fid)
144            d = {'Title': faculty['Description']}
145            f.getContent().edit(mapping=d)
146###)
147
148def loadDepartmentsFromCSV(academics,site,context): ###(
149    """install Universityspecific Faculies from CSV values"""
150    logger = context.getLogger('loaddepartments')
151    deps = csv.DictReader(open("%s/import/departments.csv" % i_home,"rb"))
152    for dep in deps:
153        fid = dep['FacultyCode']
154        f = getattr(academics,fid,None)
155        if f is None:
156            logger.info( "No Faculty with ID: %s" % fid)
157        else:
158            did = dep.get('DeptCode')
159            d = getattr(f,did,None)
160            if d is None:
161                #self.log('Creating Department %(DeptCode)s = %(Description)s' % dep)
162                logger.info('Creating Department %(DeptCode)s = %(Description)s' % dep)
163                f.invokeFactory('Department', did)
164                d = getattr(f,did)
165                dict = {'Title': dep['Description']}
166                d.getContent().edit(mapping=dict)
167###)
168
169def loadCoursesFromCSV(academics,site,context): ###(
170    """install Universityspecific Faculies from CSV values"""
171    logger = context.getLogger('loadcourses')
172    courses = csv.DictReader(open("%s/import/courses.csv" % i_home,"rb"))
173    for course in courses:
174        if course.get("FORMERCODE") != '':
175            continue
176        depid = course['Dept']
177        res = site.portal_catalog({'meta_type': "Department",
178                                      'id': depid})
179        if not res:
180            continue
181        dept=res[0].getObject()
182        course_id = ''.join(re.split('\W+',course.get('CourseCode')))
183        if len(course_id) != 6:
184            logger.info("invalid course_code %(CourseCode)s" % course)
185            #print course_id,course.get('CourseCode'),course.get('Description')
186            continue
187        c = getattr(dept,course_id,None)
188        if c is None:
189            #self.log('Creating Department %(DeptCode)s = %(Description)s' % dep)
190            logger.info('Creating Course %(CourseCode)s  %(Description)s in Department %(Dept)s' % course)
191            dept.invokeFactory('Course', course_id)
192            c = getattr(dept,course_id)
193        dict = {'Title': course['Description']}
194        dict['code'] = course_id
195        dict['credit'] = course.get('Credits')
196        #dict['level'] = course.get('CourseCode').split()[1][0]
197        dict['level'] = "%c00" % course_id[3]
198        dict['semester'] = "%(Semester)s" % course
199        dict['passmark'] = course.get('PassMark')
200        c.getContent().edit(mapping=dict)
201###)
202
203def setupStructure(site,context): ###(
204    sections = getattr(site,'sections')
205    portal = getattr(sections,'uniportal',None)
206    if portal is None:
207        sections.invokeFactory('University','uniportal')
208        portal = getattr(site,'uniportal',None)
209        portal.getContent().edit(mapping={'Title':SRPP_TITLE})
210    students =  getattr(portal,'students',None)
211    if students is None:
212        portal.invokeFactory('StudentsFolder','students')
213        students = getattr(portal,'students').getContent()
214        students.edit(mapping={'Title':'Students'})
215    academics = getattr(portal,'academics',None)
216    if academics is None:
217        portal.invokeFactory('AcademicsFolder','academics')
218        academics = getattr(portal,'academics')
219        academics.getContent().edit(mapping={'Title':'Academics'})
220    loadFacultiesFromCSV(academics,site,context)
221    loadDepartmentsFromCSV(academics,site,context)
222    loadCoursesFromCSV(academics,site,context)
223    studycourses = getattr(academics,'studycourses',None)
224    if studycourses is None:
225        academics.invokeFactory('SCFolder','studycourses')
226        studycourses = getattr(academics,'studycourses')
227        studycourses.getContent().edit(mapping={'Title':'Studycourses'})
228    installFaculties(academics)
229    if not hasattr(portal,'accommodation'):
230        portal.invokeFactory('AccoFolder','accommodation')
231        accommodation = getattr(portal,'accommodation').getContent()
232        accommodation.edit(mapping={'Title':'Accommodation'})
233###)
234
235
236def exportWAeUP(context):
237    """Export our WAeUP tool configuration
238    """
239    site = context.getSite()
240    tool = getToolByName(site, TOOL, None)
241    if tool is None:
242        logger = context.getLogger(NAME)
243        logger.info("Nothing to export.")
244        return
245    exportObjects(tool, '', context)
246
247def importWAeUP(context):
248    """Import WAeUP tool configuration
249    """
250    site = context.getSite()
251    setupStructure(site,context)
252    #import pdb; pdb.set_trace()
253    print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>p_home: ",p_home,i_home
254    pass
255    #site = context.getSite()
256    #tool = getToolByName(site, TOOL)
257    #importObjects(tool, '', context)
258
259
260# This the XMLAdapter itself. It encodes the im- / export logic that is specific
261# to our tool. `im- / exportObjects` functions will find it thanks to the zope
262# components machinery and the associations made in the configure.zcml file.
263
264class WAeUPXMLAdapter(XMLAdapterBase, PropertyManagerHelpers):
265    """XML importer and exporter for the WAeUP tool.
266
267    Hence this XMLAdapter is really simple. To get more complete examples of
268    what XMLAdapters are meant to do, please have a look at the
269    CPSSkins.exportimport.py or CPSDirectory.exportimport.py files, for
270    instance.
271    """
272
273    adapts(IWAeUPTool, ISetupEnviron)
274    implements(IBody)
275
276    _LOGGER_ID = NAME
277    name = NAME
278
279    def _exportNode(self):
280        """Export the object as a DOM node.
281        """
282        node = self._getObjectNode('object')
283        node.appendChild(self._extractProperties())
284        self._logger.info("WAeUP tool exported.")
285        return node
286
287    def _importNode(self, node):
288        """Import the object from the DOM node.
289        """
290        if self.environ.shouldPurge():
291            self._purgeProperties()
292        self._initProperties(node)
293        self._logger.info("WAeUP tool imported.")
294
Note: See TracBrowser for help on using the repository browser.