Python twisted.python.reflect.namedClass() Examples

The following are 28 code examples of twisted.python.reflect.namedClass(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module twisted.python.reflect , or try the search function .
Example #1
Source File: conduit.py    From ccs-calendarserver with Apache License 2.0 6 votes vote down vote up
def sendRequestToServer(
        self, txn, server, data, stream=None, streamType=None, writeStream=None
    ):
        request = self.conduitRequestClass(
            server, data, stream, streamType, writeStream
        )

        try:
            response = (yield request.doRequest(txn))
        except Exception as e:
            raise FailedCrossPodRequestError(
                "Failed cross-pod request: {}".format(e)
            )

        if response["result"] == "exception":
            raise namedClass(response["class"])(response["details"])
        elif response["result"] != "ok":
            raise FailedCrossPodRequestError(
                "Cross-pod request failed: {}".format(response)
            )
        else:
            returnValue(response.get("value")) 
Example #2
Source File: caldav.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def serviceMakerProperty(propname):
    def getProperty(self):
        return getattr(reflect.namedClass(self.serviceMakerClass), propname)

    return property(getProperty) 
Example #3
Source File: test_reflect.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def testClassLookup(self):
        self.assertEquals(reflect.namedClass("twisted.python.reflect.Summer"), reflect.Summer) 
Example #4
Source File: test_persisted.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def unjellyFromDOM_1(self, unjellier, element):
            from twisted.python.reflect import namedClass
            self.integer = int(element.getAttribute("integer"))
            self.instance = namedClass(element.getAttribute("instance"))()
            self.name = element.getAttribute("name")
            # just give us any ol' list
            self.sequence = [self.instance, self.instance] 
Example #5
Source File: stdio.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def main(argv=None):
    log.startLogging(file('child.log', 'w'))

    if argv is None:
        argv = sys.argv[1:]
    if argv:
        klass = reflect.namedClass(argv[0])
    else:
        klass = ConsoleManhole
    runWithProtocol(klass) 
Example #6
Source File: tap.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def opt_class(self, className):
        """Create a Resource subclass with a zero-argument constructor.
        """
        classObj = reflect.namedClass(className)
        self['root'] = classObj() 
Example #7
Source File: tap.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def opt_processor(self, proc):
        """`ext=class' where `class' is added as a Processor for files ending
        with `ext'.
        """
        if not isinstance(self['root'], static.File):
            raise usage.UsageError("You can only use --processor after --path.")
        ext, klass = proc.split('=', 1)
        self['root'].processors[ext] = reflect.namedClass(klass) 
Example #8
Source File: test_reflect.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_namedClassLookup(self):
        """
        L{namedClass} should return the class object for the name it is passed.
        """
        self.assertIdentical(
            reflect.namedClass("twisted.python.reflect.Summer"),
            reflect.Summer) 
Example #9
Source File: stdio.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def main(argv=None):
    log.startLogging(file('child.log', 'w'))

    if argv is None:
        argv = sys.argv[1:]
    if argv:
        klass = reflect.namedClass(argv[0])
    else:
        klass = ConsoleManhole
    runWithProtocol(klass) 
Example #10
Source File: tap.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def opt_class(self, className):
        """
        Create a Resource subclass with a zero-argument constructor.
        """
        classObj = reflect.namedClass(className)
        self['root'] = classObj() 
Example #11
Source File: tap.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def opt_processor(self, proc):
        """
        `ext=class' where `class' is added as a Processor for files ending
        with `ext'.
        """
        if not isinstance(self['root'], static.File):
            raise usage.UsageError("You can only use --processor after --path.")
        ext, klass = proc.split('=', 1)
        self['root'].processors[ext] = reflect.namedClass(klass) 
Example #12
Source File: service.py    From landscape-client with GNU General Public License v2.0 5 votes vote down vote up
def get_plugins(self):
        return [namedClass("landscape.client.monitor.%s.%s"
                           % (plugin_name.lower(), plugin_name))()
                for plugin_name in self.config.plugin_factories] 
Example #13
Source File: service.py    From landscape-client with GNU General Public License v2.0 5 votes vote down vote up
def get_plugins(self):
        """Return instances of all the plugins enabled in the configuration."""
        return [namedClass("landscape.client.manager.%s.%s"
                           % (plugin_name.lower(), plugin_name))()
                for plugin_name in self.config.plugin_factories] 
Example #14
Source File: deployment.py    From landscape-client with GNU General Public License v2.0 5 votes vote down vote up
def get_plugins(self):
        if self.sysinfo_plugins is None:
            include = ALL_PLUGINS
        else:
            include = self.get_plugin_names(self.sysinfo_plugins)
        if self.exclude_sysinfo_plugins is None:
            exclude = []
        else:
            exclude = self.get_plugin_names(self.exclude_sysinfo_plugins)
        plugins = [x for x in include if x not in exclude]
        return [namedClass("landscape.sysinfo.%s.%s"
                           % (plugin_name.lower(), plugin_name))()
                for plugin_name in plugins] 
Example #15
Source File: caldav.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def makeService(self, options):
        if self._serviceMaker is None:
            self._serviceMaker = reflect.namedClass(self.serviceMakerClass)()

        return self._serviceMaker.makeService(options) 
Example #16
Source File: tap.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def opt_processor(self, proc):
        """
        `ext=class' where `class' is added as a Processor for files ending
        with `ext'.
        """
        if not isinstance(self['root'], static.File):
            raise usage.UsageError(
                "You can only use --processor after --path.")
        ext, klass = proc.split('=', 1)
        self['root'].processors[ext] = reflect.namedClass(klass) 
Example #17
Source File: upgrade.py    From ccs-calendarserver with Apache License 2.0 5 votes vote down vote up
def migrateAutoSchedule(config, directory):
    # Fetch the autoSchedule assignments from resourceinfo.sqlite and store
    # the values in augments
    augmentService = None
    serviceClass = {
        "xml": "twistedcaldav.directory.augment.AugmentXMLDB",
    }
    augmentClass = namedClass(serviceClass[config.AugmentService.type])
    try:
        augmentService = augmentClass(**config.AugmentService.params)
    except:
        log.error("Could not start augment service")

    if augmentService:
        augmentRecords = []
        dbPath = os.path.join(config.DataRoot, ResourceInfoDatabase.dbFilename)
        if os.path.exists(dbPath):
            log.warn("Migrating auto-schedule settings")
            resourceInfoDatabase = ResourceInfoDatabase(config.DataRoot)
            results = resourceInfoDatabase._db_execute(
                "select GUID, AUTOSCHEDULE from RESOURCEINFO"
            )
            for uid, autoSchedule in results:
                if uid is not None:
                    record = yield directory.recordWithUID(uid)
                    if record is not None:
                        augmentRecord = (
                            yield augmentService.getAugmentRecord(
                                uid,
                                directory.recordTypeToOldName(record.recordType)
                            )
                        )
                        augmentRecord.autoScheduleMode = (
                            "automatic" if autoSchedule else "default"
                        )
                        augmentRecords.append(augmentRecord)

            if augmentRecords:
                yield augmentService.addAugmentRecords(augmentRecords)
            log.warn("Migrated {len} auto-schedule settings", len=len(augmentRecords)) 
Example #18
Source File: test_reflect.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_namedClassLookup(self):
        """
        L{namedClass} should return the class object for the name it is passed.
        """
        self.assertIs(
            reflect.namedClass("twisted.test.test_reflect.Summer"),
            Summer) 
Example #19
Source File: stdio.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def main(argv=None):
    log.startLogging(open('child.log', 'w'))

    if argv is None:
        argv = sys.argv[1:]
    if argv:
        klass = reflect.namedClass(argv[0])
    else:
        klass = ConsoleManhole
    runWithProtocol(klass) 
Example #20
Source File: tap.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def opt_class(self, className):
        """
        Create a Resource subclass with a zero-argument constructor.
        """
        classObj = reflect.namedClass(className)
        self['root'] = classObj() 
Example #21
Source File: tap.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def opt_processor(self, proc):
        """
        `ext=class' where `class' is added as a Processor for files ending
        with `ext'.
        """
        if not isinstance(self['root'], static.File):
            raise usage.UsageError(
                "You can only use --processor after --path.")
        ext, klass = proc.split('=', 1)
        self['root'].processors[ext] = reflect.namedClass(klass) 
Example #22
Source File: masterchild.py    From ccs-twistedextensions with Apache License 2.0 5 votes vote down vote up
def wrappedServiceMaker(self):
        if not hasattr(self, "_wrappedServiceMaker"):
            makerClass = namedClass(self.className)
            maker = makerClass(*self.args, **self.kwargs)
            self._wrappedServiceMaker = maker

        return self._wrappedServiceMaker 
Example #23
Source File: masterchild.py    From ccs-twistedextensions with Apache License 2.0 5 votes vote down vote up
def opt_protocol(self, value):
        """
        Protocol
        """
        try:
            protocol = namedClass(value)
        except (ValueError, AttributeError):
            raise UsageError("Unknown protocol: {0}".format(value))

        self["protocol"] = protocol 
Example #24
Source File: test_reflect.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_namedClassLookup(self):
        """
        L{namedClass} should return the class object for the name it is passed.
        """
        self.assertIs(
            reflect.namedClass("twisted.test.test_reflect.Summer"),
            Summer) 
Example #25
Source File: stdio.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def main(argv=None):
    log.startLogging(open('child.log', 'w'))

    if argv is None:
        argv = sys.argv[1:]
    if argv:
        klass = reflect.namedClass(argv[0])
    else:
        klass = ConsoleManhole
    runWithProtocol(klass) 
Example #26
Source File: tap.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def opt_class(self, className):
        """
        Create a Resource subclass with a zero-argument constructor.
        """
        classObj = reflect.namedClass(className)
        self['root'] = classObj() 
Example #27
Source File: test_upgrade.py    From ccs-calendarserver with Apache License 2.0 4 votes vote down vote up
def test_migrateAutoSchedule(self):

        self.patch(config.AugmentService, "params", {"xmlFiles": ["augments.xml"]})
        serviceClass = {
            "xml": "twistedcaldav.directory.augment.AugmentXMLDB",
        }
        augmentClass = namedClass(serviceClass[config.AugmentService.type])

        # Auto-schedule not currently set
        augmentService = augmentClass(**config.AugmentService.params)
        augmentRecord = (
            yield augmentService.getAugmentRecord(
                "mercury",
                "locations"
            )
        )
        self.assertEqual(augmentRecord.autoScheduleMode, "default")

        # Create bogus record in resourceinfo db
        resourceInfoDatabase = ResourceInfoDatabase(config.DataRoot)
        resourceInfoDatabase._db_execute(
            "insert into RESOURCEINFO (GUID, AUTOSCHEDULE) values (:1, :2)",
            "mercury", 1,
        )
        resourceInfoDatabase._db_execute(
            "insert into RESOURCEINFO (GUID, AUTOSCHEDULE) values (:1, :2)",
            None, 1,
        )
        resourceInfoDatabase._db_commit()

        # Migrate auto-schedule from sqlite into directory
        yield migrateAutoSchedule(config, self.directory)

        # Auto-schedule now set
        augmentService = augmentClass(**config.AugmentService.params)
        augmentRecord = (
            yield augmentService.getAugmentRecord(
                "mercury",
                "locations"
            )
        )
        self.assertEqual(augmentRecord.autoScheduleMode, "automatic") 
Example #28
Source File: masterchild.py    From ccs-twistedextensions with Apache License 2.0 4 votes vote down vote up
def opt_protocol(self, value):
        """
        Protocol and port (specify as proto:port).
        """
        try:
            protocol, port = value.split(":")
        except ValueError:
            if ":" in value:
                raise UsageError("Invalid protocol argument.")
            else:
                raise UsageError("Port is required in protocol argument.")

        # Validate protocol name
        try:
            protocolClass = namedClass(protocol)
        except (ValueError, AttributeError):
            raise UsageError("Unknown protocol: {0}".format(protocol))

        try:
            if not issubclass(protocolClass, Protocol):
                raise TypeError()
        except TypeError:
            raise UsageError("Not a protocol: {0}".format(protocol))

        # FIXME: port should be a strport

        # Validate port number
        try:
            try:
                port = int(port)
            except ValueError:
                raise ValueError("not an integer")

            if port < 0:
                raise ValueError("must be >=0")

        except ValueError as e:
            raise UsageError(
                "Invalid port number {0}: {1}".format(port, e)
            )

        protocols = self.setdefault("protocols", [])

        for (otherProtocol, otherPort) in protocols:
            # FIXME: Raise here because we don't properly handle multiple
            # protocols yet.
            raise UsageError("Only one protocol may be specified.")

            if otherPort == port:
                if otherProtocol == protocol:
                    return

                raise UsageError(
                    "Port {0} cannot be registered more than once "
                    "for different protocols: ({1}, {2})",
                    otherProtocol, protocol
                )

        protocols.append((protocol, port))