source: main/waeup.sirp/trunk/src/waeup/sirp/applicants/root.py @ 6392

Last change on this file since 6392 was 6392, checked in by uli, 13 years ago

* empty log message *

File size: 5.5 KB
Line 
1##
2## root.py
3## Login : <uli@pu.smp.net>
4## Started on  Thu Jan 20 04:17:59 2011 Uli Fouquet
5## $Id$
6##
7## Copyright (C) 2011 Uli Fouquet
8## This program is free software; you can redistribute it and/or modify
9## it under the terms of the GNU General Public License as published by
10## the Free Software Foundation; either version 2 of the License, or
11## (at your option) any later version.
12##
13## This program is distributed in the hope that it will be useful,
14## but WITHOUT ANY WARRANTY; without even the implied warranty of
15## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16## GNU General Public License for more details.
17##
18## You should have received a copy of the GNU General Public License
19## along with this program; if not, write to the Free Software
20## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21##
22"""
23The root for applicants.
24"""
25import logging
26import grok
27import os
28from hurry.query import Eq
29from hurry.query.interfaces import IQuery
30from zope.component import getUtility
31from waeup.sirp.interfaces import IWAeUPSIRPPluggable
32from waeup.sirp.applicants.interfaces import IApplicantsRoot
33
34class ApplicantsRoot(grok.Container):
35    """The root of applicants-related components. It contains only
36    containers for applicants.
37    """
38    grok.implements(IApplicantsRoot)
39
40    local_roles = ['waeup.ApplicationsOfficer']
41
42    @property
43    def logger(self):
44        """Get a logger for applicants.
45        """
46        # We need a different logger for every site...
47        site = grok.getSite()
48        sitename = getattr(site, '__name__', 'app')
49        loggername = 'waeup.sirp.%s.applicants' % sitename
50        logger = logging.getLogger(loggername)
51        if not logger.handlers:
52            logger = self._setupLogger(logger)
53        return logger
54
55    def _setupLogger(self, logger):
56        """Setup applicants logger.
57        """
58        logdir = os.path.join(grok.getSite()['datacenter'].storage, 'logs')
59        if not os.path.exists(logdir):
60            os.mkdir(logdir)
61        filename = os.path.join(logdir, 'applicants.log')
62
63        # Create a rotating file handler logger for datacenter.
64        handler = logging.handlers.RotatingFileHandler(
65            filename, maxBytes=5*1024**1, backupCount=5)
66        formatter = logging.Formatter(
67            '%(asctime)s - %(levelname)s - %(message)s')
68        handler.setFormatter(formatter)
69
70        # Here we decide, whether our messages will _also_ go to
71        # application log.
72        logger.propagate = False
73        logger.setLevel(logging.DEBUG)
74        logger.addHandler(handler)
75        return logger
76
77
78class ApplicantsPlugin(grok.GlobalUtility):
79    """A WAeUPSIRPPlugin that creates an applicants root in portal.
80
81    This plugin should be called by a typical
82    `waeup.sirp.app.Universtiy` instance on creation time. The
83    :meth:`update` method normally can also be triggered manually over
84    the main site configuration.
85
86    Implements :class:`waeup.sirp.interfaces.IWAeUPSIRPPluggable`
87    """
88    grok.name('applicants')
89    grok.implements(IWAeUPSIRPPluggable)
90    log_prefix = 'ApplicantsPlugin'
91
92    def setup(self, site, name, logger):
93        """Create a new :class:`ApplicantsRoot` instance in `site`.
94        """
95        site['applicants'] = ApplicantsRoot()
96        logger.info(
97            '%s: Installed applicants root.' % (self.log_prefix,)
98            )
99        return
100
101    def update(self, site, name, logger):
102        """Update site wide ``applicants`` root.
103
104        If the site already contains a suitable ``applicants`` root,
105        leave it that way. If not create one and delete the old one if
106        appropriate.
107        """
108        app_folder = site.get('applicants', None)
109        site_name = getattr(site, '__name__', '<Unnamed Site>')
110        if IApplicantsRoot.providedBy(app_folder):
111            # Applicants up to date. Return.
112            logger.info(
113                '%s: Updating site at %s: Nothing to do.' % (
114                    self.log_prefix, site_name,)
115                )
116            return
117        elif app_folder is not None:
118            # Applicants need update. Remove old instance.
119            logger.warn(
120                '%s: Outdated applicants folder detected at site %s.'
121                'Removing it.' % (self.log_prefix, site_name)
122                    )
123            del site['applicants']
124        # Add new applicants.
125        logger.info(
126            '%s: Updating site at %s. Installing '
127            'applicants.' % (self.log_prefix, site_name,)
128            )
129        self.setup(site, name, logger)
130        return
131
132def get_applicant_data(identifier):
133    """Get applicant data associated with `identifier`.
134
135    Returns the applicant object if successful and ``None`` else.
136
137    As `identifier` we expect an access code in format
138    like ``PREFIX-XXX-YYYYYYYY`` where ``PREFIX`` is something like
139    ``APP`` or ``PUDE``, ``XXX`` the access code series and
140    ``YYYYYYYYYY`` the real accesscode number.
141
142    This function requires a fully blown setup as it does catalog
143    lookups for finding applicants.
144    """
145    query = getUtility(IQuery)
146    results = list(query.searchResults(
147            Eq(('applicants_catalog', 'access_code'), identifier)
148            ))
149    if len(results) == 0:
150        return None
151    return results[0]
152
153def application_exists(identifier):
154    """Check whether an application for the given identifier already
155       exists.
156
157       `identifier` will normally be an access code.
158    """
159    applicant = get_applicant_data(identifier)
160    if applicant is None:
161        return False
162    return True
Note: See TracBrowser for help on using the repository browser.