当前位置: 首页>>代码示例>>Python>>正文


Python FilePath.getContent方法代码示例

本文整理汇总了Python中twisted.python.filepath.FilePath.getContent方法的典型用法代码示例。如果您正苦于以下问题:Python FilePath.getContent方法的具体用法?Python FilePath.getContent怎么用?Python FilePath.getContent使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在twisted.python.filepath.FilePath的用法示例。


在下文中一共展示了FilePath.getContent方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: parseArgs

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import getContent [as 别名]
    def parseArgs(self, deployment_config, application_config):
        deployment_config = FilePath(deployment_config)
        application_config = FilePath(application_config)

        if not deployment_config.exists():
            raise UsageError('No file exists at {path}'
                             .format(path=deployment_config.path))

        if not application_config.exists():
            raise UsageError('No file exists at {path}'
                             .format(path=application_config.path))

        self["deployment_config"] = deployment_config.getContent()
        self["application_config"] = application_config.getContent()

        try:
            deploy_config_obj = safe_load(self["deployment_config"])
        except YAMLError as e:
            raise UsageError(
                ("Deployment configuration at {path} could not be parsed as "
                 "YAML:\n\n{error}").format(
                    path=deployment_config.path,
                    error=str(e)
                )
            )
        try:
            app_config_obj = safe_load(self["application_config"])
        except YAMLError as e:
            raise UsageError(
                ("Application configuration at {path} could not be parsed as "
                 "YAML:\n\n{error}").format(
                    path=application_config.path,
                    error=str(e)
                )
            )

        try:
            fig_configuration = FigConfiguration(app_config_obj)
            if fig_configuration.is_valid_format():
                applications = fig_configuration.applications()
                self['application_config'] = (
                    applications_to_flocker_yaml(applications)
                )
            else:
                configuration = FlockerConfiguration(app_config_obj)
                if configuration.is_valid_format():
                    applications = configuration.applications()
                else:
                    raise ConfigurationError(
                        "Configuration is not a valid Fig or Flocker format."
                    )
            self['deployment'] = model_from_configuration(
                applications=applications,
                deployment_configuration=deploy_config_obj)
        except ConfigurationError as e:
            raise UsageError(str(e))
开发者ID:LaOnda,项目名称:flocker,代码行数:58,代码来源:script.py

示例2: test_no_config_written

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import getContent [as 别名]
 def test_no_config_written(self):
     """If no config file exists, a new one is written with the UUID."""
     path = FilePath(self.mktemp())
     service = VolumeService(path, None, reactor=Clock())
     service.startService()
     config = json.loads(path.getContent())
     self.assertEqual({u"uuid": service.uuid, u"version": 1}, config)
开发者ID:ereztourjeman,项目名称:flocker,代码行数:9,代码来源:test_service.py

示例3: test_createSSLPort

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import getContent [as 别名]
 def test_createSSLPort(self):
     """
     If a given valid strport description of an SSL port and the storeID of
     an extant factory, I{axiomatic port create} creates a new L{SSLPort}
     with the specified configuration and referring to that factory.  The
     certificate file specified is copied to a path inside the Store's files
     directory.  The port is also powered up on the store for L{IService}.
     """
     pemPath = FilePath(self.mktemp())
     pemPath.setContent(CERTIFICATE_DATA + PRIVATEKEY_DATA)
     store = Store(filesdir=self.mktemp())
     factory = DummyFactory(store=store)
     self.assertSuccessStatus(
         self._makeConfig(store),
         ["create", "--strport",
          "ssl:8443:certKey=" + pemPath.path +
          ":privateKey=" + pemPath.path,
          "--factory-identifier", str(factory.storeID)])
     self.assertEqual("Created.\n", sys.stdout.getvalue())
     [ssl] = list(store.query(SSLPort))
     self.assertEqual(ssl.portNumber, 8443)
     self.assertEqual(
         ssl.certificatePath.getContent(),
         CERTIFICATE_DATA + PRIVATEKEY_DATA)
     self.assertIdentical(ssl.factory, factory)
     self.assertEqual(
         pemPath.getContent(), CERTIFICATE_DATA + PRIVATEKEY_DATA)
     self.assertEqual(list(store.interfacesFor(ssl)), [IService])
开发者ID:rcarmo,项目名称:divmod.org,代码行数:30,代码来源:test_port.py

示例4: get_backend_api

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import getContent [as 别名]
def get_backend_api(test_case, cluster_id):
    """
    Get an appropriate BackendAPI for the specified dataset backend.

    Note this is a backdoor that is useful to be able to interact with cloud
    APIs in tests. For many dataset backends this does not make sense, but it
    provides a convenient means to interact with cloud backends such as EBS or
    cinder.

    :param test_case: The test case that is being run.

    :param cluster_id: The unique cluster_id, used for backend APIs that
        require this in order to be constructed.
    """
    backend_type = get_dataset_backend(test_case)
    if backend_type != DatasetBackend.aws:
        raise SkipTest(
            'This test is asking for backend type {} but only constructing '
            'aws backends is currently supported'.format(backend_type.name))
    backend_name = backend_type.name
    backend_config_filename = environ.get(
        "FLOCKER_ACCEPTANCE_TEST_VOLUME_BACKEND_CONFIG")
    if backend_config_filename is None:
        raise SkipTest(
            'This test requires the ability to construct an IBlockDeviceAPI '
            'in order to verify construction. Please set '
            'FLOCKER_ACCEPTANCE_TEST_VOLUME_BACKEND_CONFIG to a yaml filepath '
            'with the dataset configuration.')
    backend_config_filepath = FilePath(backend_config_filename)
    full_backend_config = yaml.safe_load(
        backend_config_filepath.getContent())
    backend_config = full_backend_config.get(backend_name)
    if 'backend' in backend_config:
        backend_config.pop('backend')
    return aws_from_configuration(cluster_id=cluster_id, **backend_config)
开发者ID:yangchaogit,项目名称:flocker,代码行数:37,代码来源:testtools.py

示例5: monitoring_check

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import getContent [as 别名]
def monitoring_check(checker, lasterrors_path, from_email, what, stdout, stderr):
    error_stream = StringIO()

    lasterrors = None
    lasterrors_fp = FilePath(lasterrors_path)
    if lasterrors_fp.exists():
        lasterrors = lasterrors_fp.getContent()

    d = checker(stdout, error_stream)
    def cb(x):
        if isinstance(x, Failure):
            print >>stderr, str(x)
            if hasattr(x.value, 'response'):
                print >>stderr, x.value.response

        errors = error_stream.getvalue()
        print >>stderr, errors
        if errors != lasterrors:
            d2 = send_monitoring_report(errors, from_email, what)
            def _sent(ign):
                lasterrors_fp.setContent(errors)
                raise Exception("Sent failure report.")
            def _err(f):
                print >>stderr, str(f)
                return f
            d2.addCallbacks(_sent, _err)
            return d2
    d.addBoth(cb)
    return d
开发者ID:pombredanne,项目名称:leastauthority.com,代码行数:31,代码来源:monitor.py

示例6: test_full

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import getContent [as 别名]
    def test_full(self):
        """
        Running C{calendarserver_export} on the command line exports an ics
        file. (Almost-full integration test, starting from the main point, using
        as few test fakes as possible.)

        Note: currently the only test for directory interaction.
        """
        yield populateCalendarsFrom(
            {
                "user02": {
                    # TODO: more direct test for skipping inbox
                    "inbox": {
                        "inbox-item.ics": (valentines, {})
                    },
                    "calendar1": {
                        "peruser.ics": (dataForTwoUsers, {}), # EST
                    }
                }
            }, self.store
        )

        output = FilePath(self.mktemp())
        main(['calendarserver_export', '--output',
              output.path, '--user', 'user02'], reactor=self)

        yield self.waitToStop

        self.assertEquals(
            Component.fromString(resultForUser2),
            Component.fromString(output.getContent())
        )
开发者ID:eventable,项目名称:CalendarServer,代码行数:34,代码来源:test_export.py

示例7: isDocker

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import getContent [as 别名]
    def isDocker(self, _initCGroupLocation="/proc/1/cgroup"):
        """
        Check if the current platform is Linux in a Docker container.

        @return: C{True} if the current platform has been detected as Linux
            inside a Docker container.
        @rtype: C{bool}
        """
        if not self.isLinux():
            return False

        from twisted.python.filepath import FilePath

        # Ask for the cgroups of init (pid 1)
        initCGroups = FilePath(_initCGroupLocation)
        if initCGroups.exists():
            # The cgroups file looks like "2:cpu:/". The third element will
            # begin with /docker if it is inside a Docker container.
            controlGroups = [x.split(b":")
                             for x in initCGroups.getContent().split(b"\n")]

            for group in controlGroups:
                if len(group) == 3 and group[2].startswith(b"/docker/"):
                    # If it starts with /docker/, we're in a docker container
                    return True

        return False
开发者ID:andywu42000,项目名称:2016YCProject,代码行数:29,代码来源:runtime.py

示例8: postOptions

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import getContent [as 别名]
    def postOptions(self):
        if self['app-template'] is not None:
            template_file = FilePath(self['app-template'])
            self['template'] = yaml.safe_load(template_file.getContent())
        elif self['apps-per-node'] > 0:
            raise UsageError(
                "app-template parameter must be provided if apps-per-node > 0"
            )

        self['purpose'] = unicode(self['purpose'])
        if any(x not in string.ascii_letters + string.digits + '-'
               for x in self['purpose']):
            raise UsageError(
                "Purpose may have only alphanumeric symbols and dash. " +
                "Found {!r}".format('purpose')
            )

        if self['cert-directory']:
            cert_path = FilePath(self['cert-directory'])
            _ensure_empty_directory(cert_path)
            self['cert-directory'] = cert_path

        # This is run last as it creates the actual "runner" object
        # based on the provided parameters.
        super(RunOptions, self).postOptions()
开发者ID:yangchaogit,项目名称:flocker,代码行数:27,代码来源:cluster_setup.py

示例9: postOptions

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import getContent [as 别名]
    def postOptions(self):
        if self['distribution'] is None:
            raise UsageError("Distribution required.")

        if self['config-file'] is not None:
            config_file = FilePath(self['config-file'])
            self['config'] = yaml.safe_load(config_file.getContent())
        else:
            self['config'] = {}

        provider = self['provider'].lower()
        provider_config = self['config'].get(provider, {})

        package_source = PackageSource(
            version=self['flocker-version'],
            branch=self['branch'],
            build_server=self['build-server'],
        )
        try:
            get_runner = getattr(self, "_runner_" + provider.upper())
        except AttributeError:
            raise UsageError(
                "Provider {!r} not supported. Available providers: {}".format(
                    provider, ', '.join(
                        name.lower() for name in self._get_provider_names()
                    )
                )
            )
        else:
            self.runner = get_runner(
                package_source=package_source,
                dataset_backend=self.dataset_backend(),
                provider_config=provider_config,
            )
开发者ID:uedzen,项目名称:flocker,代码行数:36,代码来源:acceptance.py

示例10: onConnect

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import getContent [as 别名]
	def onConnect(self,request):
		myAES = AESCipher(key)
		if 'cookie' in request.headers:
			try:
				cookie = Cookie.SimpleCookie()
				cookie.load(str(request.headers['cookie']))
			except Cookie.CookieError:
				pass
			
			if ('wsid' in cookie) and ('PSClient' in request.headers['user-agent']):
				wsid = cookie['wsid'].value
				cambot = json.loads(myAES.decrypt(wsid))
				if cambot['id'] in request.path:
					self.temp_location = self.factory.temp_path.child(cambot['id'])
					if not self.temp_location.exists():
						self.temp_location.makedirs()
					
					f = self.temp_location.child(u'index.html')
					g = FilePath("/home/chetan/pscore/templates/live_hls.html").asTextMode()
					content = g.getContent()
					new = content.replace("++camid++",cambot['id'])
					f.setContent(new)
					return None
				else:
					self.sendClose(1000,"Not authorised")
			else:
				self.sendClose(1000,"Not authorised")
		else:
			self.sendClose(1000,"Not authorised")
开发者ID:chetanbnaik,项目名称:pscore,代码行数:31,代码来源:hlsfaststreamer.py

示例11: get_backend_api

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import getContent [as 别名]
def get_backend_api(test_case, cluster_id):
    """
    Get an appropriate BackendAPI for the specified dataset backend.

    Note this is a backdoor that is useful to be able to interact with cloud
    APIs in tests. For many dataset backends this does not make sense, but it
    provides a convenient means to interact with cloud backends such as EBS or
    cinder.

    :param test_case: The test case that is being run.

    :param cluster_id: The unique cluster_id, used for backend APIs that
        require this in order to be constructed.
    """
    backend_config_filename = environ.get(
        "FLOCKER_ACCEPTANCE_TEST_VOLUME_BACKEND_CONFIG")
    if backend_config_filename is None:
        raise SkipTest(
            'This test requires the ability to construct an IBlockDeviceAPI '
            'in order to verify construction. Please set '
            'FLOCKER_ACCEPTANCE_TEST_VOLUME_BACKEND_CONFIG to a yaml filepath '
            'with the dataset configuration.')
    backend_name = environ.get("FLOCKER_ACCEPTANCE_VOLUME_BACKEND")
    if backend_name is None:
        raise SkipTest(
            "Set acceptance testing volume backend using the " +
            "FLOCKER_ACCEPTANCE_VOLUME_BACKEND environment variable.")
    backend_config_filepath = FilePath(backend_config_filename)
    full_backend_config = yaml.safe_load(
        backend_config_filepath.getContent())
    backend_config = full_backend_config.get(backend_name)
    if 'backend' in backend_config:
        backend_config.pop('backend')
    backend = get_backend(backend_name)
    return get_api(backend, pmap(backend_config), reactor, cluster_id)
开发者ID:james-w,项目名称:flocker,代码行数:37,代码来源:testtools.py

示例12: postOptions

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import getContent [as 别名]
    def postOptions(self):
        if self['distribution'] is None:
            raise UsageError("Distribution required.")

        if self['config-file'] is not None:
            config_file = FilePath(self['config-file'])
            self['config'] = yaml.safe_load(config_file.getContent())
        else:
            self['config'] = {}

        if self['flocker-version']:
            rpm_version = make_rpm_version(self['flocker-version'])
            os_version = "%s-%s" % (rpm_version.version, rpm_version.release)
            if os_version.endswith('.dirty'):
                os_version = os_version[:-len('.dirty')]
        else:
            os_version = None

        self['package_source'] = PackageSource(
            version=self['flocker-version'],
            os_version=os_version,
            branch=self['branch'],
            build_server=self['build-server'],
        )

        if self['pip']:
            supported = PIP_DISTRIBUTIONS
        else:
            supported = PACKAGED_CLIENT_DISTRIBUTIONS
        if self['distribution'] not in supported:
            raise UsageError(
                "Distribution %r not supported. Available distributions: %s"
                % (self['distribution'], ', '.join(supported)))
开发者ID:hackday-profilers,项目名称:flocker,代码行数:35,代码来源:client.py

示例13: test_full

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import getContent [as 别名]
    def test_full(self):
        """
        Running C{calendarserver_export} on the command line exports an ics
        file. (Almost-full integration test, starting from the main point, using
        as few test fakes as possible.)

        Note: currently the only test for directory interaction.
        """
        yield populateCalendarsFrom(
            {
                "user02": {
                    # TODO: more direct test for skipping inbox
                    "inbox": {
                        "inbox-item.ics": (valentines, {})
                    },
                    "calendar1": {
                        "peruser.ics": (dataForTwoUsers, {}), # EST
                    }
                }
            }, self.store
        )

        augmentsData = """
            <augments>
              <record>
                <uid>Default</uid>
                <enable>true</enable>
                <enable-calendar>true</enable-calendar>
                <enable-addressbook>true</enable-addressbook>
              </record>
            </augments>
        """
        augments = FilePath(self.mktemp())
        augments.setContent(augmentsData)

        accountsData = """
            <accounts realm="Test Realm">
                <user>
                    <uid>user-under-test</uid>
                    <guid>user02</guid>
                    <name>Not Interesting</name>
                    <password>very-secret</password>
                </user>
            </accounts>
        """
        accounts = FilePath(self.mktemp())
        accounts.setContent(accountsData)
        output = FilePath(self.mktemp())
        self.accountsFile = accounts.path
        self.augmentsFile = augments.path
        main(['calendarserver_export', '--output',
              output.path, '--user', 'user-under-test'], reactor=self)

        yield self.waitToStop

        self.assertEquals(
            Component.fromString(resultForUser2),
            Component.fromString(output.getContent())
        )
开发者ID:azbarcea,项目名称:calendarserver,代码行数:61,代码来源:test_export.py

示例14: test_success

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import getContent [as 别名]
 def test_success(self):
     """
     Neon generates a valid document when invoked with valid data.
     """
     unsignedPDF = FilePath(__file__).sibling('data').child('test.pdf')
     d = self.signPDF(unsignedPDF.getContent())
     d.addCallback(self.assertValidPDF)
     return d
开发者ID:fusionapp,项目名称:documint,代码行数:10,代码来源:test_neon.py

示例15: getContent

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import getContent [as 别名]
 def getContent(self):
     data = FilePath.getContent(self)
     # There is a duplicate of thing2.pem, so ignore anything that
     # looks like it.
     if data == casPath.child("thing2.pem").getContent():
         raise IOError(EPERM)
     else:
         return data
开发者ID:antong,项目名称:twisted,代码行数:10,代码来源:test_endpoints.py


注:本文中的twisted.python.filepath.FilePath.getContent方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。