How to use the zope.component.adapts function in Zope

To help you get started, we’ve selected a few Zope examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github collective / wildcard.media / wildcard / media / browser / syndication.py View on Github external
from Products.CMFPlone.browser.syndication.adapters import DexterityItem
from Products.CMFPlone.interfaces.syndication import IFeed
from zope.component import adapts
from wildcard.media.interfaces import IAudioEnabled, IVideoEnabled
from zope.cachedescriptors.property import Lazy as lazy_property


class AudioFeedItem(DexterityItem):
    adapts(IAudioEnabled, IFeed)

    @property
    def has_enclosure(self):
        return True

    @property
    def file_url(self):
        return '%s/@@download/audio_file/%s' % (
            self.base_url,
            self.context.audio_file.filename
        )

    @lazy_property
    def file(self):
        return self.context.audio_file
github collective / wildcard.media / wildcard / media / primary.py View on Github external
from plone.rfc822.interfaces import IPrimaryFieldInfo
from zope.component import adapts
from zope.interface import implements
from wildcard.media.interfaces import (
    IMediaEnabled, IVideoEnabled
)
from wildcard.media.behavior import IVideo, IAudio


class PrimaryFieldInfo(object):
    implements(IPrimaryFieldInfo)
    adapts(IMediaEnabled)

    def __init__(self, context):
        self.context = context
        if IVideoEnabled.providedBy(self.context):
            self.fieldname = 'video_file'
            self.field = IVideo[self.fieldname]
        else:
            self.fieldname = 'audio_file'
            self.field = IAudio[self.fieldname]

    @property
    def value(self):
        return self.field.get(self.context)
github zopefoundation / z3c.form / src / z3c / form / error.py View on Github external
else:
            self.message = self.createMessage()

    def render(self):
        template = zope.component.getMultiAdapter(
            (self, self.request), IPageTemplate)
        return template(self)

    def __repr__(self):
        return '<%s for %s>' %(
            self.__class__.__name__, self.error.__class__.__name__)


class ValueErrorViewSnippet(ErrorViewSnippet):
    """An error view for ValueError."""
    zope.component.adapts(
        ValueError, None, None, None, None, None)

    defaultMessage = _('The system could not process the given value.')

    def createMessage(self):
        return self.defaultMessage


class InvalidErrorViewSnippet(ErrorViewSnippet):
    """Error view snippet."""
    zope.component.adapts(
        zope.interface.Invalid, None, None, None, None, None)

    def createMessage(self):
        return self.error.args[0]
github plone / plone.app.portlets / plone / app / portlets / manager.py View on Github external
def safe_render(self, portlet_renderer):
        try:
            return portlet_renderer.render()
        except ConflictError:
            raise
        except Exception:
            logger.exception('Error while rendering %r' % self)
            aq_acquire(self, 'error_log').raising(sys.exc_info())
            return self.error_message()


class DashboardPortletManagerRenderer(ColumnPortletManagerRenderer):
    """Render a column of the dashboard
    """

    adapts(Interface, IDefaultBrowserLayer, IBrowserView, IDashboard)
    template = ViewPageTemplateFile('browser/templates/dashboard-column.pt')
github zenoss / ZenPacks.zenoss.CloudStack / ZenPacks / zenoss / CloudStack / dynamicview / adapters.py View on Github external
if host:
                yield self.constructRelationTo(host, TAG_IMPACTED_BY)


class RouterVMRelationsProvider(BaseRelationsProvider):
    adapts(RouterVM)

    def relations(self, type=TAG_ALL):
        if type in (TAG_ALL, TAG_IMPACTED_BY):
            host = self._adapted.host()
            if host:
                yield self.constructRelationTo(host, TAG_IMPACTED_BY)


class ClusterRelationsProvider(BaseRelationsProvider):
    adapts(Cluster)

    def relations(self, type=TAG_ALL):
        if type in (TAG_ALL, TAG_IMPACTS):
            for host in self._adapted.hosts():
                yield self.constructRelationTo(host, TAG_IMPACTS)

        if type in (TAG_ALL, TAG_IMPACTED_BY):
            yield self.constructRelationTo(
                self._adapted.pod(), TAG_IMPACTED_BY)


class HostRelationsProvider(BaseRelationsProvider):
    adapts(Host)

    def relations(self, type=TAG_ALL):
        if type in (TAG_ALL, TAG_IMPACTS):
github collective / wildcard.media / wildcard / media / behavior.py View on Github external
def _get_metadata(self):
        return unicode(json.dumps(getattr(self.context, 'metadata', {})))

    def _set_metadata(self, value):
        pass

    metadata = property(_get_metadata, _set_metadata)


_marker = object()


class Video(BaseAdapter):
    implements(IVideo)
    adapts(IDexterityContent)

    def __init__(self, context):
        self.context = context

    def _get_video_file(self):
        return self.context.video_file

    def _set_video_file(self, value):
        if value is None:
            self.context.video_file = None
            self.context.video_file_ogv = None
            self.context.video_file_webm = None
        elif value != getattr(self.context, 'video_file', _marker):
            self.context.video_converted = False
            self.context.video_file = value
    video_file = property(_get_video_file, _set_video_file)
github zenoss / ZenPacks.zenoss.OpenStackInfrastructure / ZenPacks / zenoss / OpenStack / info.py View on Github external
    @property
    def flavorCount(self):
        return self._object.flavors.countObjects()

    @property
    def imageCount(self):
        return self._object.images.countObjects()

    @property
    def serverCount(self):
        return self._object.servers.countObjects()


class FlavorInfo(OpenStackComponentInfo):
    implements(IFlavorInfo)
    adapts(Flavor)

    flavorId = ProxyProperty('flavorId')
    flavorRAM = ProxyProperty('flavorRAM')
    flavorDisk = ProxyProperty('flavorDisk')

    @property
    def flavorRAMString(self):
        return convToUnits(self._object.flavorRAM, 1024, 'B')

    @property
    def flavorDiskString(self):
        return convToUnits(self._object.flavorDisk, 1024, 'B')

    @property
    def serverCount(self):
        return self._object.servers.countObjects()
github castlecms / castle.cms / castle / cms / widgets.py View on Github external
class TmpFile(object):

    def __init__(self, info):
        self.info = info


class IUploadNamedFileWidget(INamedFileWidget):
    pass


class NamedFileDataConverter(NamedDataConverter):
    """Converts from a file-upload to a NamedFile variant.
    """
    adapts(INamedFileField, IUploadNamedFileWidget)

    def toWidgetValue(self, value):
        return value

    def toFieldValue(self, value):
        extracted = self.widget.extract()
        if isinstance(extracted, TmpFile):
            info = extracted.info
            if not os.path.exists(info['tmp_file']):
                return
            fi = open(info['tmp_file'], 'r')
            filename = ploneutils.safe_unicode(info['name'])
            annotations = IAnnotations(self.widget.context)
            tmp_files = annotations['_tmp_files']
            val = NamedBlobFile(data=fi, filename=filename)
            del tmp_files[info['field_name']]
github ned14 / Easyshop / easyshop.groups / easyshop / groups / adapters / product_management.py View on Github external
# zope imports
from zope.interface import implements
from zope.component import adapts

# CMFCore imports
from Products.CMFCore.utils import getToolByName

# easyshop importss
from iqpp.easyshop.interfaces import IProductManagement
from iqpp.easyshop.interfaces import IProductGroup

class GroupProductManager:
    """
    """
    implements(IProductManagement)
    adapts(IProductGroup)
    
    def __init__(self, context):
        """
        """
        self.context = context

    def getProducts(self):
        """
        """       
        mtool = getToolByName(self.context, "portal_membership")

        result = []
        # Returns just "View"-able products.
        for product in self.context.getRefs('groups_products'):
            if mtool.checkPermission("View", product) is not None:
                result.append(product)
github zopefoundation / z3c.form / src / z3c / form / datamanager.py View on Github external
if isinstance(context, Proxy):
            return canWrite(context, self.field.__name__)
        return True

class DictionaryField(DataManager):
    """Dictionary field.

    NOTE: Even though, this data manager allows nearly all kinds of
    mappings, by default it is only registered for dict, because it
    would otherwise get picked up in undesired scenarios. If you want
    to it use for another mapping, register the appropriate adapter in
    your application.

    """

    zope.component.adapts(
        dict, zope.schema.interfaces.IField)

    _allowed_data_classes = tuple(ALLOWED_DATA_CLASSES)

    def __init__(self, data, field):
        if (not isinstance(data, self._allowed_data_classes) and
            not mapping.IMapping.providedBy(data)):
            raise ValueError("Data are not a dictionary: %s" %type(data))
        self.data = data
        self.field = field

    def get(self):
        """See z3c.form.interfaces.IDataManager"""
        value = self.data.get(self.field.__name__, _marker)
        if value is _marker:
            raise AttributeError