class DaemonStateRenderer(Adapter): implements(IProcessStateRenderer) context(DaemonProcess) def __str__(self): return "[%s%s]" % (self.context.__name__, ': paused' if self.context.paused else '')
class Interface_SchemaName(grok.Adapter): """Adapter between Interface and ISchemaName.""" grok.context(zope.interface.interfaces.IInterface) def __init__(self, context): self.schema_name = six.text_type(context.getName())
class ContinueTaskAction(SignalAction): """Send CONT signal""" context(ISuspendableTask) action('continue') __signal__ = 'CONT'
class TerminateTaskAction(SignalAction): """Send TERM signal""" context(ITask) action('terminate') __signal__ = 'TERM'
class WebDAVProperties(grok.Adapter, collections.MutableMapping): grok.context(zeit.retresco.interfaces.ITMSContent) grok.provides(zeit.connector.interfaces.IWebDAVProperties) def __getitem__(self, key): name, ns = map(unquote_es_field_name, key) namespace = ns.replace(zeit.retresco.interfaces.DAV_NAMESPACE_BASE, '', 1) return self.context._tms_payload[namespace][name] def keys(self): for ns, values in self.context._tms_payload.items(): namespace = zeit.retresco.interfaces.DAV_NAMESPACE_BASE + ns for name in values: yield (unquote_es_field_name(name), unquote_es_field_name(namespace)) def __iter__(self): return iter(self.keys()) def __len__(self): return len(self.keys()) def __delitem__(self, key): raise RuntimeError("Cannot write on ReadOnlyWebDAVProperties") def __setitem__(self, key, value): raise RuntimeError("Cannot write on ReadOnlyWebDAVProperties")
class Dependencies(grok.Adapter): """Adapter to find the publication dependencies of an object.""" grok.context(zeit.cms.interfaces.ICMSContent) grok.implements(zeit.workflow.interfaces.IPublicationDependencies) def get_dependencies(self): dependencies = set() for adapter in self._find_adapters(): dependencies.update(adapter.get_dependencies()) return sorted(dependencies, key=lambda x: x.uniqueId) def get_retract_dependencies(self): dependencies = set() for adapter in self._find_adapters(): if adapter.retract_dependencies: dependencies.update(adapter.get_dependencies()) return sorted(dependencies, key=lambda x: x.uniqueId) def _find_adapters(self): for name, adapter in zope.component.getAdapters( (self.context, ), zeit.workflow.interfaces.IPublicationDependencies): if not name: # This is actually this adapter continue yield adapter
class SecurityRest(rest.REST): grok.context(MyContent) view.layer(LayerSecurity) @security.require(security.Public) def GET(self): self.request.response.setHeader('Content-Type', 'text/plain;charset=utf-8') return "GET3" @security.require('zope.ManageContent') def POST(self): self.request.response.setHeader('Content-Type', 'text/plain;charset=utf-8') return "POST3" @security.require('zope.ManageContent') def PUT(self): self.request.response.setHeader('Content-Type', 'text/plain;charset=utf-8') return "PUT3" @security.require('zope.ManageContent') def DELETE(self): self.request.response.setHeader('Content-Type', 'text/plain;charset=utf-8') return "DELETE3"
class BaseClassPathMapping(component.Subscription): """ Base class for all extjs class path mapping registrations """ component.baseclass() component.context(IApplicationContext) namespace = '' path = ''
class ManageIpAction(Action): context(IPv4Pool) action('manage') @db.ro_transact(proxy=False) def subject(self, *args, **kwargs): return tuple((self.context, )) def arguments(self): parser = VirtualConsoleArgumentParser() parser.add_argument('-f', '--free', action='store_true', help='Mark IP as free') parser.add_argument('-u', '--use', action='store_true', help='Mark IP as used') parser.add_argument('ip') return parser @require_admins_only_action @defer.inlineCallbacks def execute(self, cmd, args): @db.transact def manage(cmd, args): ip = IPAddress(args.ip) if args.free: self.context.free(ip) elif args.use: self.context.use(ip) yield manage(cmd, args)
class DRest(rest.REST): grok.context(MyContent) def GET(self): self.request.response.setHeader('Content-Type', 'text/plain;charset=utf-8') return "GET2"
class SyncIPUsageAction(Action): context(IPv4Pools) @db.ro_transact def subject(self): return tuple((self.context, )) @defer.inlineCallbacks def execute(self, cmd, args): @db.transact def get_compute_ips(): try: computes = map( follow_symlinks, filter( lambda c: ICompute.providedBy(follow_symlinks(c)), db.get_root()['oms_root']['computes'].listcontent())) pools = db.get_root()['oms_root']['ippools'] for c in computes: ip = IPAddress(c.ipv4_address.split('/')[0]) pool = pools.find_pool(ip) if pool is not None and not pool.get(ip): log.msg('Marking %s as used...' % ip, system='sync-ippool') pool.use(ip) except Exception: log.err(system='sync-ippool') raise yield get_compute_ips()
class Step1(wizard.WizardStep): composed.view(MyWizard) grok.context(Content) ignoreContent = False fields = Fields(IContact).select('name') label = "Step1"
class EventDescription(EventDescriptionBase, grok.Adapter): """Adapter from IEvent to IEventDescription needed by renderer.""" grok.context(icemac.ab.calendar.interfaces.IBaseEvent) grok.implements(IEventDescription) def __init__(self, context): super(EventDescription, self).__init__(context) self.prio = 0 self.whole_day = context.whole_day_event self.special_event = None calendar = icemac.ab.calendar.interfaces.ICalendar(context) # Without the following line we get a ForbidenError for # `__getitem__` when accessing the annotations where # `ICalendarDisplaySettings` are stored. As only authorized users # are able to access this adapter, this is no security hole. unsave_calendar = zope.security.proxy.getObject(calendar) # Making a copy so changing is not possible: self._info_fields = copy.copy( icemac.ab.calendar.interfaces.ICalendarDisplaySettings( unsave_calendar).event_additional_fields) @hyphenated def getText(self, lang=None): return self._text @hyphenated def getInfo(self, lang=None): return self._get_info_from_fields(self._info_fields)
class Traverser(grokcore.traverser.Traverser): grok.context(Herd) def traverse(self, name): if name == 'special': return Special() return None
class TestRecipient(grok.Adapter): """The recipient to test sending a newsletter is pre-populated with the current user's email address (from LDAP), but can be overriden in the session. We need the request for all these things, so we adapt it. But since the workflow form has the newsletter as context which is completely irrelevant for us, we cheat and pretend to be an adapter ourselves (i.e. are callable with a context), but in fact we ignore it. """ grok.context(zeit.cms.browser.interfaces.ICMSLayer) def __init__(self, request): self.request = request def __call__(self, context): return self @property def session(self): return zope.session.interfaces.ISession(self.request) @property def email(self): return self.session[self.__module__].get( 'test-recipient', self.get_email_for_principal()) def get_email_for_principal(self): return self.request.principal.description @email.setter def email(self, value): self.session[self.__module__]['test-recipient'] = value
class OncViewFactory(Adapter): implements(IHttpRestSubViewFactory) context(OncPlugin) def resolve(self, path, request): if request.method.lower() != 'get': raise MethodNotAllowed('Method not allowed', ('GET', )) if path == []: path = ['index.html'] relative_path = os.path.join(*(['../..'] + path)) filename = pkg_resources.resource_filename(__name__, relative_path) if os.path.join(*path) == 'config.js': return OncConfigView(filename) resource = File(filename) if not resource.exists(): return # make sure fonts are servers with a correct mime type resource.contentTypes['.woff'] = 'application/x-font-woff' return OncView(resource)
class TMSRepresentation(grok.Adapter): grok.context(zeit.cms.interfaces.ICMSContent) def __call__(self): result = {} for name, converter in sorted( zope.component.getAdapters( (self.context, ), zeit.retresco.interfaces.ITMSRepresentation)): if not name: # The unnamed adapter is the one which runs all the named # adapters, i.e. this one. continue merge_and_skip_empty(converter(), result) if not self._validate(result): return None return result REQUIRED_FIELDS = ( 'doc_id', 'title', 'teaser', # For completeness, but these cannot be empty with our implementation. 'doc_type', 'url', 'date', ) def _validate(self, data): return all([data.get(x) for x in self.REQUIRED_FIELDS])
class PersonWizard(wizard.Wizard): grok.context(MyContent) def finish(self): print("Finish Action: {0} {1}".format(self.context.surname, self.context.age)) return None
class SaltBase(Adapter): """Base class for all Salt method calls.""" context(ISaltInstalled) baseclass() action = None __executor__ = None # 'sync' and 'async' are left for backwards compatibility with older configs executor_classes = { 'sync': SimpleSaltExecutor, 'async': AsynchronousSaltExecutor, 'simple': SimpleSaltExecutor } @defer.inlineCallbacks def run(self, *args, **kwargs): executor_class = self.__executor__ hostname = yield op.IMinion(self.context).hostname() interaction = db.context(self.context).get('interaction', None) executor = executor_class(hostname, self.action, interaction, timeout=self.timeout) res = yield executor.run(*args, **kwargs) defer.returnValue(res)
class Traverser(grokcore.traverser.Traverser): grok.context(Herd) def traverse(self, name): # we don't really need to do anything here as we want to test # the fallback behaviour pass
class Converter(grok.Adapter): """This adapter works a bit differently: It adapts its context to a separately _configured_ `interface`, and declines if that is not possible; but all adapters are _registered_ for the same basic ICMSContent interface. This way we can retrieve data stored in various DAVPropertyAdapters. """ grok.baseclass() grok.context(zeit.cms.interfaces.ICMSContent) interface = NotImplemented # Subclasses need to register as named adapters to work with # `TMSRepresentation`, e.g. by specifying `grok.name(interface.__name__)` def __new__(cls, context): adapted = cls.interface(context, None) if adapted is None: return None instance = object.__new__(cls) instance.context = adapted instance.content = context return instance def __init__(self, context): pass # self.context has been set by __new__() already. def __call__(self): return {'payload': {}}
class LocalSublocations(grok.Adapter): grok.context(zeit.content.image.interfaces.ILocalImageGroup) grok.implements(zope.location.interfaces.ISublocations) def sublocations(self): return []
class ArticleValidator(zeit.edit.rule.RecursiveValidator, grok.Adapter): grok.context(zeit.content.article.interfaces.IArticle) @property def children(self): return self.context.body.values()
class View(BaseView): baseclass() context(Interface) responseFactory = Response def url(self, obj, name=None, data=None): """This function does something. Args: obj (object): The ILocation providing object. Kwargs: name (str): . data (dict): . Returns: str. """ return compute_url(self.request, obj, name, data) def application_url(self): return self.request.application_url def flash(self, message, type=BASE_MESSAGE_TYPE): return send(message, type=type) def redirect(self, url, code=302): exception = REDIRECTIONS[code] raise exception(url) def namespace(self): ns = super(View, self).namespace() ns.update(h=format_decimal) return ns
class EraseCavePainting(grokcore.view.View): grok.context(zope.interface.Interface) grokcore.security.require(ErasePermission) def render(self): return 'Oops, mistake, let\'s erase it.'
class BaseUrl(component.Adapter): component.context(IRequest) def __init__(self, request): self.request = request def url(self, relativ_path=None): if X_FULL_PATH in self.request.headers: base_url = self.request.headers.get(X_FULL_PATH) else: base_url = self.request.application_url if not base_url.endswith('/'): base_url = '%s/' % base_url # if the publisher take a default utility. we # need rebuild the correct url. appname = urlparse(base_url).path.split('/')[-2:-1][0] if queryUtility(IApplicationContext, name=appname) is None: base_url = '%s%s/' % ( base_url, DEFAULT_EXTJS_APPLICATION, ) if relativ_path is None: return base_url if relativ_path.startswith('/'): relativ_path = relativ_path[1:] return base_url + relativ_path
class CavePainting(grokcore.view.View): grok.context(zope.interface.Interface) grokcore.security.require(ViewPermission) def render(self): return 'What a beautiful painting.'
class EditCavePainting(grokcore.view.View): grok.context(zope.interface.Interface) grokcore.security.require(EditPermission) def render(self): return 'Let\'s make it even prettier.'
class ApproveCavePainting(grokcore.view.View): grok.context(zope.interface.Interface) grokcore.security.require(ApprovePermission) def render(self): return 'Painting owners cannot approve their paintings.'
class NotAllowedREST(grokcore.rest.REST): """Default REST view, whose methods all raise Not Allowed errors. By binding itself to ``Interface``, this becomes the most general available REST view, and will be called into service for objects that have not had more specific REST views registered. This means that such objects can at least return attractive refusals when clients attempt to assail them with unwanted HTTP methods. """ grokcore.view.layer(grokcore.rest.IRESTLayer) grok.context(Interface) is_not_allowed = True def GET(self): raise GrokMethodNotAllowed(self.context, self.request) def POST(self): raise GrokMethodNotAllowed(self.context, self.request) def PUT(self): raise GrokMethodNotAllowed(self.context, self.request) def DELETE(self): raise GrokMethodNotAllowed(self.context, self.request)
>>> home = IHome(hole) >>> IHome.providedBy(home) True >>> isinstance(home, Home) True """ import grokcore.component as grok from zope import interface class ICave(interface.Interface): pass @grok.implementer(ICave) class Cave(grok.Context): pass @grok.implementer(ICave) class Hole(grok.Context): pass grok.context(ICave) class IHome(interface.Interface): pass @grok.implementer(IHome) class Home(grok.Adapter): pass
def meth(self): """We don't allow calling `grok.context` from anything else than a module or a class""" grok.context(Cave)
""" Explicit module-level context for an imported model: >>> grok.testing.grok(__name__) >>> cave = Cave() >>> painting = IPainting(cave) >>> IPainting.providedBy(painting) True >>> isinstance(painting, Painting) True """ import grokcore.component as grok from grokcore.component.tests.adapter.adapter import Cave from zope import interface grok.context(Cave) class IPainting(interface.Interface): pass @grok.implementer(IPainting) class Painting(grok.Adapter): pass
import grokcore.component as grok from zope import interface class Cave(grok.Context): pass class Club(grok.Context): pass grok.context(Cave) grok.context(Club)
class Herd(content.Model): def __init__(self, name): self.name = name def getMammoth(self, name): return Mammoth(name) def traverse(self, name): return self.getMammoth(name) class Mammoth(content.Model): def __init__(self, name): self.name = name grok.context(Mammoth) class Index(view.View): pass index = view.PageTemplate("""\ <html> <body> <h1>Hello, <span tal:replace="context/name/title" />!</h1> <p><span tal:replace="context/name/title" /> is part of <span tal:replace="context/__parent__/name" />.</p> </body> </html> """)