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
Line 
1## $Id: interfaces.py 7772 2012-03-07 09:06:12Z 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.vocabulary import SimpleVocabulary, SimpleTerm
34
35_ = MessageFactory = zope.i18nmessageid.MessageFactory('waeup.sirp')
36
37CREATED = 'created'
38ADMITTED = 'admitted'
39CLEARANCE = 'clearance started'
40REQUESTED = 'clearance requested'
41CLEARED = 'cleared'
42PAID = 'school fee paid'
43RETURNING = 'returning'
44REGISTERED = 'courses registered'
45VALIDATED = 'courses validated'
46
47default_frontpage = u'' + codecs.open(os.path.join(
48        os.path.dirname(__file__), 'frontpage.rst'),
49        encoding='utf-8', mode='rb').read()
50
51def SimpleSIRPVocabulary(*terms):
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
60    return range(curr_year - 4, curr_year + 5)
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
67academic_sessions_vocab = SimpleSIRPVocabulary(*academic_sessions())
68
69registration_states_vocab = SimpleSIRPVocabulary(
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),
79    )
80
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
103# Define a valiation 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
115class FatalCSVError(Exception):
116    """Some row could not be processed.
117    """
118    pass
119
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
135class RoleSource(BasicSourceFactory):
136    """A source for site roles.
137    """
138    def getValues(self):
139        # late import: in interfaces we should not import local modules
140        from waeup.sirp.permissions import get_waeup_role_names
141        return get_waeup_role_names()
142
143    def getTitle(self, value):
144        # late import: in interfaces we should not import local modules
145        from waeup.sirp.permissions import get_all_roles
146        roles = dict(get_all_roles())
147        if value in roles.keys():
148            title = roles[value].title
149            if '.' in title:
150                title = title.split('.', 2)[1]
151        return title
152
153class CaptchaSource(BasicSourceFactory):
154    """A source for captchas.
155    """
156    def getValues(self):
157        captchas = ['No captcha', 'Testing captcha', 'ReCaptcha']
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
169class ISIRPUtils(Interface):
170    """A collection of methods which are subject to customization.
171    """
172
173    def storage():
174        """Return the initial storage path of the data center.
175        """
176
177    def sendContactForm(
178          from_name,from_addr,rcpt_name,rcpt_addr,
179          from_username,usertype,portal,body,subject):
180        """Send an email with data provided by forms.
181        """
182
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
200    def getVerdictsDict():
201        """Provide a dict of verdicts.
202        """
203
204class ISIRPObject(Interface):
205    """A SIRP object.
206
207    This is merely a marker interface.
208    """
209
210class IUniversity(ISIRPObject):
211    """Representation of a university.
212    """
213
214
215class ISIRPContainer(ISIRPObject):
216    """A container for SIRP objects.
217    """
218
219class ISIRPContained(ISIRPObject):
220    """An item contained in an ISIRPContainer.
221    """
222
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
234    def export(iterable, filepath=None):
235        """Export iterables as rows in a CSV file.
236
237        If `filepath` is not given, a string with the data should be returned.
238
239        What kind of iterables are acceptable depends on the specific
240        exporter implementation.
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
249class ISIRPExporter(Interface):
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
261class ISIRPXMLExporter(Interface):
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
273class ISIRPXMLImporter(Interface):
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
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        )
293
294    def doImport(path, headerfields, mode='create', user='Unknown',
295                 logger=None):
296        """Read data from ``path`` and update connected object.
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.
308        """
309
310class IContactForm(ISIRPObject):
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
340class ISIRPPrincipalInfo(IPrincipalInfo):
341    """Infos about principals that are users of SIRP SIRP.
342    """
343    email = Attribute("The email address of a user")
344    phone = Attribute("The phone number of a user")
345
346
347class ISIRPPrincipal(IPrincipal):
348    """A principle for SIRP SIRP.
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
359    phone = schema.TextLine(
360        title = u'Phone',
361        description = u'',
362        required=False,)
363
364class IUserAccount(ISIRPObject):
365    """A user account.
366    """
367    name = schema.TextLine(
368        title = u'User ID',
369        description = u'Login name of user',
370        required = True,)
371
372    title = schema.TextLine(
373        title = u'Full Name',
374        required = False,)
375
376    description = schema.Text(
377        title = u'Description/Notice',
378        required = False,)
379
380    email = schema.ASCIILine(
381        title = u'Email',
382        default = None,
383        required = True,
384        constraint=validate_email,
385        )
386
387    phone = schema.TextLine(
388        title = u'Phone',
389        default = None,
390        required = True,
391        )
392
393    roles = schema.List(
394        title = u'Portal roles',
395        value_type = schema.Choice(source=RoleSource()))
396
397class IPasswordValidator(Interface):
398    """A password validator utility.
399    """
400
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
407class IUsersContainer(ISIRPObject):
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
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
432class IConfigurationContainer(ISIRPObject):
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
442    acronym = schema.TextLine(
443        title = u'Abbreviated Title of University',
444        default = u'WAeUP.SIRP',
445        required = True,
446        )
447
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
461    frontpage_dict = schema.Dict(
462        title = u'Content as language dictionary with values in html format',
463        required = False,
464        default = {},
465        )
466
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
483    name_admin = schema.TextLine(
484        title = u'Name of Administrator',
485        default = u'Administrator',
486        required = False,
487        )
488
489    email_admin = schema.ASCIILine(
490        title = u'Email Address of Administrator',
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
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
509    captcha = schema.Choice(
510        title = u'Captcha used for public registration pages',
511        source = CaptchaSource(),
512        default = u'No captcha',
513        required = True,
514        )
515
516    carry_over = schema.Bool(
517        title = u'Carry-over Course Registration',
518        default = False,
519        )
520
521class ISessionConfiguration(ISIRPObject):
522    """A session configuration object.
523    """
524
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
533    school_fee_base = schema.Int(
534        title = u'School Fee',
535        default = 0,
536        )
537
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
553    clearance_fee = schema.Int(
554        title = u'Clearance Fee',
555        default = 0,
556        )
557
558    booking_fee = schema.Int(
559        title = u'Booking Fee',
560        default = 0,
561        )
562
563    acceptance_fee = schema.Int(
564        title = u'Acceptance Fee',
565        default = 0,
566        )
567
568    def getSessionString():
569        """Returns the session string from the vocabulary.
570        """
571
572
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
588class IDataCenter(ISIRPObject):
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    """
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')
610
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        """
618
619    def getLinesNumber():
620        """Get number of lines of file.
621        """
622
623class IDataCenterStorageMovedEvent(IObjectEvent):
624    """Emitted, when the storage of a datacenter changes.
625    """
626
627class IObjectUpgradeEvent(IObjectEvent):
628    """Can be fired, when an object shall be upgraded.
629    """
630
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
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.')
650
651class ISIRPPluggable(Interface):
652    """A component that might be plugged into a SIRP SIRP app.
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
662    respective subarea like the applicants area or the datacenter
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.
673    """
674    def setup(site, name, logger):
675        """Create an instance of the plugin.
676
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.
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
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.
705        """
706
707class IAuthPluginUtility(Interface):
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        """
729
730class IObjectConverter(Interface):
731    """Object converters are available as simple adapters, adapting
732       interfaces (not regular instances).
733
734    """
735
736    def fromStringDict(self, data_dict, context, form_fields=None):
737        """Convert values in `data_dict`.
738
739        Converts data in `data_dict` into real values based on
740        `context` and `form_fields`.
741
742        `data_dict` is a mapping (dict) from field names to values
743        represented as strings.
744
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`.
749
750        If no `form_fields` are given, a default is computed from the
751        associated interface.
752
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.
776        """
777
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        """
788
789class ISIRPWorkflowInfo(IWorkflowInfo):
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        """
799
800class ISiteLoggers(Interface):
801
802    loggers = Attribute("A list or generator of registered SIRPLoggers")
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):
823        """Create a SIRP logger instance.
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        """
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        """
852
853#
854# External File Storage and relatives
855#
856class IFileStoreNameChooser(INameChooser):
857    """See zope.container.interfaces.INameChooser for base methods.
858    """
859    def checkName(name, attr=None):
860        """Check whether an object name is valid.
861
862        Raises a user error if the name is not valid.
863        """
864
865    def chooseName(name, attr=None):
866        """Choose a unique valid file id for the object.
867
868        The given name may be taken into account when choosing the
869        name (file id).
870
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.
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
899    def getFileByContext(context, attr=None):
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
905        Both, `context` and `attr` might be used to find (`context`)
906        and feed (`attr`) an appropriate file name chooser.
907
908        This is a convenience method.
909        """
910
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
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
955        ``file_like_obj`` should be a HurryFile, a SIRPImageFile or
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        """
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        """
977
978class IMailService(Interface):
979    """A mail service.
980    """
981
982    def __call__():
983        """Get the default mail delivery.
984        """
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.