source: main/waeup.sirp/trunk/src/waeup/sirp/app.py @ 6174

Last change on this file since 6174 was 6138, checked in by uli, 14 years ago

Make a possibility to update/create catalogs in a running site.

  • Property svn:eol-style set to native
File size: 5.3 KB
Line 
1import grok
2import logging
3import os
4try:
5    from zope.authentication.interfaces import IAuthentication
6except:
7    # BBB
8    from zope.app.security.interfaces import IAuthentication
9from zope.component import createObject, getUtilitiesFor
10from zope.component.interfaces import ObjectEvent
11try:
12    from zope.pluggableauth import PluggableAuthentication
13except ImportError:
14    # BBB
15    from zope.app.authentication.authentication import PluggableAuthentication
16
17from waeup.sirp.authentication import setup_authentication
18from waeup.sirp.datacenter import DataCenter
19from waeup.sirp.interfaces import (
20    IUniversity, IDataCenter, IWAeUPSIRPPluggable,
21    IDataCenterStorageMovedEvent, IObjectUpgradeEvent, )
22from waeup.sirp.users import UserContainer
23
24class University(grok.Application, grok.Container):
25    """A university.
26    """
27    grok.implements(IUniversity)
28
29    # Setup authentication for this app. Note: this is only
30    # initialized, when a new instance of this app is created.
31    grok.local_utility(
32        PluggableAuthentication, provides = IAuthentication,
33        setup = setup_authentication,)
34
35    # The name of the university.
36    name=u'Sample University'
37
38    # The default layout.
39    skin=u'gray waeup theme'
40
41    # The default frontpage.
42    frontpage= """
43This is the default frontpage of the portal written
44in `reStructuredText (reST)
45<http://docutils.sourceforge.net/docs/user/rst/quickref.html>`_
46markup language.
47
48Some more reST examples for getting started:
49
501. Heading
51----------
52
53Text
54
551.2 Heading
56...........
57
58Text
59
602. Heading
61----------
62
63Text
64
652.1 Heading
66...........
67
68Text
69
702.2 Heading
71...........
72
73Text
74
75"""
76
77    # The default title.
78    title=u'Welcome to the Student Information and Registration Portal of %s' % name
79
80    @property
81    def logger(self):
82        """The application logger.
83
84        Returns a standard logger object as provided by :mod:`logging`
85        module from the standard library.
86
87        Other components can use this logger to perform log entries
88        into the 'main' logfile.
89
90        The logger is initialized the first time, it is called.
91        """
92        sitename = self.__name__
93        loggername = 'waeup.sirp.%s' % sitename
94        logger = logging.getLogger(loggername)
95        if not logger.handlers:
96            logger = self._setupLogger(logger)
97        return logger
98
99
100    def __init__(self, name=name, skin=skin, title=title,
101                 frontpage=frontpage, **kw):
102        super(University, self).__init__(**kw)
103        self.name = name
104        self.skin = skin
105        self.title = title
106        self.frontpage = frontpage
107        self.setup()
108
109    def setup(self):
110        """Setup some hard-wired components.
111
112        Create local datacenter, containers for users, students and
113        the like.
114        """
115        self['users'] = UserContainer()
116        self['datacenter'] = DataCenter()
117
118        self['students'] = createObject(u'waeup.StudentContainer')
119        self['hostels'] = createObject(u'waeup.HostelContainer')
120        self._createPlugins()
121
122    def _createPlugins(self):
123        """Create instances of all plugins defined somewhere.
124        """
125        for name, plugin in getUtilitiesFor(IWAeUPSIRPPluggable):
126            plugin.setup(self, name, self.logger)
127        return
128
129    def updatePlugins(self):
130        """Lookup all plugins and call their `update()` method.
131        """
132        name = getattr(self, '__name__', '<Unnamed>')
133        self.logger.info('Fire upgrade event for site %s' % name)
134        grok.notify(ObjectUpgradeEvent(self))
135        self.logger.info('Done.')
136        self.logger.info('Now upgrading any plugins.')
137        for name, plugin in getUtilitiesFor(IWAeUPSIRPPluggable):
138            plugin.update(self, name, self.logger)
139        self.logger.info('Plugin update finished.')
140        return
141
142    def _setupLogger(self, logger):
143        """Setup general application logger.
144
145        The logfile will be stored in the datacenter logs/ dir.
146        """
147        logdir = os.path.join(self['datacenter'].storage, 'logs')
148        if not os.path.exists(logdir):
149            os.mkdir(logdir)
150        filename = os.path.join(logdir, 'application.log')
151
152        # Create a rotating file handler logger for application.
153        handler = logging.handlers.RotatingFileHandler(
154            filename, maxBytes=5*1024**1, backupCount=7)
155        formatter = logging.Formatter(
156            '%(asctime)s - %(levelname)s - %(message)s')
157        handler.setFormatter(formatter)
158
159        # Don't send log msgs to ancestors. This stops displaying
160        # logmessages on the commandline.
161        logger.propagate = False
162        logger.addHandler(handler)
163        return logger
164
165@grok.subscribe(IDataCenter, IDataCenterStorageMovedEvent)
166def handle_storage_move(obj, event):
167    """Event handler, in case datacenter storage moves.
168
169    We initialize the application log again, then.
170    """
171    app = grok.getSite()
172    if app is None:
173        return
174    if obj is not app['datacenter']:
175        return
176    logger = app.logger
177    logger.warn('Log Dir moved. Closing.')
178    handlers = logger.handlers
179    for handler in handlers:
180        logger.removeHandler(handler)
181    app._setupLogger(logger)
182    logger.warn('Log file moved. Opening.')
183
184class ObjectUpgradeEvent(ObjectEvent):
185    """An event fired, when datacenter storage moves.
186    """
187    grok.implements(IObjectUpgradeEvent)
Note: See TracBrowser for help on using the repository browser.