Пример #1
0
def site_factory(request):
    """Application site factory

    On application startup, this factory checks configuration to get application name and
    load it from the ZODB; if the application can't be found, configuration is scanned to
    get application factory, create a new one and create a local site manager.
    """
    conn = get_connection(request)
    root = conn.root()
    application_key = request.registry.settings.get(PYAMS_APPLICATION_SETTINGS_KEY,
                                                    PYAMS_APPLICATION_DEFAULT_NAME)
    application = root.get(application_key)
    if application is None:
        factory = request.registry.settings.get(PYAMS_APPLICATION_FACTORY_KEY)
        if factory:
            resolver = DottedNameResolver()
            factory = resolver.maybe_resolve(factory)
        else:
            factory = request.registry.queryUtility(ISiteRootFactory, default=BaseSiteRoot)
        application = root[application_key] = factory()
        if IPossibleSite.providedBy(application):
            lsm = LocalSiteManager(application, default_folder=False)
            application.setSiteManager(lsm)
        try:
            # if some components require a valid and complete registry
            # with all registered utilities, they can subscribe to
            # INewLocalSiteCreatedEvent event interface
            set_local_registry(application.getSiteManager())
            get_current_registry().notify(NewLocalSiteCreatedEvent(application))
        finally:
            set_local_registry(None)
        import transaction  # pylint: disable=import-outside-toplevel
        transaction.commit()
    return application
Пример #2
0
def get_annotation_adapter(context,
                           key,
                           factory=None,
                           markers=None,
                           notify=True,
                           locate=True,
                           parent=None,
                           name=None,
                           callback=None,
                           **kwargs):
    # pylint: disable=too-many-arguments
    """Get an adapter via object's annotations, creating it if not existent

    :param object context: context object which should be adapted
    :param str key: annotations key to look for
    :param factory: if annotations key is not found, this is the factory which will be used to
        create a new object; factory can be a class or callable object, or an interface for which
        a factory has been registered; if factory is None and is requested object can't be found,
        None is returned
    :param markers: if not None, list of marker interfaces which created adapter should provide
    :param bool=True notify: if 'False', no notification event will be sent on object creation
    :param bool=True locate: if 'False', the new object is not attached to any parent
    :param object=None parent: parent to which new object is attached; if None, object is
        attached to context
    :param str=None name: if locate is not False, this is the name with which the new object is
        attached to it's parent
    :param callback: if not None, callback function which will be called after object creation
    """
    annotations = IAnnotations(context, None)
    if annotations is None:
        return None
    adapter = annotations.get(key)  # pylint: disable=assignment-from-no-return
    if adapter is None:
        if 'default' in kwargs:
            return kwargs['default']
        if factory is None:
            return None
        if is_interface(factory):
            factory = get_object_factory(factory)
            assert factory is not None, "Missing object factory"
        adapter = annotations[key] = factory()
        if markers:
            if not isinstance(markers, (list, tuple, set)):
                markers = {markers}
            for marker in markers:
                alsoProvides(adapter, marker)
        if notify:
            get_current_registry().notify(ObjectCreatedEvent(adapter))
        if locate:
            zope_locate(adapter, context if parent is None else parent, name)
        if callback:
            callback(adapter)
    return adapter
Пример #3
0
def check_required_utilities(site, utilities):
    """Utility function to check for required utilities

    :param ISite site: the site manager into which configuration may be checked
    :param tuple utilities: each element of the tuple is another tuple made of the utility
        interface, the utility registration name, the utility factory and the object name when
        creating the utility, as in:

    .. code-block:: python

        REQUIRED_UTILITIES = ((ISecurityManager, '', SecurityManager, 'Security manager'),
                              (IPrincipalAnnotationUtility, '', PrincipalAnnotationUtility,
                               'User profiles'))
    """
    registry = get_current_registry()
    for interface, name, factory, default_id in utilities:
        utility = query_utility(interface, name=name)
        if utility is None:
            lsm = site.getSiteManager()
            if default_id in lsm:
                continue
            if factory is None:
                factory = get_object_factory(interface)
            utility = factory()
            registry.notify(ObjectCreatedEvent(utility))
            lsm[default_id] = utility
            lsm.registerUtility(utility, interface, name=name)
Пример #4
0
def handle_removed_object(event):
    """Notify IntId utility for removed objects

    This subscriber is used for all persistent objects to be unregistered
    from all locally registered IIntIds utilities.
    """
    registry = get_current_registry()
    locations = ISublocations(event.object, None)
    if locations is not None:
        for location in locations.sublocations():  # pylint: disable=too-many-function-args
            registry.notify(ObjectRemovedEvent(location))
    utilities = tuple(get_all_utilities_registered_for(IIntIds))
    if utilities:
        try:
            key = IKeyReference(event.object, None)
        except NotYet:
            pass
        else:
            # Register only objects that adapt to key reference
            if key is not None:
                # Notify the catalogs that this object is about to be removed.
                registry.notify(IntIdRemovedEvent(event.object, event))
                for utility in utilities:
                    try:
                        utility.unregister(key)
                    except KeyError:
                        pass
Пример #5
0
def register_factory_adapter(for_, klass, registry=None):
    """register the basic object factory adapter for a given interface and class"""
    class temp(FactoryAdapter):  # pylint: disable=invalid-name
        """Factory adapter class"""
        factory = klass

    name = get_interface_name(for_)
    if registry is None:
        registry = get_current_registry()
    registry.registerAdapter(temp,
                             required=(None, IFormLayer, None, IObjectWidget),
                             provided=IObjectFactory,
                             name=name)
Пример #6
0
def handle_added_object(event):
    """Notify IntId utility for added objects

    This subscriber is used for all persistent objects to be registered
    in all locally registered IIntIds utilities.
    """
    utilities = tuple(get_all_utilities_registered_for(IIntIds))
    if utilities:
        # assert that there are any utilities
        try:
            key = IKeyReference(event.object, None)
        except NotYet:
            pass
        else:
            # Register only objects that adapt to key reference
            if key is not None:
                idmap = {}
                for utility in utilities:
                    idmap[utility] = utility.register(key)
                # Notify the catalogs that this object was added.
                get_current_registry().notify(
                    IntIdAddedEvent(event.object, event, idmap))
Пример #7
0
 def _validate(self, value):  # pylint: disable=too-many-branches
     if self.required:
         if self.default:
             return
         if not value:
             raise RequiredMissing
         has_value = False
         registry = get_current_registry()
         for lang, lang_value in value.items():
             # check for NOT_CHANGED value
             if lang_value is NOT_CHANGED:  # check for empty file value
                 adapter = registry.queryMultiAdapter((self.context, self),
                                                      IDataManager)
                 if adapter is not None:
                     try:
                         old_value = adapter.query() or {}
                     except TypeError:  # can't adapt field context => new content?
                         old_value = None
                     else:
                         old_value = old_value.get(lang)
                 else:  # default data manager
                     old_value = getattr(self.context, self.__name__,
                                         {}).get(lang)
                 has_value = has_value or bool(old_value)
                 if has_value:
                     break
             elif lang_value is not TO_BE_DELETED:
                 has_value = True
                 break
         if not has_value:
             raise RequiredMissing
     for lang_value in value.values():
         if lang_value in (NOT_CHANGED, TO_BE_DELETED):
             return
         if isinstance(lang_value, tuple):
             try:
                 filename, stream = lang_value
                 if not isinstance(filename, str):
                     raise WrongType(filename, str,
                                     '{0}.filename'.format(self.__name__))
                 if not hasattr(stream, 'read'):
                     raise WrongType(stream, '<file-like object>',
                                     self.__name__)
             except ValueError as exc:
                 raise WrongType(lang_value, tuple, self.__name__) from exc
         elif not self.value_type.schema.providedBy(lang_value):
             raise WrongType(lang_value, self.value_type.schema,
                             self.__name__)
Пример #8
0
def changed_field(field, value, context=None):
    """Figure if a field's value changed

    Comparing the value of the context attribute and the given value"""
    if context is None:
        context = field.context
    if context is None:
        # IObjectWidget madness
        return True
    if IObject.providedBy(field):
        return True

    # Get the datamanager and get the original value
    dman = get_current_registry().getMultiAdapter((context, field),
                                                  IDataManager)
    # now figure value changed status
    # Or we can not get the original value, in which case we can not check
    # Or it is an Object, in case we'll never know
    if (not dman.can_access()) or (dman.query() != value):
        return True
    return False
Пример #9
0
 def __getattr__(self, name):
     schema = self._Data_schema___
     data = self._Data_data___
     try:
         field = schema[name]
     except KeyError as err:
         raise AttributeError(name) from err
     # If the found field is a method, then raise an error.
     if IMethod.providedBy(field):
         raise RuntimeError("Data value is not a schema field", name)
     # Try to get the value for the field
     value = data.get(name, data)
     if value is data:
         if self.__context__ is None:
             raise NoInputData(name)
         registry = get_current_registry()
         dman = registry.getMultiAdapter((self.__context__, field), IDataManager)
         value = dman.get()
     # Optimization: Once we know we have a good value, set it as an
     # attribute for faster access.
     setattr(self, name, value)
     return value
Пример #10
0
def register_factory(interface, klass, registry=None, name=''):
    """Register factory for a given interface

    :param interface: the interface for which the factory is registered
    :param klass: the object factory
    :param registry: the registry into which factory adapter should be registered; if None, the
        global registry is used
    :param name: custom name given to registered factory
    """

    class Temp(ObjectFactoryAdapter):
        """Object factory matching given interface"""
        classImplements(klass, interface)
        factory = klass

    if_name = get_interface_name(interface)
    if name:
        if_name = '{0}::{1}'.format(if_name, name)
    if registry is None:
        registry = get_current_registry()
    registry.registerAdapter(Temp, name=if_name)
    _factories.setdefault(interface, []).append((name, Temp))
Пример #11
0
 def auth_type(cls):  # pylint: disable=no-self-argument,no-self-use
     """HTTP authentication type setting"""
     return get_current_registry().settings.get('pyams.jwt.auth_type',
                                                'Bearer')
Пример #12
0
 def http_header(cls):  # pylint: disable=no-self-argument,no-self-use
     """HTTP header setting"""
     return get_current_registry().settings.get('pyams.jwt.http_header',
                                                'Authorization')
Пример #13
0
 def update(self):
     """See interfaces.widget.IWidgets"""
     # Create a unique prefix.
     prefix = expand_prefix(self.form.prefix) + expand_prefix(self.prefix)
     # Walk through each field, making a widget out of it.
     data = {}
     data.update(self)
     registry = self.request.registry
     for field in self.form.fields.values():
         # Step 0. Determine whether the context should be ignored.
         ignore_context = self.ignore_context
         if field.ignore_context is not None:
             ignore_context = field.ignore_context
         # Step 1: Determine the mode of the widget.
         mode = self.mode
         if field.mode is not None:
             mode = field.mode
         elif field.field.readonly and not self.ignore_readonly:
             mode = DISPLAY_MODE
         elif not ignore_context:
             # If we do not have enough permissions to write to the
             # attribute, then switch to display mode.
             dman = registry.getMultiAdapter((self.content, field.field),
                                             IDataManager)
             if not dman.can_write():
                 mode = DISPLAY_MODE
         # Step 2: Get the widget for the given field.
         short_name = field.__name__
         new_widget = True
         if short_name in self:
             # reuse existing widget
             widget = data[short_name]
             new_widget = False
         elif field.widget_factory.get(mode) is not None:
             factory = field.widget_factory.get(mode)
             widget = factory(field.field, self.request)
         else:
             widget = registry.getMultiAdapter((field.field, self.request),
                                               IFieldWidget)
         # Step 3: Set the prefix for the widget
         widget.name = prefix + short_name
         widget.id = (prefix + short_name).replace('.', '-')
         # Step 4: Set the context
         widget.context = self.content
         # Step 5: Set the form
         widget.form = self.form
         # Optimization: Set both interfaces here, rather in step 4 and 5:
         # ``alsoProvides`` is quite slow
         alsoProvides(widget, IContextAware, IFormAware)
         # Step 6: Set some variables
         widget.ignore_context = ignore_context
         widget.ignore_request = self.ignore_request
         if field.show_default is not None:
             widget.show_default = field.show_default
         # Step 7: Set the mode of the widget
         widget.mode = mode
         # Step 8: Update the widget
         widget.update()
         get_current_registry().notify(AfterWidgetUpdateEvent(widget))
         # Step 9: Add the widget to the manager
         if widget.required:
             self.has_required_fields = True
         if new_widget:
             data[short_name] = widget
             locate(widget, self, short_name)
     self.create_according_to_list(data, self.form.fields.keys())