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


Python CachingFilePath.children方法代码示例

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


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

示例1: File

# 需要导入模块: from twext.python.filepath import CachingFilePath [as 别名]
# 或者: from twext.python.filepath.CachingFilePath import children [as 别名]
class File(StaticRenderMixin):
    """
    File is a resource that represents a plain non-interpreted file
    (although it can look for an extension like .rpy or .cgi and hand the
    file to a processor for interpretation if you wish). Its constructor
    takes a file path.

    Alternatively, you can give a directory path to the constructor. In this
    case the resource will represent that directory, and its children will
    be files underneath that directory. This provides access to an entire
    filesystem tree with a single Resource.

    If you map the URL C{http://server/FILE} to a resource created as
    File('/tmp'), C{http://server/FILE/foo/bar.html} will return the contents of
    C{/tmp/foo/bar.html} .
    """
    implements(iweb.IResource)

    def _getContentTypes(self):
        if not hasattr(File, "_sharedContentTypes"):
            File._sharedContentTypes = loadMimeTypes()
        return File._sharedContentTypes

    contentTypes = property(_getContentTypes)

    contentEncodings = {
        ".gz" : "gzip",
        ".bz2": "bzip2"
        }

    processors = {}

    indexNames = ["index", "index.html", "index.htm", "index.trp", "index.rpy"]

    type = None

    def __init__(self, path, defaultType="text/plain", ignoredExts=(), processors=None, indexNames=None):
        """Create a file with the given path.
        """
        super(File, self).__init__()

        self.putChildren = {}
        if isinstance(path, FilePath):
            self.fp = path
        else:
            assert isinstance(path, str), "This should be a string."
            self.fp = FilePath(path)
        # Remove the dots from the path to split
        self.defaultType = defaultType
        self.ignoredExts = list(ignoredExts)
        if processors is not None:
            self.processors = dict([
                (key.lower(), value)
                for key, value in processors.items()
                ])

        if indexNames is not None:
            self.indexNames = indexNames

    def comparePath(self, path):
        
        if isinstance(path, FilePath):
            return path.path == self.fp.path
        else:
            return path == self.fp.path

    def exists(self):
        return self.fp.exists()

    def etag(self):
        if not self.fp.exists(): return succeed(None)

        st = self.fp.statinfo

        #
        # Mark ETag as weak if it was modified more recently than we can
        # measure and report, as it could be modified again in that span
        # and we then wouldn't know to provide a new ETag.
        #
        weak = (time.time() - st.st_mtime <= 1)

        return succeed(http_headers.ETag(
            "%X-%X-%X" % (st.st_ino, st.st_size, st.st_mtime),
            weak=weak
        ))

    def lastModified(self):
        if self.fp.exists():
            return self.fp.getmtime()
        else:
            return None

    def creationDate(self):
        if self.fp.exists():
            return self.fp.getmtime()
        else:
            return None

    def contentLength(self):
        if self.fp.exists():
#.........这里部分代码省略.........
开发者ID:jrossi,项目名称:twext,代码行数:103,代码来源:static.py

示例2: EINVALTestCase

# 需要导入模块: from twext.python.filepath import CachingFilePath [as 别名]
# 或者: from twext.python.filepath.CachingFilePath import children [as 别名]
class EINVALTestCase(TestCase):
    """
    Sometimes, L{os.listdir} will raise C{EINVAL}.  This is a transient error,
    and L{CachingFilePath.listdir} should work around it by retrying the
    C{listdir} operation until it succeeds.
    """

    def setUp(self):
        """
        Create a L{CachingFilePath} for the test to use.
        """
        self.cfp = CachingFilePath(self.mktemp())
        self.clock = Clock()
        self.cfp._sleep = self.clock.advance


    def test_testValidity(self):
        """
        If C{listdir} is replaced on a L{CachingFilePath}, we should be able to
        observe exceptions raised by the replacement.  This verifies that the
        test patching done here is actually testing something.
        """
        class CustomException(Exception): "Just for testing."
        def blowUp(dirname):
            raise CustomException()
        self.cfp._listdir = blowUp
        self.assertRaises(CustomException, self.cfp.listdir)
        self.assertRaises(CustomException, self.cfp.children)


    def test_retryLoop(self):
        """
        L{CachingFilePath} should catch C{EINVAL} and respond by retrying the
        C{listdir} operation until it succeeds.
        """
        calls = []
        def raiseEINVAL(dirname):
            calls.append(dirname)
            if len(calls) < 5:
                raise OSError(EINVAL, "This should be caught by the test.")
            return ['a', 'b', 'c']
        self.cfp._listdir = raiseEINVAL
        self.assertEquals(self.cfp.listdir(), ['a', 'b', 'c'])
        self.assertEquals(self.cfp.children(), [
                CachingFilePath(pathjoin(self.cfp.path, 'a')),
                CachingFilePath(pathjoin(self.cfp.path, 'b')),
                CachingFilePath(pathjoin(self.cfp.path, 'c')),])


    def requireTimePassed(self, filenames):
        """
        Create a replacement for listdir() which only fires after a certain
        amount of time.
        """
        self.calls = []
        def thunk(dirname):
            now = self.clock.seconds()
            if now < 20.0:
                self.calls.append(now)
                raise OSError(EINVAL, "Not enough time has passed yet.")
            else:
                return filenames
        self.cfp._listdir = thunk


    def assertRequiredTimePassed(self):
        """
        Assert that calls to the simulated time.sleep() installed by
        C{requireTimePassed} have been invoked the required number of times.
        """
        # Waiting should be growing by *2 each time until the additional wait
        # exceeds BACKOFF_MAX (5), at which point we should wait for 5s each
        # time.
        def cumulative(values):
            current = 0.0
            for value in values:
                current += value
                yield current

        self.assertEquals(self.calls,
                          list(cumulative(
                    [0.0, 0.1, 0.2, 0.4, 0.8, 1.6, 3.2, 5.0, 5.0])))


    def test_backoff(self):
        """
        L{CachingFilePath} will wait for an increasing interval up to
        C{BACKOFF_MAX} between calls to listdir().
        """
        self.requireTimePassed(['a', 'b', 'c'])
        self.assertEquals(self.cfp.listdir(), ['a', 'b', 'c'])


    def test_siblingExtensionSearch(self):
        """
        L{FilePath.siblingExtensionSearch} is unfortunately not implemented in
        terms of L{FilePath.listdir}, so we need to verify that it will also
        retry.
        """
        filenames = [self.cfp.basename()+'.a',
#.........这里部分代码省略.........
开发者ID:jrossi,项目名称:twext,代码行数:103,代码来源:test_filepath.py


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