def icon_present_for_display_types_that_need_it(self): display = self.display has_icon = any(getattr(self, key, None) not in ('', None) for key in (ICON_PROPERTIES)) icon_required = ('title-buttons', 'add-menu') icon_forbidden = ('actions-menu', 'user-menu') icon_optional = ('action-buttons', ) # noqa if display in icon_forbidden: if has_icon: raise Invalid("Display location %r doesn't allow an icon." % display) elif display in icon_required: if not has_icon: raise Invalid('Display location %r requires an icon.' % display)
def saneDates(poll): """Ensure the poll's dates are sane. A poll's end date must be after its start date and its start date must be at least 12h from now. """ if poll.dateopens >= poll.datecloses: raise Invalid( "A poll cannot close at the time (or before) it opens.") now = datetime.now(pytz.UTC) twelve_hours_ahead = now + timedelta(hours=12) start_date = poll.dateopens.astimezone(pytz.UTC) if start_date < twelve_hours_ahead: raise Invalid( "A poll cannot open less than 12 hours after it's created.")
def BarGreaterThanFoo(obj): foo = getattr(obj, 'foo', None) bar = getattr(obj, 'bar', None) if foo is not None and isinstance(foo, type(bar)): # type checking should be handled elsewhere (like, say, # schema); these invariants should be intra-interface # constraints. This is a hacky way to do it, maybe, but you # get the idea if not bar > foo: raise Invalid('Please, Boo MUST be greater than Foo!')
def validateObject(self, obj): errors = super(AddTermFormValidator, self).validateObject(obj) try: dr = DateRange(obj.first, obj.last) try: validateTermsForOverlap(self.view.context, dr, None) except TermOverlapError, e: errors += (e, ) except ValueError, e: errors += (Invalid(_("Term must begin before it ends.")), )
def validateObject(self, obj): errors = super(AddSchoolYearOverlapValidator, self).validateObject(obj) try: dr = DateRange(obj.first, obj.last) try: validateScholYearsForOverlap(self.view.context, dr, None) except SchoolYearOverlapError, e: errors += (e, ) except ValueError, e: errors += (Invalid(_("School year must begin before it ends.")), )
def legal_not_immediately_addable(data): missing = [] for one_allowed in data.secondary_types: if one_allowed not in data.allowed_types: missing.append(one_allowed) if missing: raise Invalid( PC_("You cannot have a type as a secondary type without " "having it allowed. You have selected ${types}s.", mapping=dict(types=", ".join(missing)))) return True
def validate_columns(obj): columns = [ v for k, v in obj._Data_data___.items() if k.startswith("column_") ] if obj._Data_data___.get( 'treating_groups' ) is not None and u'treating_groups_title' in columns: raise Invalid( _("You can't select both a treating_groups and a column associated to treating groups title" )) required = extract_required_columns(obj) return tree_utils.validate_csv_columns(obj, required)
def validateInvariants(self, obj, errors=None): """validate object to defined invariants.""" for iface in self.__iro__: for invariant in iface.queryDirectTaggedValue('invariants', ()): try: invariant(obj) except Invalid as error: if errors is not None: errors.append(error) else: raise if errors: raise Invalid(errors)
def validateInvariants(self, obj, errors=None): """validate object to defined invariants.""" for call in self.queryTaggedValue('invariants', []): try: call(obj) except Invalid as e: if errors is None: raise errors.append(e) for base in self.__bases__: try: base.validateInvariants(obj, errors) except Invalid: if errors is None: raise if errors: raise Invalid(errors)
def handlePasswordReset(self, action): authenticator = getMultiAdapter( (self.context, self.request), name=u'authenticator') if not authenticator.verify(): raise Unauthorized data, errors = self.extractData() if errors: self.status = self.formErrorsMessage return if 'password' in data and 'password_confirm' in data: if data['password'] != data['password_confirm']: raise WidgetActionExecutionError('password', Invalid(_( u'error_passwords_must_match', default=u'Passwords must ' u'match.'))) current = api.user.get_current() # Try traverse subpath first: try: key = self.request['TraversalRequestNameStack'][:0] except IndexError: key = None # Fall back to request variable for BW compat if not key: key = self.request.get('key', None) pw_tool = getToolByName(self.context, 'portal_password_reset') # key is the value for arg randomstring pw_tool.resetPassword(current, key, data.get('password')) IStatusMessage(self.request).addStatusMessage( _(u'statusmessage_pwreset_passwort_was_reset', default=u'Your ' u'password has been reset.'), 'info') self.request.response.redirect(self.context.absolute_url())
class InterfaceClass(Element, InterfaceBase, Specification): """Prototype (scarecrow) Interfaces Implementation.""" # We can't say this yet because we don't have enough # infrastructure in place. # #implements(IInterface) def __init__(self, name, bases=(), attrs=None, __doc__=None, __module__=None): if attrs is None: attrs = {} if __module__ is None: __module__ = attrs.get('__module__') if isinstance(__module__, str): del attrs['__module__'] else: try: # Figure out what module defined the interface. # This is how cPython figures out the module of # a class, but of course it does it in C. :-/ __module__ = sys._getframe(1).f_globals['__name__'] except (AttributeError, KeyError): pass self.__module__ = __module__ d = attrs.get('__doc__') if d is not None: if not isinstance(d, Attribute): if __doc__ is None: __doc__ = d del attrs['__doc__'] if __doc__ is None: __doc__ = '' Element.__init__(self, name, __doc__) tagged_data = attrs.pop(TAGGED_DATA, None) if tagged_data is not None: for key, val in tagged_data.items(): self.setTaggedValue(key, val) for base in bases: if not isinstance(base, InterfaceClass): raise TypeError('Expected base interfaces') Specification.__init__(self, bases) # Make sure that all recorded attributes (and methods) are of type # `Attribute` and `Method` for name, attr in attrs.items(): if name == '__locals__': # This happens under Python 3 sometimes, not sure why. /regebro continue if isinstance(attr, Attribute): attr.interface = self if not attr.__name__: attr.__name__ = name elif isinstance(attr, FunctionType): attrs[name] = fromFunction(attr, self, name=name) elif attr is _decorator_non_return: del attrs[name] else: raise InvalidInterface("Concrete attribute, " + name) self.__attrs = attrs self.__identifier__ = "%s.%s" % (self.__module__, self.__name__) def interfaces(self): """Return an iterator for the interfaces in the specification for example:: >>> from zope.interface import Interface >>> class I1(Interface): pass ... >>> >>> i = I1.interfaces() >>> [x.getName() for x in i] ['I1'] >>> list(i) [] """ yield self def getBases(self): return self.__bases__ def isEqualOrExtendedBy(self, other): """Same interface or extends?""" return self == other or other.extends(self) def names(self, all=False): """Return the attribute names defined by the interface.""" if not all: return self.__attrs.keys() r = self.__attrs.copy() for base in self.__bases__: r.update(dict.fromkeys(base.names(all))) return r.keys() def __iter__(self): return iter(self.names(all=True)) def namesAndDescriptions(self, all=False): """Return attribute names and descriptions defined by interface.""" if not all: return self.__attrs.items() r = {} for base in self.__bases__[::-1]: r.update(dict(base.namesAndDescriptions(all))) r.update(self.__attrs) return r.items() def getDescriptionFor(self, name): """Return the attribute description for the given name.""" r = self.get(name) if r is not None: return r raise KeyError(name) __getitem__ = getDescriptionFor def __contains__(self, name): return self.get(name) is not None def direct(self, name): return self.__attrs.get(name) def queryDescriptionFor(self, name, default=None): return self.get(name, default) def deferred(self): """Return a defered class corresponding to the interface.""" if hasattr(self, "_deferred"): return self._deferred klass = {} exec "class %s: pass" % self.__name__ in klass klass = klass[self.__name__] self.__d(klass) self._deferred = klass return klass def validateInvariants(self, obj, errors=None): """validate object to defined invariants.""" for call in self.queryTaggedValue('invariants', []): try: call(obj) except Invalid, e: if errors is None: raise else: errors.append(e) for base in self.__bases__: try: base.validateInvariants(obj, errors) except Invalid: if errors is None: raise if errors: raise Invalid(errors)
def contained(node): if IShadowTreeRoot.providedBy(node): return if node.__parent__ is None or not node.id: raise Invalid(b'A node must be contained within the shadowtree.')
def _epic_fail(obj): raise Invalid("testing")
def no_more_than_one_icon(self): icons = filter(None, (getattr(self, key, None) for key in (ICON_PROPERTIES))) if len(icons) > 1: raise Invalid( 'Icon properties %r are mutually exclusive. ' 'At most one icon allowed.' % ICON_PROPERTIES)
def ifFooThenBar(obj): if getattr(obj, 'foo', None) and not getattr(obj, 'bar', None): raise Invalid('If Foo, then Bar!')
def empty_id(node): if node.id != b'': raise Invalid( u'Root node id should be the empty string.' )
def _epic_fail(obj): raise Invalid('testing')
def validateObject(self, obj): errors = super(EditSchoolYearValidator, self).validateObject(obj) try: dr = DateRange(obj.first, obj.last) try: validateScholYearsForOverlap(self.view.context.__parent__, dr, self.view.context) except SchoolYearOverlapError, e: errors += (e, ) try: validateScholYearForOverflow(dr, self.view.context) except TermOverflowError, e: errors += (e, ) except ValueError, e: errors += (Invalid(_("School year must begin before it ends.")), ) except NoInputData: return errors return errors WidgetsValidatorDiscriminators(EditSchoolYearValidator, view=SchoolYearEditView, schema=getSpecification(ISchoolYearAddForm, force=True)) class FlourishInvalidDateRangeError(ValidationError): __doc__ = _('School year must begin before it ends')
def mirrorMustHaveHTTPOrFTPURL(mirror): if not (mirror.http_base_url or mirror.ftp_base_url): raise Invalid('A mirror must have at least an HTTP or FTP URL.')
def validatePluralData(form_language): pair = (form_language.pluralforms, form_language.pluralexpression) if None in pair and pair != (None, None): raise Invalid( 'The number of plural forms and the plural form expression ' 'must be set together, or not at all.')
def no_parent(node): if node.__parent__ is not None: raise Invalid( u'Root node of the shadowtree should have no parent' )