def typeMap(self): tm = {} ps = self.TYPES_NS api = self.API for k in self.supportedTypes: c = importObject(ps.get(k, NullConverter)) for v in getattr(api, k).values: v = api.Type(v) # needed to get usable typemap keys tm[v] = importObject(ps.get(PropertyName.fromString(v), c)) return tm
def interpret(self, filename): """Interpret file as an '.ini' and run the command it specifies""" try: factory = config.getStreamFactory(self, filename) except protocols.AdaptationFailure: raise InvocationError("Not a valid file/stream source: " + filename) else: if not factory.exists(): raise InvocationError("File/stream does not exist: " + filename) cfg = config.ServiceArea(self.getCommandParent()) config.loadConfigFile(cfg, factory) # Set up a command factory based on the configuration setting executable = importObject(config.lookup(cfg, 'peak.running.app', None)) if executable is None: raise InvocationError("%s doesn't specify a 'peak.running.app'" % filename) # Now create and return the subcommand return self.getSubcommand(executable, parentComponent=cfg)
def internalize(klass, format, stream, **options): internalize = importObject(_readers.of(klass).get(format)) if internalize is None: raise FormatNotSupported(format) from peak.metamodels import MOF131 return internalize(MOF131, klass, format, stream, **options)
def externalize(self, format='peak.model', **options): externalize = importObject(_writers.of(self).get(format)) if externalize is None: raise FormatNotSupported(format) from peak.metamodels import MOF131 return externalize(MOF131, self, format, **options)
def typeMap(self): tm = {} ps = self.TYPES_NS api = self.API for k in self.supportedTypes: tm[getattr(api, k)] = importObject(ps.get(k, NullConverter)) return tm
def typeMap(self): tm = {} ps = self.TYPES_NS api = self.API for k in self.supportedTypes: c = importObject(ps.get(k, NullConverter)) tob = getattr(api, k, getattr(self, k, None)) tob = getattr(tob, 'values', tob) try: iter(tob) except TypeError: tob = [tob] for v in tob: try: v + '' except: if v not in tm or tm[v] is NullConverter: tm[v] = c else: # We support either '.int4' or '.INTEGER' style properties tm[v] = importObject(ps.get(PropertyName.fromString(v), c)) return tm
def makePart(self, directive): args = tokenize(directive) partName = args.pop(0) if args: typeName = PropertyName.fromString(args.pop(0).lower()) else: typeName = 'digit' factory = importObject(PART_FACTORIES.of(self).get(typeName, None)) if factory is None: raise ValueError("Unrecognized part kind %r in %r" % (typeName, directive)) return factory(self, name=partName, args=args, cmd=directive)
def makeFormat(self, name, directive): args = tokenize(directive) format = args[0] if format != unquote(format): format = 'string' else: args.pop(0) format = PropertyName.fromString(format.lower()) factory = importObject(FORMAT_FACTORIES.of(self).get(format, None)) if factory is None: raise ValueError( "Unrecognized format kind %r in %r for format %r" % (format, directive, name)) return factory(self, name=name, args=args, cmd=directive)
def getURLContext(parent, scheme, iface, componentName=None, **options): """Return a context object for the given URL scheme and interface This is done by looking up 'scheme' in the 'peak.naming.schemes.*' property namespace. (That is, the '"ldap:"' URL scheme is retrieved from the 'peak.naming.schemes.ldap' property. Per RFC 1738, the lowercase form of the scheme name is always used; note that the '":"' should not be included in the scheme name.) The property value found, if a string, will be treated as an import specification, and the relevant object imported. The property value or imported object must do one of the following: * Implement 'naming.IURLContextFactory', in which case its 'getURLContext()' method will be called with the same arguments as supplied to this function. * Be a class whose instances implement the requested context interface (e.g. 'naming.IBasicContext'), in which case an instance will be constructed and returned, using 'parent' as its parent component, and 'componentName' as its name. (Note that the class must also implement the 'binding.IComponentFactory' constructor signature for this to work.) * Be a class whose instances implement 'naming.IAddress', in which case a generic 'AddressContext' will be returned, with its 'schemeParser' set to the appropriate address class. If none of these conditions apply, or the property isn't found in the first place, this function returns 'None', as per the 'naming.IURLContextFactory' interface. """ factory = SCHEMES_PREFIX.of(parent).get(scheme.lower()) if factory is None: return None factory = adapt(importObject(factory), IURLContextFactory, None) if factory is not None: return factory.getURLContext(parent, scheme, iface, componentName, **options) return None
def add_section(self, section, lines, lineInfo): if section is None: section = '*' section = section.strip() s = ' '.join(section.lower().split()) if ' ' in s: pn = PropertyName.fromString(s.replace(' ', '.')) func = importObject(SECTION_PARSERS.of(self.pMap).get(pn)) if func is None: raise SyntaxError(("Invalid section type", section, lineInfo)) handler = lambda *args: func(self, *args) else: section = self.prefix + PropertyName(section).asPrefix() handler = self.add_setting self.process_settings(section, lines, handler)
def getInitialContext(parentComponent, componentName=None, **options): """Create initial context for parent, w/component name and options The type of initial context created is determined by asking the supplied 'parentComponent' for its 'peak.naming.initialContextFactory' property, which will be treated as an import string if it is of string type. (Note: the property name used is available as the constant 'naming.INIT_CTX_FACTORY', if you want to provide an attribute binding for it.) Keyword options and the component name desired for the initial context are passed through to the actual factory, along with the parent component and component name. If a 'creationParent' argument is not supplied, it will be defaulted to 'parentComponent', in order to establish the parent component for any newly created objects retrieved from the resulting context object. """ factory = importObject(INIT_CTX_FACTORY(parentComponent)) options.setdefault('creationParent', parentComponent) return factory(parentComponent, componentName, **options)
def restore(self, context, name): factory = importObject(FACTORY_PREFIX.of(context)[self.factoryName]) factory = adapt(factory, IObjectFactory) return factory.getObjectInstance(context, self, name)
def getConverter(field): return importObject(schema.get(field, NullConverter), globals())
class SQLConnection(ManagedConnection): protocols.advise(instancesProvide=[ISQLConnection]) def commitTransaction(self, txnService): self.connection.commit() def abortTransaction(self, txnService): self.closeCursors() self.connection.rollback() cursorClass = SQLCursor DRIVER = binding.Require("DBAPI module name") # Replace in subclasses API = binding.Make(lambda self: importObject(self.DRIVER)) Error = \ Warning = \ NotSupportedError = \ Date = \ Time = \ Binary = \ Timestamp = \ DateFromTicks = \ TimeFromTicks = \ TimestampFromTicks = binding.Delegate("API") Exceptions = binding.Obtain(["Error", "Warning"]) supportedTypes = 'STRING', 'BINARY', 'NUMBER', 'DATETIME', 'ROWID' TYPES_NS = binding.Make( lambda self: config.Namespace('%s.sql_types' % self.DRIVER)) appConfig = binding.Make( lambda self: config.Namespace('%s.appConfig' % self.DRIVER)) twoPhaseProp = binding.Make( lambda self: PropertyName(self.DRIVER + '.twoPhaseCommit')) serialProp = binding.Make( lambda self: PropertyName(self.DRIVER + '.serializable')) twoPhase = binding.Obtain(naming.Indirect('twoPhaseProp'), default=False) serializable = binding.Obtain(naming.Indirect('serialProp'), default=False) log = binding.Obtain('logger:sql') def voteForCommit(self, txnService): super(SQLConnection, self).voteForCommit(txnService) if self.twoPhase: self._prepare() def typeMap(self): tm = {} ps = self.TYPES_NS api = self.API for k in self.supportedTypes: tm[getattr(api, k)] = importObject(ps.get(k, NullConverter)) return tm typeMap = binding.Make(typeMap) def _prepare(self): raise NotImplementedError("Two-phase commit not implemented", self) newParams = binding.Make( lambda s: s.TYPES_NS['paramstyles.' + s.API.paramstyle]) addParam = binding.Make( lambda s: s.TYPES_NS['paramadders.' + s.API.paramstyle]) def getRowConverter(self, description, post=None): """See ISQLConnection.getRowConverter()""" typeMap = self.typeMap converters = [ instancemethod(typeMap.get(d[1], NullConverter), d, None) for d in description ] for conv in converters: if conv.im_func is not NullConverter: # At least one conversion, so we must create a row converter if post is None: return lambda row: [ conv(col) for (col, conv) in zip(row, converters) ] else: return lambda row: post( [conv(col) for (col, conv) in zip(row, converters)]) else: return post # No conversions other than postprocessor dbTxnStarted = True txnAttrs = ManagedConnection.txnAttrs + ('dbTxnStarted', ) def setTxnState(self, outsideTxn): self.joinedTxn # ALWAYS join the PEAK transaction if outsideTxn: if self.dbTxnStarted: raise exceptions.TransactionInProgress( """Database connection already has an active transaction""" ) elif outsideTxn is not None: if not self.dbTxnStarted: self.dbTxnStarted = self._startDBTxn() def _startDBTxn(self): raise NotImplementedError("DB doesn't support explicit transactions")
def do_include(parser, section, name, value, lineInfo): propertyMap = parser.pMap loader = importObject(CONFIG_LOADERS.of(propertyMap)[name]) eval("loader(propertyMap,%s,includedFrom=parser)" % value, parser.globalDict, locals())