''' msg = MIMEMultipart() msg["From"] = sender msg["To"] = COMMASPACE.join(recipient) # List to String msg["Subject"] = email.Header.Header(subject, 'UTF-8') msg.attach(MIMEText(body.encode('utf-8'), 'plain', 'utf-8')) # Attachment von Dateien if file is not None: fn = file.split("/") fn = fn[-1] part = MIMEBase('application', 'octet-stream') part.set_payload(open(file, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename=%s' % filename or fn) msg.attach(part) mailer = zope.component.getUtility(zope.sendmail.interfaces.IMailDelivery, name=u'uvcsite.maildelivery') mailer.send(sender, recipient, msg.as_string()) grok.global_utility(mailer, provides=zope.sendmail.interfaces.IMailer, name='uvcsite.smtpmailer') grok.global_utility(delivery, zope.sendmail.interfaces.IMailDelivery, name='uvcsite.maildelivery') start_processor_thread()
grok.name('tiny') class IFireplace(interface.Interface): pass class IHome(interface.Interface): pass class Fireplace(object): grok.implements(IFireplace) class Home(object): grok.implements(IFireplace, IHome) grok.global_utility(Fireplace) grok.global_utility(Fireplace, name='hot') grok.global_utility(Home, provides=IHome) grok.global_utility(NightClub, name='cool') grok.global_utility(NightClub, provides=ISpikyClub) grok.global_utility(SmallClub, provides=ITinyClub) grok.global_utility(SmallClub, name='small') grok.global_utility(SmallClub(), name='smallish', direct=True)
from zeam.form.ztk import customize from zope.schema.interfaces import IDate from zeam.form.ztk.widgets.choice import ChoiceField from .interfaces import IAdHocLayer from zope.interface import Interface adhocRegistry = create_components_registry( name="adhocRegistry", bases=(zope.component.globalSiteManager, ), ) grok.global_utility( adhocRegistry, name="adhocRegistry", provides=IComponents, direct=True, ) def setup_pau(PAU): PAU.authenticatorPlugins = ('principals', ) PAU.credentialsPlugins = ( "cookies", "Zope Realm Basic-Auth", "No Challenge if Authenticated") def intid_factory(): return AdHocIdReference(attribute='docid')
""" Subclasses of grok.GlobalUtility that implement more than one interface must specify which interface to use for the registration: >>> grok.testing.grok(__name__) Traceback (most recent call last): ... GrokError: <class 'grok.tests.utility.implementsmany2.Club'> is implementing more than one interface (use grok.provides to specify which one to use). """ import grok from zope import interface class IClub(interface.Interface): pass class ISpikyClub(interface.Interface): pass class Club(object): grok.implements(IClub, ISpikyClub) grok.global_utility(Club)
'foo' >>> factory, provides, name, direct = guis[1] >>> factory <class 'grok.tests.directive.multipletimes.Cave'> >>> provides is None True >>> name u'' """ import grok from zope import interface class IClub(interface.Interface): pass class ICave(interface.Interface): pass class Club(object): grok.implements(IClub) class Cave(object): grok.implements(ICave) grok.global_utility(Club, provides=IClub, name='foo') grok.global_utility(Cave)
hurry.workflow.workflow.Transition( transition_id='publish', title='publish', source=cls.states.CREATED, destination=cls.states.PUBLISHED), hurry.workflow.workflow.Transition( transition_id='progress', title='progress', source=cls.states.CREATED, destination=cls.states.PROGRESS), hurry.workflow.workflow.Transition( transition_id='fix', title='fix', source=cls.states.PROGRESS, destination=cls.states.PUBLISHED), hurry.workflow.workflow.Transition(transition_id='review', title='publish_to_review', source=cls.states.CREATED, destination=cls.states.REVIEW), hurry.workflow.workflow.Transition( transition_id='review_to_publish', title='review to publish', source=cls.states.REVIEW, destination=cls.states.PUBLISHED) ]) grok.global_utility(Workflow.create(), provides=hurry.workflow.interfaces.IWorkflow, direct=True)
import grok class Calculator(grok.GlobalUtility): grok.implements(ICalculator) # if this is not specified, it breaks grok.name('') # this is actually the default grok.provides(ICalculator) # this is actually the default grok.global_utility(factory, provides=IFace, name=u'') class Calculator(grok.LocalUtility): grok.utility_provides(ICalculator) class Anything(grok.Model): pass class NonPersistent(object): pass class SpecialAnything(Anything): pass class Foo(grok.Model, grok.Site): grok.local_utility(Anything, hide=False,
geschlecht = schema.Choice( title=u"Gender", description=u"Bitte geben Sie das Geschlecht ein", source=kk, ) from zope.component.interfaces import IFactory class SimplePerson(uvcsite.Content): uvcsite.schema(ISimplePerson) grok.global_utility(SimplePerson, name='uvcsite.tests.forms.ISimplePerson', direct=True, provides=IFactory) class IAdressen(interface.Interface): personen = schema.List( title=u"Personen", description=u"Bitte tragen Sie alle Personen ein...", value_type=schema.Object(title=u"Person", schema=ISimplePerson), ) class IAdressen1(interface.Interface): personen = schema.Object(title=u"Person", schema=ISimplePerson)
) geschlecht = schema.Choice( title=u"Gender", description=u"Bitte geben Sie das Geschlecht ein", values=('m', 'w'), ) class SimplePerson(uvcsite.Content): uvcsite.schema(ISimplePerson) grok.global_utility( SimplePerson, name='uvcsite.tests.bgvform.ISimplePerson', direct=True, provides=IFactory) class IAdressen(interface.Interface): personen = schema.List( title=u"Personen", description=u"Bitte tragen Sie alle Personen ein...", value_type=schema.Object( title=u"Person", schema=ISimplePerson), )
# [email protected] import grok import uvcsite import zope.app.appsetup.product from dolmen.beaker.utilities import ImmutableDict from dolmen.beaker.interfaces import ISessionConfig config = zope.app.appsetup.product.getProductConfiguration('beaker') if config: CONFIG = ImmutableDict( data_dir=config.get('session.data_dir', None), invalidate_corrupt=True, key=config.get('session.key', 'uvcsite.session.id'), log_file=None, secret=config.get('session.secret', 'DolmenRocks'), timeout=config.get('session.timeout', 600,), type=config.get('session.type', 'cookie'), validate_key=config.get('session.validatekey', 'thisCouldBeChanged') ) grok.global_utility( CONFIG, provides=ISessionConfig, direct=True, )
grok.implements(interfaces.IRulesetContainer) def get_ruleitems(self): """ return all ruleitems in all rulesets """ for ruleset in self.objects(): for item in ruleset.objects(): yield item @grok.subscribe(IMailcone, grok.IApplicationInitializedEvent) def init_rulesets_container(obj, event): obj['rulesets'] = RulesetContainer() class RulesetContainerLocator(bases.BaseLocator): splitedpath = ['rulesets'] grok.global_utility(RulesetContainerLocator, provides=interfaces.IRulesetContainerLocator) class BaseRuleItem(grok.Model): grok.baseclass() grok.implements(interfaces.IRuleItem) position = PersistentDict() overrides = PersistentDict() identifer = PersistentDict() _v_customer = None def __getattribute__(self, attr): """ proxy to get the overrides of a customer. to set the
logger = logging.getLogger('raptus.mailcone.mails') class MailContainer(bases.QueryContainer): grok.implements(interfaces.IMailContainer) def query(self): return self.session.query(Mail) @grok.subscribe(IMailcone, grok.IApplicationInitializedEvent) def init_mails_container(obj, event): obj['mails'] = MailContainer() class MailContainerLocator(bases.BaseLocator): splitedpath = ['mails'] grok.global_utility(MailContainerLocator, provides=interfaces.IMailContainerLocator) class Attachment(bases.ORMModel): grok.implements(interfaces.IAttachment) database.schema(interfaces.IAttachment) rdb.metadata(database.create_metadata) rdb.tablename('attachments') id = Column(BigInteger, primary_key=True) mail_id = Column(BigInteger, ForeignKey('mails.id', ondelete='CASCADE')) class Tag(bases.ORMModel):
import mars.view import mars.form from tfws.website import interfaces from tfws.website import authentication from tfws.website import permissions from tfws.website import roles from tfws.website import members from tfws.website.catalog import setup_catalog from tfws.website.layer import IWebSiteLayer from tfws.website.i18n import MessageFactory as _ mars.layer.layer(IWebSiteLayer) grok.global_utility(PersistentSessionDataContainer, ISessionDataContainer, name='') class WebSite(grok.Application, grok.Container): """Mars/Grok/Z3C demo website """ zope.interface.implements(interfaces.IWebSite) grok.local_utility(IntIds, IIntIds) # needed for the catalog grok.local_utility(Catalog, ICatalog, setup=setup_catalog, name_in_container='wcatalog') grok.local_utility(SimpleAuthentication, IAuthentication,
@grok.subscribe(IMailcone, grok.IApplicationInitializedEvent) def init_smtp_container(obj, event): obj['settings']['smtp'] = SMPTSettings() register = vocabulary.getVocabularyRegistry().register def vocabulary_smtp(context): terms = list() terms.append(vocabulary.SimpleTerm(value=smtplib.SMTP, token='smtp', title=_('SMTP'))) terms.append(vocabulary.SimpleTerm(value=smtplib.SMTP_SSL, token='smtp_ssl', title=_('SMTP SSL'))) terms.append(vocabulary.SimpleTerm(value=smtplib.LMTP, token='lmtp', title=_('LMTP'))) return vocabulary.SimpleVocabulary(terms) register('raptus.mailcone.settings.smtp', vocabulary_smtp) class SMTPLocator(bases.BaseLocator): splitedpath = ['settings','smtp'] grok.global_utility(SMTPLocator, provides=interfaces.ISMTPLocator) class LogoSettings(bases.Container): grok.implements(interfaces.ILogoSettings) grok.traversable('image') image = None @grok.subscribe(IMailcone, grok.IApplicationInitializedEvent) def init_logo_container(obj, event): obj['settings']['logo'] = LogoSettings()
>>> provides is None True >>> name u'' """ import grok from zope import interface class IClub(interface.Interface): pass class ICave(interface.Interface): pass class Club(object): grok.implements(IClub) class Cave(object): grok.implements(ICave) grok.global_utility(Club, provides=IClub, name='foo') grok.global_utility(Cave)
class FolderIndexSource(object): """A source of items in a folder.""" def __call__(self, context): result = [] for key in context.values(): item = context[key] term = zope.schema.vocabulary.SimpleTerm(item, token=item.title) result.append(term) return zope.schema.vocabulary.SimpleVocabulary(result) grok.global_utility(FolderIndexSource, provides=zope.schema.interfaces.IVocabularyFactory, name=u'Folder Index Source') @grok.subscribe(interfaces.IPage, grok.IObjectCopiedEvent) def removeFolderIndexOnCopiedObject(item, event): """Remove IFolderIndex on copied objects. This handler removes the IFolderIndex from a copied object after copy/paste. This is needed for clean up copied objects because we can't have more the one object marked with IFolderIndex. """ if interfaces.IFolderIndex.providedBy(item): zope.interface.directlyProvides( item,
class ClubMaker(grok.GlobalUtility): grok.implements(IClub) interface.classProvides(IClubMaker) grok.direct() grok.name('maker') class IFireplace(interface.Interface): pass class IHome(interface.Interface): pass class Fireplace(object): grok.implements(IFireplace) class Home(object): grok.implements(IFireplace, IHome) grok.global_utility(Fireplace) grok.global_utility(Fireplace, name='hot') grok.global_utility(Home, provides=IHome) grok.global_utility(NightClub, name='cool') grok.global_utility(NightClub, provides=ISpikyClub) grok.global_utility(SmallClub, provides=ITinyClub) grok.global_utility(SmallClub, name='small') grok.global_utility(SmallClub(), name='smallish', direct=True)
# -*- coding: utf-8 -*- # Copyright (c) 2007-2011 NovaReto GmbH # [email protected] import grok from zope.generations.generations import SchemaManager from zope.generations.interfaces import ISchemaManager UVCSchemaManager = SchemaManager( minimum_generation = 1, generation = 2, package_name = __name__ ) grok.global_utility( UVCSchemaManager, provides=ISchemaManager, name="uvcsite", direct=True )
workflow.Transition(transition_id='reply', title='Reply', source=MessageState.read, destination=MessageState.replied), workflow.Transition(transition_id='progress', title='Progress', source=MessageState.sent, destination=MessageState.progress), workflow.Transition(transition_id='finish', title='Finish', source=MessageState.sent, destination=MessageState.finish) ]) grok.global_utility(MessageWorkflow, provides=workflow.IWorkflow, name="message", direct=True) class WorkflowState(workflow.WorkflowState, grok.Adapter): grok.context(uvc.letterbasket.interfaces.IMessage) grok.provides(workflow.IWorkflowState) grok.name('message') class WorkflowInfo(workflow.WorkflowInfo, grok.Adapter): grok.context(uvc.letterbasket.interfaces.IMessage) grok.provides(workflow.IWorkflowInfo) name = "message"
def setup_pau(PAU): PAU.authenticatorPlugins = ('principals', ) PAU.credentialsPlugins = ("cookies", "Zope Realm Basic-Auth", "No Challenge if Authenticated",) uvcsiteRegistry = create_components_registry( name="uvcsiteRegistry", bases=(zope.component.globalSiteManager, ), ) grok.global_utility( uvcsiteRegistry, name="uvcsiteRegistry", provides=IComponents, direct=True) @implementer(uvcsite.IUVCSite) class Uvcsite(grok.Application, grok.Container): """Application Object for uvc.site """ grok.traversable('plugins') grok.local_utility(PortalMembership, provides=IHomeFolderManager) grok.local_utility(UVCAuthenticator, name=u"principals",
return data overrides = dict() rules = component.getUtility(IRulesetContainerLocator)().get_ruleitems() for rule in rules: if id is not rule.id: continue for k, v in rule.overrides.iteritems(): if v: overrides[k] = getattr(rule, k) overrides.update(data) return overrides def set_ruleset_data(self, id, data): self.ruleset_data.update({id:data}) self._p_changed = 1 class CustomerContainer(bases.Container): grok.implements(interfaces.ICustomersContainer) @grok.subscribe(IMailcone, grok.IApplicationInitializedEvent) def init_customers_container(obj, event): obj['customers'] = CustomerContainer() class CustomersContainerLocator(bases.BaseLocator): splitedpath = ['customers'] grok.global_utility(CustomersContainerLocator, provides=interfaces.ICustomersContainerLocator)
"Zope Realm Basic-Auth", "No Challenge if Authenticated", ) grok.local_utility(PluggableAuthentication, IAuthentication, public=True, setup=setup_pau) crypto_keys = CryptographicKeys( pkg_resources.resource_filename("uvc.rest", "tests/fixtures/keys"), [ "novareto", ]) grok.global_utility(crypto_keys, direct=True) def http_method_resolve(inst, request): httpmethod = request.method.upper() method = getattr(inst, httpmethod, None) if method is not None: return method raise NotImplementedError("`%s` method has no bound resolver." % httpmethod) class RestService(RESTAdapter): grok.context(MyAuthApp) grok.name("service")
job.status = old if old == CRONJOB: job.status = CRONJOB return return_value @grok.subscribe(interfaces.ICronJob, grok.IObjectModifiedEvent) def cronjob_modified_event(obj, event): container = component.getUtility(interfaces.ICronJobContainerLocator)() container.reschedule(obj.__name__) class CronJobContainerLocator(bases.BaseLocator): splitedpath = ['cronjobs'] grok.global_utility(CronJobContainerLocator, provides=interfaces.ICronJobContainerLocator) @grok.subscribe(IDatabaseOpenedWithRoot) def database_opened_cronjobs(event): # so we don't need to add some configuration in zope.conf from zope.app.appsetup.product import setProductConfiguration db = event.database connection = db.open() root = connection.root() root_folder = root.get(ZopePublication.root_name, None) for app in root_folder.values(): if IMailcone.providedBy(app): name = 'z3c.taskqueue@%s' % app.__name__ site = '%s@*'%app.__name__
# once in our integration framework, after which we can just import # Session Session = scoped_session(session_factory, scopefunc) class IEngine(Interface): """The database engine. """ # we register the available engines as global utilities. # we want to be able to configure the engines, preferably also through # the UI. This might mean we need to register the engine as a local, # non-persistent utility that is somehow recreated on each restart. engine1 = create_engine('postgres:///experiment', convert_unicode=True) grok.global_utility(engine1, provides=IEngine, direct=True, name='engine1') engine2 = create_engine('postgres:///experiment2', convert_unicode=True) grok.global_utility(engine2, provides=IEngine, direct=True, name='engine2') # an application that allows the configuration of the engine name class IForm(Interface): engine_name = schema.TextLine(title=u"Engine name") class App(grok.Application, grok.Container): grok.local_utility(Database, provides=IDatabase, public=True, name_in_container='database')
from raptus.mailcone.persistentlog import interfaces class Log(File, bases.Container): grok.implements(interfaces.ILog) log_from = FieldProperty(interfaces.ILog["log_from"]) log_to = FieldProperty(interfaces.ILog["log_to"]) category = FieldProperty(interfaces.ILog["category"]) has_errors = FieldProperty(interfaces.ILog["has_errors"]) def __init__(self): bases.Container.__init__(self) super(Log, self).__init__() class LogContainer(bases.Container): grok.implements(interfaces.ILogContainer) @grok.subscribe(IMailcone, grok.IApplicationInitializedEvent) def init_logs_container(obj, event): obj["cronjob_logs"] = LogContainer() class LogContainerLocator(bases.BaseLocator): splitedpath = ["cronjob_logs"] grok.global_utility(LogContainerLocator, provides=interfaces.ILogContainerLocator)
class ProcessRulesTask(object): grok.implements(ITask) name = _('Process Rules') inputSchema = FieldProperty(ITask['inputSchema']) outputSchema = FieldProperty(ITask['outputSchema']) def __call__(self, service, jobid, input): process() return 'rules processed' grok.global_utility(ProcessRulesTask, name='raptus.mailcone.cronjob.process_rules_task') mcu_logger = logging.getLogger('raptus.mailcone.cronjob.cleanup') mcu_handler = PersistentLogHandler(u'cronjob: mail cleanup', ILogContainerLocator) mcu_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s')) mcu_handler.setLevel(0) mcu_logger.addHandler(mcu_handler) class CleanupMails7Days(object): grok.implements(ITask) delay = 7
name = schema.TextLine(title=u"Name", required=True, description=u"Bitte geben Sie hier den Namen ein") vorname = schema.Int(title=u"Vorname", description=u"Bitte geben Sie den Vornamen ein") geschlecht = schema.Choice(title=u"Gender", description=u"Bitte geben Sie das Geschlecht ein", source=kk) from zope.component.interfaces import IFactory class SimplePerson(uvcsite.Content): uvcsite.schema(ISimplePerson) grok.global_utility(SimplePerson, name="uvcsite.tests.forms.ISimplePerson", direct=True, provides=IFactory) class IAdressen(interface.Interface): personen = schema.List( title=u"Personen", description=u"Bitte tragen Sie alle Personen ein...", value_type=schema.Object(title=u"Person", schema=ISimplePerson), ) class IAdressen1(interface.Interface): personen = schema.Object(title=u"Person", schema=ISimplePerson)
txt = MIMEText(text, 'plain', 'utf-8') msg.attach(txt) for f in files: part = MIMEBase('application', "octet-stream") with open(f, 'rb') as fd: part.set_payload(fd.read()) Encoders.encode_base64(part) part.add_header( 'Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f)) msg.attach(part) mailer = zope.component.getUtility( zope.sendmail.interfaces.IMailDelivery, name=u'flg.maildelivery' ) print "I SEND THE MAIL VIA THE MAILER" mailer.send(send_from, send_to, msg.as_string()) grok.global_utility( mailer, provides=zope.sendmail.interfaces.IMailer, name='flg.smtpmailer') grok.global_utility( delivery, zope.sendmail.interfaces.IMailDelivery, name='flg.maildelivery') start_processor_thread()
destination=REVIEW) review_to_publish = workflow.Transition( transition_id='review_to_publish', title='review to publish', source=REVIEW, destination=PUBLISHED) return workflow.Workflow([create_transition, progress_transition, fix_transition, review, review_to_publish, publish_transition]) grok.global_utility(create_workflow, provides=IWorkflow) # Workflow States class WorkflowState(workflow.WorkflowState, grok.Adapter): grok.context(IContent) grok.provides(IWorkflowState) # Workflow Info class WorkflowInfo(workflow.WorkflowInfo, grok.Adapter): grok.context(IContent) grok.provides(IWorkflowInfo)
# -*- coding: utf-8 -*- # Copyright (c) 2007-2013 NovaReto GmbH # [email protected] import grok from fernlehrgang import log from z3c.saconfig import EngineFactory, GloballyScopedSession from zope.app.appsetup.product import getProductConfiguration config = getProductConfiguration('database') try: DSN = config['dsn'] except: DSN = "postgresql+psycopg2://flg:flg@localhost/flg" log(DSN) print DSN # FIX: engine_factory = EngineFactory(DSN, convert_unicode=True, encoding='utf-8', optimize_limits=True, echo=False) engine_factory = EngineFactory( DSN, convert_unicode=True, encoding='iso-8859-15', echo=False) scoped_session = GloballyScopedSession() grok.global_utility(engine_factory, direct=True) grok.global_utility(scoped_session, direct=True)
# [email protected] import os import grok from z3c.saconfig import EngineFactory, GloballyScopedSession from sqlalchemy import Table, MetaData from zope.app.appsetup.product import getProductConfiguration config = getProductConfiguration('database') DSN = config['dsn'] SCHEMA = config.get('schema', 'EDUCUSADAT') engine_factory = EngineFactory(DSN, echo=False) scoped_session = GloballyScopedSession() grok.global_utility(engine_factory, direct=True) grok.global_utility(scoped_session, direct=True) engine = engine_factory() metadata = MetaData(bind=engine) if os.environ.get('ADHOC_TEST') == "True": c1unf1aa = None c1prs1aa = None avika1aa = None zczve1aa = None zckto1aa = None z1vrs1aa = None z1vrs2aa = None else: c1unf1aa = Table(config['c1unf1aa'],
import grok from sqlalchemy import Column, ForeignKey from sqlalchemy.types import Integer, String from sqlalchemy.orm import relation from megrok import rdb from z3c.saconfig import EngineFactory, GloballyScopedSession from z3c.saconfig.interfaces import (IEngineFactory, IScopedSession, IEngineCreatedEvent) TEST_DSN = 'sqlite:///:memory:' metadata = rdb.MetaData() engine_factory = EngineFactory(TEST_DSN) scoped_session = GloballyScopedSession() grok.global_utility(engine_factory, provides=IEngineFactory, direct=True) grok.global_utility(scoped_session, provides=IScopedSession, direct=True) class Example(grok.Application, grok.Container): pass class Index(grok.View): grok.context(Example) pass # see app_templates/index.pt class Cursos(rdb.Container): pass class Departamento(rdb.Model): rdb.metadata(metadata)
title='publish_to_review', source=CREATED, destination=REVIEW) review_to_publish = workflow.Transition(transition_id='review_to_publish', title='review to publish', source=REVIEW, destination=PUBLISHED) return workflow.Workflow([ create_transition, progress_transition, fix_transition, review, review_to_publish, publish_transition ]) grok.global_utility(create_workflow, provides=IWorkflow) # Workflow States class WorkflowState(workflow.WorkflowState, grok.Adapter): grok.context(IContent) grok.provides(IWorkflowState) # Workflow Info class WorkflowInfo(workflow.WorkflowInfo, grok.Adapter): grok.context(IContent) grok.provides(IWorkflowInfo)
import grok class Calculator(grok.GlobalUtility): grok.implements(ICalculator) # if this is not specified, it breaks grok.name('') # this is actually the default grok.provides(ICalculator) # this is actually the default grok.global_utility(factory, provides=IFace, name=u'') class Calculator(grok.LocalUtility): grok.utility_provides(ICalculator) class Anything(grok.Model): pass class NonPersistent(object): pass class SpecialAnything(Anything): pass class Foo(grok.Model, grok.Site): grok.local_utility(Anything, hide=False, name_in_container='foo', persistent=None) grok.local_adapter() grok.local_view() class Foo2(Foo): grok.local_utility(SpecialAnything)