source: main/waeup.kofa/trunk/src/waeup/kofa/interfaces.py @ 7860

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

Make validator work correctly.

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