source: main/waeup.sirp/branches/ulif-schoolgrades/src/waeup/sirp/interfaces.py @ 7772

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

Move grade and subject sources to central interfaces. They are needed in several submodules.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 28.3 KB
RevLine 
[7193]1## $Id: interfaces.py 7772 2012-03-07 09:06:12Z uli $
[3521]2##
[7193]3## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann
4## This program is free software; you can redistribute it and/or modify
5## it under the terms of the GNU General Public License as published by
6## the Free Software Foundation; either version 2 of the License, or
7## (at your option) any later version.
8##
9## This program is distributed in the hope that it will be useful,
10## but WITHOUT ANY WARRANTY; without even the implied warranty of
11## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12## GNU General Public License for more details.
13##
14## You should have received a copy of the GNU General Public License
15## along with this program; if not, write to the Free Software
16## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17##
[6361]18import os
[7221]19import re
[7702]20import codecs
[7670]21import zope.i18nmessageid
[6915]22from datetime import datetime
[7063]23from hurry.file.interfaces import IFileRetrieval
[6353]24from hurry.workflow.interfaces import IWorkflow, IWorkflowInfo
[4789]25from zc.sourcefactory.basic import BasicSourceFactory
[6147]26from zope import schema
[7233]27from zope.pluggableauth.interfaces import IPrincipalInfo
28from zope.security.interfaces import IGroupClosureAwarePrincipal as IPrincipal
[4789]29from zope.component import getUtility
[4882]30from zope.component.interfaces import IObjectEvent
[7063]31from zope.container.interfaces import INameChooser
[5955]32from zope.interface import Interface, Attribute, implements
[4789]33from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm
[3521]34
[7670]35_ = MessageFactory = zope.i18nmessageid.MessageFactory('waeup.sirp')
[6990]36
[7673]37CREATED = 'created'
38ADMITTED = 'admitted'
39CLEARANCE = 'clearance started'
40REQUESTED = 'clearance requested'
41CLEARED = 'cleared'
42PAID = 'school fee paid'
43RETURNING = 'returning'
44REGISTERED = 'courses registered'
45VALIDATED = 'courses validated'
[7670]46
[7702]47default_frontpage = u'' + codecs.open(os.path.join(
48        os.path.dirname(__file__), 'frontpage.rst'),
49        encoding='utf-8', mode='rb').read()
[6361]50
[7321]51def SimpleSIRPVocabulary(*terms):
[6915]52    """A well-buildt vocabulary provides terms with a value, token and
53       title for each term
54    """
55    return SimpleVocabulary([
56            SimpleTerm(value, value, title) for title, value in terms])
57
58def year_range():
59    curr_year = datetime.now().year
[7459]60    return range(curr_year - 4, curr_year + 5)
[6915]61
62def academic_sessions():
63    curr_year = datetime.now().year
64    year_range = range(curr_year - 10, curr_year + 2)
65    return [('%s/%s' % (year,year+1), year) for year in year_range]
66
[7321]67academic_sessions_vocab = SimpleSIRPVocabulary(*academic_sessions())
[6915]68
[7321]69registration_states_vocab = SimpleSIRPVocabulary(
[7677]70    (_('created'), CREATED),
71    (_('admitted'), ADMITTED),
72    (_('clearance started'), CLEARANCE),
73    (_('clearance requested'), REQUESTED),
74    (_('cleared'), CLEARED),
75    (_('school fee paid'), PAID),
76    (_('returning'), RETURNING),
77    (_('courses registered'), REGISTERED),
78    (_('courses validated'), VALIDATED),
[6990]79    )
80
[7772]81SUBJECTS = dict(math=_(u'Math'),
82                bio=_(u'Biology'),
83                eng=_(u'English'),
84                )
85class SubjectSource(BasicSourceFactory):
86    def getValues(self):
87        return sorted(SUBJECTS.keys())
88    def getTitle(self, value):
89        return SUBJECTS.get(value, None)
90
91GRADES = {'A':_(u'Very Good'),
92          'B':_(u'Good'),
93          'C':_(u'Satisfactory'),
94          'D':_(u'Sufficient'),
95          'E':_(u'Fail'),
96          }
97class GradeSource(BasicSourceFactory):
98    def getValues(self):
99        return sorted(GRADES.keys())
100    def getTitle(self, value):
101        return GRADES.get(value, None)
102
[7221]103# Define a valiation method for email addresses
104class NotAnEmailAddress(schema.ValidationError):
105    __doc__ = u"Invalid email address"
106
107check_email = re.compile(
[7608]108    r"[a-zA-Z0-9._%-']+@([a-zA-Z0-9-]+.)*[a-zA-Z]{2,4}").match
[7221]109
110def validate_email(value):
111    if not check_email(value):
112        raise NotAnEmailAddress(value)
113    return True
114
[4858]115class FatalCSVError(Exception):
116    """Some row could not be processed.
117    """
118    pass
119
[6226]120class DuplicationError(Exception):
121    """An exception that can be raised when duplicates are found.
122
123    When raising :exc:`DuplicationError` you can, beside the usual
124    message, specify a list of objects which are duplicates. These
125    values can be used by catching code to print something helpful or
126    similar.
127    """
128    def __init__(self, msg, entries=[]):
129        self.msg = msg
130        self.entries = entries
131
132    def __str__(self):
133        return '%r' % self.msg
134
[6143]135class RoleSource(BasicSourceFactory):
[7178]136    """A source for site roles.
[6508]137    """
[6143]138    def getValues(self):
[6157]139        # late import: in interfaces we should not import local modules
[7186]140        from waeup.sirp.permissions import get_waeup_role_names
141        return get_waeup_role_names()
[6157]142
143    def getTitle(self, value):
144        # late import: in interfaces we should not import local modules
[7186]145        from waeup.sirp.permissions import get_all_roles
146        roles = dict(get_all_roles())
[6157]147        if value in roles.keys():
148            title = roles[value].title
[6569]149            if '.' in title:
150                title = title.split('.', 2)[1]
[6157]151        return title
[6143]152
[7313]153class CaptchaSource(BasicSourceFactory):
154    """A source for captchas.
155    """
156    def getValues(self):
[7323]157        captchas = ['No captcha', 'Testing captcha', 'ReCaptcha']
[7313]158        try:
159            # we have to 'try' because IConfiguration can only handle
160            # interfaces from w.s.interface.
161            from waeup.sirp.browser.interfaces import ICaptchaManager
162        except:
163            return captchas
164        return sorted(getUtility(ICaptchaManager).getAvailCaptchas().keys())
165
166    def getTitle(self, value):
167        return value
168
[7358]169class ISIRPUtils(Interface):
170    """A collection of methods which are subject to customization.
171    """
[7568]172
173    def storage():
174        """Return the initial storage path of the data center.
175        """
176
[7404]177    def sendContactForm(
178          from_name,from_addr,rcpt_name,rcpt_addr,
179          from_username,usertype,portal,body,subject):
[7358]180        """Send an email with data provided by forms.
181        """
182
[7475]183    def fullname(firstname,lastname,middlename):
184        """Full name constructor.
185        """
186
187    def sendCredentials(user, password, login_url, msg):
188        """Send credentials as email.
189
190        Input is the applicant for which credentials are sent and the
191        password.
192
193        Returns True or False to indicate successful operation.
194        """
195
196    def genPassword(length, chars):
197        """Generate a random password.
198        """
199
[7619]200    def getVerdictsDict():
201        """Provide a dict of verdicts.
202        """
203
[7321]204class ISIRPObject(Interface):
205    """A SIRP object.
[5663]206
207    This is merely a marker interface.
[4789]208    """
209
[7321]210class IUniversity(ISIRPObject):
[3521]211    """Representation of a university.
212    """
[5955]213
[6065]214
[7321]215class ISIRPContainer(ISIRPObject):
216    """A container for SIRP objects.
[4789]217    """
218
[7321]219class ISIRPContained(ISIRPObject):
220    """An item contained in an ISIRPContainer.
[4789]221    """
[6136]222
[7726]223class ICSVExporter(Interface):
224    """A CSV file exporter for objects.
225    """
226    fields = Attribute("""List of fieldnames in resulting CSV""")
227   
228    def mangle_value(value, name, obj):
229        """Mangle `value` extracted from `obj` or suobjects thereof.
230
231        This is called by export before actually writing to the result file.
232        """
233
[7730]234    def export(iterable, filepath=None):
235        """Export iterables as rows in a CSV file.
[7726]236
237        If `filepath` is not given, a string with the data should be returned.
[7730]238
239        What kind of iterables are acceptable depends on the specific
240        exporter implementation.
[7726]241        """
242
243    def export_all(site, filapath=None):
244        """Export all items in `site` as CSV file.
245
246        if `filepath` is not given, a string with the data should be returned.
247        """
248
[7321]249class ISIRPExporter(Interface):
[4789]250    """An exporter for objects.
251    """
252    def export(obj, filepath=None):
253        """Export by pickling.
254
255        Returns a file-like object containing a representation of `obj`.
256
257        This is done using `pickle`. If `filepath` is ``None``, a
258        `cStringIO` object is returned, that contains the saved data.
259        """
260
[7321]261class ISIRPXMLExporter(Interface):
[4789]262    """An XML exporter for objects.
263    """
264    def export(obj, filepath=None):
265        """Export as XML.
266
267        Returns an XML representation of `obj`.
268
269        If `filepath` is ``None``, a StringIO` object is returned,
270        that contains the transformed data.
271        """
272
[7321]273class ISIRPXMLImporter(Interface):
[4789]274    """An XML import for objects.
275    """
276    def doImport(filepath):
277        """Create Python object from XML.
278
279        Returns a Python object.
280        """
281
[4858]282class IBatchProcessor(Interface):
283    """A batch processor that handles mass-operations.
284    """
285    name = schema.TextLine(
286        title = u'Importer name'
287        )
288
289    mode = schema.Choice(
290        title = u'Import mode',
291        values = ['create', 'update', 'remove']
292        )
[6136]293
[5476]294    def doImport(path, headerfields, mode='create', user='Unknown',
295                 logger=None):
[4858]296        """Read data from ``path`` and update connected object.
[5476]297
298        `headerfields` is a list of headerfields as read from the file
299        to import.
300
301        `mode` gives the import mode to use (``'create'``,
302        ``'update'``, or ``'remove'``.
303
304        `user` is a string describing the user performing the
305        import. Normally fetched from current principal.
306
307        `logger` is the logger to use during import.
[4858]308        """
309
[7321]310class IContactForm(ISIRPObject):
[7225]311    """A contact form.
312    """
313
314    email_from = schema.ASCIILine(
315        title = u'Email Address:',
316        default = None,
317        required = True,
318        constraint=validate_email,
319        )
320
321    email_to = schema.ASCIILine(
322        title = u'Email to:',
323        default = None,
324        required = True,
325        constraint=validate_email,
326        )
327
328    subject = schema.TextLine(
329        title = u'Subject:',
330        required = True,)
331
332    fullname = schema.TextLine(
333        title = u'Full Name:',
334        required = True,)
335
336    body = schema.Text(
337        title = u'Text:',
338        required = True,)
339
[7233]340class ISIRPPrincipalInfo(IPrincipalInfo):
[7321]341    """Infos about principals that are users of SIRP SIRP.
[7233]342    """
343    email = Attribute("The email address of a user")
344    phone = Attribute("The phone number of a user")
[7225]345
[7233]346
347class ISIRPPrincipal(IPrincipal):
[7321]348    """A principle for SIRP SIRP.
[7233]349
350    This interface extends zope.security.interfaces.IPrincipal and
351    requires also an `id` and other attributes defined there.
352    """
353
354    email = schema.TextLine(
355        title = u'Email',
356        description = u'',
357        required=False,)
358
[7323]359    phone = schema.TextLine(
[7233]360        title = u'Phone',
361        description = u'',
362        required=False,)
363
[7321]364class IUserAccount(ISIRPObject):
[4789]365    """A user account.
366    """
367    name = schema.TextLine(
368        title = u'User ID',
[6512]369        description = u'Login name of user',
[4789]370        required = True,)
[7221]371
[4789]372    title = schema.TextLine(
[7459]373        title = u'Full Name',
[4789]374        required = False,)
[7221]375
[7197]376    description = schema.Text(
377        title = u'Description/Notice',
[4789]378        required = False,)
[7221]379
380    email = schema.ASCIILine(
381        title = u'Email',
382        default = None,
[7222]383        required = True,
[7221]384        constraint=validate_email,
385        )
386
[7323]387    phone = schema.TextLine(
[7233]388        title = u'Phone',
389        default = None,
390        required = True,
391        )
392
[4789]393    roles = schema.List(
[7178]394        title = u'Portal roles',
[4789]395        value_type = schema.Choice(source=RoleSource()))
[6136]396
[7147]397class IPasswordValidator(Interface):
398    """A password validator utility.
399    """
[6136]400
[7147]401    def validate_password(password, password_repeat):
402        """Validates a password by comparing it with
403        control password and checking some other requirements.
404        """
405
406
[7321]407class IUsersContainer(ISIRPObject):
[4789]408    """A container for users (principals).
409
410    These users are used for authentication purposes.
411    """
412
413    def addUser(name, password, title=None, description=None):
414        """Add a user.
415        """
416
417    def delUser(name):
418        """Delete a user if it exists.
419        """
420
[6141]421class ILocalRolesAssignable(Interface):
422    """The local roles assignable to an object.
423    """
424    def __call__():
425        """Returns a list of dicts.
426
427        Each dict contains a ``name`` referring to the role assignable
428        for the specified object and a `title` to describe the range
429        of users to which this role can be assigned.
430        """
431
[7321]432class IConfigurationContainer(ISIRPObject):
[6907]433    """A container for session configuration objects.
434    """
435
436    name = schema.TextLine(
437        title = u'Name of University',
438        default = u'Sample University',
439        required = True,
440        )
441
[7459]442    acronym = schema.TextLine(
443        title = u'Abbreviated Title of University',
444        default = u'WAeUP.SIRP',
445        required = True,
446        )
447
[6907]448    skin = schema.Choice(
449        title = u'Skin',
450        default = u'gray waeup theme',
451        vocabulary = 'waeup.sirp.browser.theming.ThemesVocabulary',
452        required = True,
453        )
454
455    frontpage = schema.Text(
456        title = u'Content in reST format',
457        required = False,
458        default = default_frontpage,
459        )
460
[7702]461    frontpage_dict = schema.Dict(
462        title = u'Content as language dictionary with values in html format',
[7485]463        required = False,
[7702]464        default = {},
[7485]465        )
466
[6990]467    accommodation_session = schema.Choice(
468        title = u'Accommodation Booking Session',
469        source = academic_sessions_vocab,
470        default = datetime.now().year,
471        required = False,
472        readonly = False,
473        )
474
475    accommodation_states = schema.List(
476        title = u'Allowed States for Accommodation Booking',
477        value_type = schema.Choice(
478            vocabulary = registration_states_vocab,
479            ),
480        default = [],
481        )
482
[7223]483    name_admin = schema.TextLine(
484        title = u'Name of Administrator',
485        default = u'Administrator',
486        required = False,
487        )
488
[7221]489    email_admin = schema.ASCIILine(
[7223]490        title = u'Email Address of Administrator',
[7221]491        default = 'contact@waeup.org',
492        required = False,
493        constraint=validate_email,
494        )
495
496    email_subject = schema.TextLine(
497        title = u'Subject of Email to Administrator',
498        default = u'SIRP Contact',
499        required = False,
500        )
501
[7470]502    smtp_mailer = schema.Choice(
503        title = u'SMTP mailer to use when sending mail',
504        vocabulary = 'Mail Delivery Names',
505        default = 'No email service',
506        required = True,
507        )
508
[7313]509    captcha = schema.Choice(
[7475]510        title = u'Captcha used for public registration pages',
[7313]511        source = CaptchaSource(),
512        default = u'No captcha',
513        required = True,
514        )
[7221]515
[7664]516    carry_over = schema.Bool(
517        title = u'Carry-over Course Registration',
518        default = False,
519        )
520
[7321]521class ISessionConfiguration(ISIRPObject):
[6915]522    """A session configuration object.
[6907]523    """
524
[6915]525    academic_session = schema.Choice(
526        title = u'Academic Session',
527        source = academic_sessions_vocab,
528        default = None,
529        required = True,
530        readonly = True,
531        )
532
[7021]533    school_fee_base = schema.Int(
[6915]534        title = u'School Fee',
535        default = 0,
536        )
537
[6929]538    surcharge_1 = schema.Int(
539        title = u'Surcharge 1',
540        default = 0,
541        )
542
543    surcharge_2 = schema.Int(
544        title = u'Surcharge 2',
545        default = 0,
546        )
547
548    surcharge_3 = schema.Int(
549        title = u'Surcharge 3',
550        default = 0,
551        )
552
[7022]553    clearance_fee = schema.Int(
[6929]554        title = u'Clearance Fee',
[6916]555        default = 0,
556        )
557
[6993]558    booking_fee = schema.Int(
559        title = u'Booking Fee',
560        default = 0,
561        )
562
[7250]563    acceptance_fee = schema.Int(
564        title = u'Acceptance Fee',
565        default = 0,
566        )
567
[6918]568    def getSessionString():
569        """Returns the session string from the vocabulary.
570        """
571
572
[6916]573class ISessionConfigurationAdd(ISessionConfiguration):
574    """A session configuration object in add mode.
575    """
576
577    academic_session = schema.Choice(
578        title = u'Academic Session',
579        source = academic_sessions_vocab,
580        default = None,
581        required = True,
582        readonly = False,
583        )
584
585ISessionConfigurationAdd['academic_session'].order =  ISessionConfiguration[
586    'academic_session'].order
587
[7321]588class IDataCenter(ISIRPObject):
[4789]589    """A data center.
590
591    TODO : declare methods, at least those needed by pages.
592    """
593    pass
594
595class IDataCenterFile(Interface):
596    """A data center file.
597    """
[4858]598
599    name = schema.TextLine(
600        title = u'Filename')
601
602    size = schema.TextLine(
603        title = u'Human readable file size')
604
605    uploaddate = schema.TextLine(
606        title = u'Human readable upload datetime')
607
608    lines = schema.Int(
609        title = u'Number of lines in file')
[6136]610
[4789]611    def getDate():
612        """Get creation timestamp from file in human readable form.
613        """
614
615    def getSize():
616        """Get human readable size of file.
617        """
[4858]618
619    def getLinesNumber():
620        """Get number of lines of file.
621        """
[4882]622
623class IDataCenterStorageMovedEvent(IObjectEvent):
624    """Emitted, when the storage of a datacenter changes.
625    """
[5007]626
[6136]627class IObjectUpgradeEvent(IObjectEvent):
628    """Can be fired, when an object shall be upgraded.
629    """
630
[6180]631class ILocalRoleSetEvent(IObjectEvent):
632    """A local role was granted/revoked for a principal on an object.
633    """
634    role_id = Attribute(
635        "The role id that was set.")
636    principal_id = Attribute(
637        "The principal id for which the role was granted/revoked.")
638    granted = Attribute(
639        "Boolean. If false, then the role was revoked.")
640
[5007]641class IQueryResultItem(Interface):
642    """An item in a search result.
643    """
644    url = schema.TextLine(
645        title = u'URL that links to the found item')
646    title = schema.TextLine(
647        title = u'Title displayed in search results.')
648    description = schema.Text(
649        title = u'Longer description of the item found.')
[6136]650
[7321]651class ISIRPPluggable(Interface):
652    """A component that might be plugged into a SIRP SIRP app.
[5658]653
654    Components implementing this interface are referred to as
655    'plugins'. They are normally called when a new
656    :class:`waeup.sirp.app.University` instance is created.
657
658    Plugins can setup and update parts of the central site without the
659    site object (normally a :class:`waeup.sirp.app.University` object)
660    needing to know about that parts. The site simply collects all
661    available plugins, calls them and the plugins care for their
[5676]662    respective subarea like the applicants area or the datacenter
[5658]663    area.
664
665    Currently we have no mechanism to define an order of plugins. A
666    plugin should therefore make no assumptions about the state of the
667    site or other plugins being run before and instead do appropriate
668    checks if necessary.
669
670    Updates can be triggered for instance by the respective form in
671    the site configuration. You normally do updates when the
672    underlying software changed.
[5013]673    """
[5069]674    def setup(site, name, logger):
675        """Create an instance of the plugin.
[5013]676
[5658]677        The method is meant to be called by the central app (site)
678        when it is created.
679
680        `site`:
681           The site that requests a setup.
682
683        `name`:
684           The name under which the plugin was registered (utility name).
685
686        `logger`:
687           A standard Python logger for the plugins use.
[5069]688        """
689
690    def update(site, name, logger):
691        """Method to update an already existing plugin.
692
693        This might be called by a site when something serious
[5658]694        changes. It is a poor-man replacement for Zope generations
695        (but probably more comprehensive and better understandable).
696
697        `site`:
698           The site that requests an update.
699
700        `name`:
701           The name under which the plugin was registered (utility name).
702
703        `logger`:
704           A standard Python logger for the plugins use.
[5069]705        """
[5898]706
[5899]707class IAuthPluginUtility(Interface):
[5898]708    """A component that cares for authentication setup at site creation.
709
710    Utilities providing this interface are looked up when a Pluggable
711    Authentication Utility (PAU) for any
712    :class:`waeup.sirp.app.University` instance is created and put
713    into ZODB.
714
715    The setup-code then calls the `register` method of the utility and
716    expects a modified (or unmodified) version of the PAU back.
717
718    This allows to define any authentication setup modifications by
719    submodules or third-party modules/packages.
720    """
721
722    def register(pau):
723        """Register any plugins wanted to be in the PAU.
724        """
725
726    def unregister(pau):
727        """Unregister any plugins not wanted to be in the PAU.
728        """
[6273]729
730class IObjectConverter(Interface):
731    """Object converters are available as simple adapters, adapting
732       interfaces (not regular instances).
733
734    """
735
[6277]736    def fromStringDict(self, data_dict, context, form_fields=None):
737        """Convert values in `data_dict`.
[6273]738
[6277]739        Converts data in `data_dict` into real values based on
740        `context` and `form_fields`.
[6273]741
[6277]742        `data_dict` is a mapping (dict) from field names to values
743        represented as strings.
[6273]744
[6277]745        The fields (keys) to convert can be given in optional
746        `form_fields`. If given, form_fields should be an instance of
747        :class:`zope.formlib.form.Fields`. Suitable instances are for
748        example created by :class:`grok.AutoFields`.
[6273]749
[6277]750        If no `form_fields` are given, a default is computed from the
751        associated interface.
[6273]752
[6277]753        The `context` can be an existing object (implementing the
754        associated interface) or a factory name. If it is a string, we
755        try to create an object using
756        :func:`zope.component.createObject`.
757
758        Returns a tuple ``(<FIELD_ERRORS>, <INVARIANT_ERRORS>,
759        <DATA_DICT>)`` where
760
761        ``<FIELD_ERRORS>``
762           is a list of tuples ``(<FIELD_NAME>, <ERROR>)`` for each
763           error that happened when validating the input data in
764           `data_dict`
765
766        ``<INVARIANT_ERRORS>``
767           is a list of invariant errors concerning several fields
768
769        ``<DATA_DICT>``
770           is a dict with the values from input dict converted.
771
772        If errors happen, i.e. the error lists are not empty, always
773        an empty ``<DATA_DICT>`` is returned.
774
775        If ``<DATA_DICT>` is non-empty, there were no errors.
[6273]776        """
[6293]777
[6338]778class IObjectHistory(Interface):
779
780    messages = schema.List(
781        title = u'List of messages stored',
782        required = True,
783        )
784
785    def addMessage(message):
786        """Add a message.
787        """
[6353]788
[7321]789class ISIRPWorkflowInfo(IWorkflowInfo):
[6353]790    """A :class:`hurry.workflow.workflow.WorkflowInfo` with additional
791       methods for convenience.
792    """
793    def getManualTransitions():
794        """Get allowed manual transitions.
795
796        Get a sorted list of tuples containing the `transition_id` and
797        `title` of each allowed transition.
798        """
[6481]799
800class ISiteLoggers(Interface):
801
[7321]802    loggers = Attribute("A list or generator of registered SIRPLoggers")
[6481]803
804    def register(name, filename=None, site=None, **options):
805        """Register a logger `name` which logs to `filename`.
806
807        If `filename` is not given, logfile will be `name` with
808        ``.log`` as filename extension.
809        """
810
811    def unregister(name):
812        """Unregister a once registered logger.
813        """
814
815class ILogger(Interface):
816    """A logger cares for setup, update and restarting of a Python logger.
817    """
818
819    logger = Attribute("""A :class:`logging.Logger` instance""")
820
821
822    def __init__(name, filename=None, site=None, **options):
[7321]823        """Create a SIRP logger instance.
[6481]824        """
825
826    def setup():
827        """Create a Python :class:`logging.Logger` instance.
828
829        The created logger is based on the params given by constructor.
830        """
831
832    def update(**options):
833        """Update the logger.
834
835        Updates the logger respecting modified `options` and changed
836        paths.
837        """
[6754]838
839class ILoggerCollector(Interface):
840
841    def getLoggers(site):
842        """Return all loggers registered for `site`.
843        """
844
845    def registerLogger(site, logging_component):
846        """Register a logging component residing in `site`.
847        """
848
849    def unregisterLogger(site, logging_component):
850        """Unregister a logger.
851        """
[7063]852
853#
854# External File Storage and relatives
855#
856class IFileStoreNameChooser(INameChooser):
857    """See zope.container.interfaces.INameChooser for base methods.
858    """
[7066]859    def checkName(name, attr=None):
[7063]860        """Check whether an object name is valid.
861
862        Raises a user error if the name is not valid.
863        """
864
[7066]865    def chooseName(name, attr=None):
866        """Choose a unique valid file id for the object.
[7063]867
[7066]868        The given name may be taken into account when choosing the
869        name (file id).
[7063]870
[7066]871        chooseName is expected to always choose a valid file id (that
872        would pass the checkName test) and never raise an error.
873
874        If `attr` is not ``None`` it might been taken into account as
875        well when generating the file id. Usual behaviour is to
876        interpret `attr` as a hint for what type of file for a given
877        context should be stored if there are several types
878        possible. For instance for a certain student some file could
879        be the connected passport photograph or some certificate scan
880        or whatever. Each of them has to be stored in a different
881        location so setting `attr` to a sensible value should give
882        different file ids returned.
[7063]883        """
884
885class IExtFileStore(IFileRetrieval):
886    """A file storage that stores files in filesystem (not as blobs).
887    """
888    root = schema.TextLine(
889        title = u'Root path of file store.',
890        )
891
892    def getFile(file_id):
893        """Get raw file data stored under file with `file_id`.
894
895        Returns a file descriptor open for reading or ``None`` if the
896        file cannot be found.
897        """
898
[7071]899    def getFileByContext(context, attr=None):
[7063]900        """Get raw file data stored for the given context.
901
902        Returns a file descriptor open for reading or ``None`` if no
903        such file can be found.
904
[7071]905        Both, `context` and `attr` might be used to find (`context`)
906        and feed (`attr`) an appropriate file name chooser.
907
[7063]908        This is a convenience method.
909        """
910
[7090]911    def deleteFile(file_id):
912        """Delete file stored under `file_id`.
913
914        Remove file from filestore so, that it is not available
915        anymore on next call to getFile for the same file_id.
916
917        Should not complain if no such file exists.
918        """
919
920    def deleteFileByContext(context, attr=None):
921        """Delete file for given `context` and `attr`.
922
923        Both, `context` and `attr` might be used to find (`context`)
924        and feed (`attr`) an appropriate file name chooser.
925
926        This is a convenience method.
927        """
928
[7063]929    def createFile(filename, f):
930        """Create file given by f with filename `filename`
931
932        Returns a hurry.file.File-based object.
933        """
934
935class IFileStoreHandler(Interface):
936    """Filestore handlers handle specific files for file stores.
937
938    If a file to store/get provides a specific filename, a file store
939    looks up special handlers for that type of file.
940
941    """
942    def pathFromFileID(store, root, filename):
943        """Turn file id into path to store.
944
945        Returned path should be absolute.
946        """
947
948    def createFile(store, root, filename, file_id, file):
949        """Return some hurry.file based on `store` and `file_id`.
950
951        Some kind of callback method called by file stores to create
952        file objects from file_id.
953
954        Returns a tuple ``(raw_file, path, file_like_obj)`` where the
[7321]955        ``file_like_obj`` should be a HurryFile, a SIRPImageFile or
[7063]956        similar. ``raw_file`` is the (maybe changed) input file and
957        ``path`` the relative internal path to store the file at.
958
959        Please make sure the ``raw_file`` is opened for reading and
960        the file descriptor set at position 0 when returned.
961
962        This method also gets the raw input file object that is about
963        to be stored and is expected to raise any exceptions if some
964        kind of validation or similar fails.
965        """
[7389]966
967class IPDF(Interface):
968    """A PDF representation of some context.
969    """
970
971    def __call__(view=None):
972        """Create a bytestream representing a PDF from context.
973
974        If `view` is passed in additional infos might be rendered into
975        the document.
976        """
[7473]977
978class IMailService(Interface):
979    """A mail service.
980    """
981
982    def __call__():
983        """Get the default mail delivery.
984        """
[7576]985
986from zope.configuration.fields import Path
987class IDataCenterConfig(Interface):
988    path = Path(
989        title = u'Path',
990        description = u"Directory where the datacenter should store"
991                     u"files by default (adjustable in web UI).",
992        required = True,
993        )
994
Note: See TracBrowser for help on using the repository browser.