Decorator to return standard content objects as SuperModels
497033
def returns_super_model(func):
    
    def to_super_model(obj):
        # avoid circular imports
        from senaite.core.supermodel import SuperModel

        # Object is already a SuperModel
        if isinstance(obj, SuperModel):
            return obj

        # Only portal objects are supported
        if not api.is_object(obj):
            raise TypeError("Expected a portal object, got '{}'"
                            .format(type(obj)))

        # Wrap the object into a specific Publication Object Adapter
        uid = api.get_uid(obj)
        portal_type = api.get_portal_type(obj)

        adapter = queryAdapter(uid, ISuperModel, name=portal_type)
        if adapter is None:
            return SuperModel(uid)
        return adapter

    @wraps(func)
    def wrapper(*args, **kwargs):
        obj = func(*args, **kwargs)
        if isinstance(obj, (list, tuple)):
            return map(to_super_model, obj)
        return to_super_model(obj)

    return wrapper
913118
def load_model_from_package(name, **overrides):
    """"""
    cls = importlib.import_module(name)
    return cls.load(**overrides)
123494
def resolve_model(self, model):
        '''
        
        '''
        if not model:
            raise ValueError('Unsupported model specifications')
        if isinstance(model, basestring):
            classname = model
        elif isinstance(model, dict) and 'class' in model:
            classname = model['class']
        else:
            raise ValueError('Unsupported model specifications')

        try:
            return get_document(classname)
        except self.NotRegistered:
            message = 'Model "{0}" does not exist'.format(classname)
            raise ValueError(message)
490812
def lazy(decorator):
    """"""
    def decorate(fn, *args, **kwargs):
        name = fn.__name__
        parent = decorator(fn, *args, **kwargs)
        #doc = _add_msg(getattr(parent, '__doc__', None), '*@lazy*')
        doc = getattr(parent, '__doc__', None)
        if hasattr(parent, '__set__') or hasattr(parent, '__delete__'):
            return _lazy_data(name, parent, doc)
        else:
            return _lazy_nondata(name, parent, doc)
    return decorate
821854
def decorator(cls, func_or_class):
        """"""
        resources = getattr(func_or_class, 'resources', [])
        resources.append(cls)
        func_or_class.resources = resources
        return func_or_class
611661
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'models' in _dict:
            args['models'] = [
                Model._from_dict(x) for x in (_dict.get('models'))
            ]
        return cls(**args)
235227
def dict_to_object(d):
    """"""
    top = type('CreateSendModel', (object,), d)
    seqs = tuple, list, set, frozenset
    for i, j in d.items():
        if isinstance(j, dict):
            setattr(top, i, dict_to_object(j))
        elif isinstance(j, seqs):
            setattr(top, i, type(j)(dict_to_object(sj) if isinstance(sj, dict) else sj for sj in j))
        else:
            setattr(top, i, j)
    return top
193276
def compiled_model(self):
        """"""
        return ALCHEMY_TEMPLATES.model.safe_substitute(class_name=self.class_name,
                                                       table_name=self.table_name,
                                                       column_definitions=self.compiled_columns,
                                                       init_function=self.compiled_init_func,
                                                       update_function=self.compiled_update_func,
                                                       hash_function=self.compiled_hash_func,
                                                       eq_function=self.compiled_eq_func,
                                                       neq_function=self.compiled_neq_func,
                                                       str_function=self.compiled_str_func,
                                                       unicode_function=self.compiled_unicode_func,
                                                       repr_function=self.compiled_repr_func,
                                                       types=", ".join(self.basic_types),
                                                       username=self.username,
                                                       foreign_keys=self.compiled_foreign_keys,
                                                       relationships=self.compiled_relationships,
                                                       named_imports=self.compiled_named_imports,
                                                       orm_imports=self.compiled_orm_imports,
                                                       get_proxy_cls_function=self.compiled_proxy_cls_func,
                                                       add_function=ALCHEMY_TEMPLATES.add_function.template,
                                                       delete_function=ALCHEMY_TEMPLATES.delete_function.template,
                                                       to_dict_function=ALCHEMY_TEMPLATES.to_dict_function.template,
                                                       to_proxy_function=ALCHEMY_TEMPLATES.to_proxy_function.template,
                                                       from_proxy_function=ALCHEMY_TEMPLATES.from_proxy_function.template)
1078034
def get_base_wrappers(method='get', template_name='', predicates=(), wrappers=()):
    
    wrappers += (preserve_view(MethodPredicate(method), *predicates),)

    if template_name:
        wrappers += (render_template(template_name),)

    return wrappers
271711
def as_models(self, klass):
        """"""
        try:
            return [klass(mod) for mod in self.tree.reply.data.results.array[0].item]
        except AttributeError:
            return []
1088046
def create_extras(cls: Type[T],
                  extras: Dict[str, Any]) -> Dict[str, Any]:
    
    subextras: Dict[str, Any] = {}
    if hasattr(cls, "from_params"):
        from_params_method = cls.from_params  # type: ignore
    else:
        # In some rare cases, we get a registered subclass that does _not_ have a
        # from_params method (this happens with Activations, for instance, where we
        # register pytorch modules directly).  This is a bit of a hack to make those work,
        # instead of adding a `from_params` method for them somehow. Then the extras
        # in the class constructor are what we are looking for, to pass on.
        from_params_method = cls
    if takes_kwargs(from_params_method):
        # If annotation.params accepts **kwargs, we need to pass them all along.
        # For example, `BasicTextFieldEmbedder.from_params` requires a Vocabulary
        # object, but `TextFieldEmbedder.from_params` does not.
        subextras = extras
    else:
        # Otherwise, only supply the ones that are actual args; any additional ones
        # will cause a TypeError.
        subextras = {k: v for k, v in extras.items()
                     if takes_arg(from_params_method, k)}
    return subextras
1188493
def _get_ctypes(self):
        
        ctypes = []
        for related_object in self.model._meta.get_all_related_objects():
            model = getattr(related_object, 'related_model', related_object.model)
            ctypes.append(ContentType.objects.get_for_model(model).pk)
            if model.__subclasses__():
                for child in model.__subclasses__():
                    ctypes.append(ContentType.objects.get_for_model(child).pk)
        return ctypes
146676
def post_loader(*decorator_args, serializer):
    
    def wrapped(fn):
        @wraps(fn)
        def decorated(*args, **kwargs):
            return fn(*serializer.load(request.get_json()))
        return decorated

    if decorator_args and callable(decorator_args[0]):
        return wrapped(decorator_args[0])
    return wrapped
179110
def results_decorator(func):
    
    # Wrap function to maintian the original doc string, etc
    @wraps(func)
    def decorator(lookup_cls):
        # Construct a class decorator from the original function
        original = lookup_cls.results
        def inner(self, request):
            # Wrap lookup_cls.results by first calling func and checking the result
            result = func(request)
            if isinstance(result, HttpResponse):
                return result
            return original(self, request)
        # Replace original lookup_cls.results with wrapped version
        lookup_cls.results = inner
        return lookup_cls
    # Return the constructed decorator
    return decorator
1174053
def templated(template=None, *templates):
    

    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            template_ = template
            if template_ is None:
                template_ = request.endpoint.split('.', 1)[1].replace(
                    '.', '/') + '.html'
            context = func(*args, **kwargs)
            if context is None:
                context = {}
            elif not isinstance(context, dict):
                return context
            return custom_render_template(
                list(chain(to_list(template_), templates)), **context)

        return wrapper

    return decorator
859455
def wrap_content_as_binary_if_needed(func_, *args, **kwargs):
    
    assert isinstance(args[0], dict)
    try:
        args[0][CONTENT_FIELD] = BINARY(args[0].get(CONTENT_FIELD, b""))
    except (r.errors.ReqlDriverCompileError, AttributeError):  # pragma: no cover
        pass  # toss in the object as string
    return func_(*args, **kwargs)
1374993
def get_fieldsets(self, request, obj=None):
        '''  '''
        # If subclass declares fieldsets, this is respected
        if (hasattr(self, 'declared_fieldset') and self.declared_fieldsets) \
           or not self.base_fieldsets:
            return super(PolymorphicChildModelAdmin, self).get_fieldsets(request, obj)

        other_fields = self.get_subclass_fields(request, obj)

        if other_fields:
            return (
                (self.extra_fieldset_title, {'fields': other_fields}),
            ) + self.base_fieldsets
        else:
            return self.base_fieldsets