本文整理汇总了Python中twext.python.filepath.CachingFilePath.child方法的典型用法代码示例。如果您正苦于以下问题:Python CachingFilePath.child方法的具体用法?Python CachingFilePath.child怎么用?Python CachingFilePath.child使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twext.python.filepath.CachingFilePath
的用法示例。
在下文中一共展示了CachingFilePath.child方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_fileStoreFromPath
# 需要导入模块: from twext.python.filepath import CachingFilePath [as 别名]
# 或者: from twext.python.filepath.CachingFilePath import child [as 别名]
def test_fileStoreFromPath(self):
"""
Verify that fileStoreFromPath() will return a CommonDataStore if
the given path contains either "calendars" or "addressbooks"
sub-directories. Otherwise it returns None
"""
# No child directories
docRootPath = CachingFilePath(self.mktemp())
docRootPath.createDirectory()
step = UpgradeToDatabaseStep.fileStoreFromPath(docRootPath)
self.assertEquals(step, None)
# "calendars" child directory exists
childPath = docRootPath.child("calendars")
childPath.createDirectory()
step = UpgradeToDatabaseStep.fileStoreFromPath(docRootPath)
self.assertTrue(isinstance(step, CommonDataStore))
childPath.remove()
# "addressbooks" child directory exists
childPath = docRootPath.child("addressbooks")
childPath.createDirectory()
step = UpgradeToDatabaseStep.fileStoreFromPath(docRootPath)
self.assertTrue(isinstance(step, CommonDataStore))
childPath.remove()
示例2: test_copy
# 需要导入模块: from twext.python.filepath import CachingFilePath [as 别名]
# 或者: from twext.python.filepath.CachingFilePath import child [as 别名]
def test_copy(self):
tempDir = FilePath(self.mktemp())
tempDir.makedirs()
tempFile1 = tempDir.child("test1")
tempFile1.touch()
tempFile2 = tempDir.child("test2")
tempFile2.touch()
# Existing store
store1_user1 = PropertyStore("user01", lambda : tempFile1)
store1_user2 = PropertyStore("user01", lambda : tempFile1)
store1_user2._setPerUserUID("user02")
# New store
store2_user1 = PropertyStore("user01", lambda : tempFile2)
store2_user2 = PropertyStore("user01", lambda : tempFile2)
store2_user2._setPerUserUID("user02")
# Populate current store with data
class DummyProperty1(WebDAVTextElement):
namespace = "http://calendarserver.org/ns/"
name = "dummy1"
class DummyProperty2(WebDAVTextElement):
namespace = "http://calendarserver.org/ns/"
name = "dummy2"
class DummyProperty3(WebDAVTextElement):
namespace = "http://calendarserver.org/ns/"
name = "dummy3"
props_user1 = (
DummyProperty1.fromString("value1-user1"),
DummyProperty2.fromString("value2-user1"),
)
props_user2 = (
DummyProperty1.fromString("value1-user2"),
DummyProperty3.fromString("value3-user2"),
)
for prop in props_user1:
store1_user1[PropertyName.fromElement(prop)] = prop
for prop in props_user2:
store1_user2[PropertyName.fromElement(prop)] = prop
store1_user1.flush()
store1_user2.flush()
# Do copy and check results
store2_user1.copyAllProperties(store1_user1)
store2_user1.flush()
self.assertEqual(store1_user1.attrs.items(), store2_user1.attrs.items())
self.assertEqual(store1_user2.attrs.items(), store2_user2.attrs.items())
示例3: _connectorFor_pg8000
# 需要导入模块: from twext.python.filepath import CachingFilePath [as 别名]
# 或者: from twext.python.filepath.CachingFilePath import child [as 别名]
def _connectorFor_pg8000(dbmodule, **kwargs):
"""
Turn properties into pg8000 kwargs
"""
params = DBAPIParameters(**kwargs)
dbkwargs = {
"user": params.user,
"password": params.password,
"database": params.database,
}
if params.unixsocket:
dbkwargs["unix_sock"] = params.unixsocket
# We're using a socket file
socketFP = CachingFilePath(dbkwargs["unix_sock"])
if socketFP.isdir():
# We have been given the directory, not the actual socket file
socketFP = socketFP.child(".s.PGSQL.{}".format(params.port if params.port else "5432"))
dbkwargs["unix_sock"] = socketFP.path
if not socketFP.isSocket():
raise InternalDataStoreError(
"No such socket file: {}".format(socketFP.path)
)
else:
dbkwargs["host"] = params.host
if params.port:
dbkwargs["port"] = int(params.port)
return DBAPIConnector(dbmodule, postgresPreflight, **dbkwargs)
示例4: setUp
# 需要导入模块: from twext.python.filepath import CachingFilePath [as 别名]
# 或者: from twext.python.filepath.CachingFilePath import child [as 别名]
def setUp(self):
tempDir = FilePath(self.mktemp())
tempDir.makedirs()
tempFile = tempDir.child("test")
tempFile.touch()
self.propertyStore = self.propertyStore1 = PropertyStore("user01", "user01", lambda : tempFile)
self.propertyStore2 = PropertyStore("user02", "user01", lambda : tempFile)
示例5: buildStore
# 需要导入模块: from twext.python.filepath import CachingFilePath [as 别名]
# 或者: from twext.python.filepath.CachingFilePath import child [as 别名]
def buildStore(self, testCase, notifierFactory):
"""
Do the necessary work to build a store for a particular test case.
@return: a L{Deferred} which fires with an L{IDataStore}.
"""
disableMemcacheForTest(testCase)
dbRoot = CachingFilePath(self.SHARED_DB_PATH)
attachmentRoot = dbRoot.child("attachments")
if self.sharedService is None:
ready = Deferred()
def getReady(connectionFactory):
self.makeAndCleanStore(
testCase, notifierFactory, attachmentRoot
).chainDeferred(ready)
return Service()
self.sharedService = self.createService(getReady)
self.sharedService.startService()
def startStopping():
log.msg("Starting stopping.")
self.sharedService.unpauseMonitor()
return self.sharedService.stopService()
reactor.addSystemEventTrigger(#@UndefinedVariable
"before", "shutdown", startStopping)
result = ready
else:
result = self.makeAndCleanStore(
testCase, notifierFactory, attachmentRoot
)
def cleanUp():
def stopit():
self.sharedService.pauseMonitor()
return deferLater(reactor, 0.1, stopit)
testCase.addCleanup(cleanUp)
return result
示例6: doDirectoryTest
# 需要导入模块: from twext.python.filepath import CachingFilePath [as 别名]
# 或者: from twext.python.filepath.CachingFilePath import child [as 别名]
def doDirectoryTest(self, addedNames, modify=lambda x: None,
expectedNames=None):
"""
Do a test of a L{DAVFile} pointed at a directory, verifying that files
existing with the given names will be faithfully 'played back' via HTML
rendering.
"""
if expectedNames is None:
expectedNames = addedNames
fp = FilePath(self.mktemp())
fp.createDirectory()
for sampleName in expectedNames:
fp.child(sampleName).touch()
df = DAVFile(fp)
modify(df)
responseText = (yield df.render(SimpleFakeRequest('/'))).stream.read()
responseXML = browserHTML2ETree(responseText)
names = set([element.text.encode("utf-8")
for element in responseXML.findall(".//a")])
self.assertEquals(set(expectedNames), names)
示例7: setUp
# 需要导入模块: from twext.python.filepath import CachingFilePath [as 别名]
# 或者: from twext.python.filepath.CachingFilePath import child [as 别名]
def setUp(self):
yield super(GroupShareeTestBase, self).setUp()
accountsFilePath = FilePath(
os.path.join(os.path.dirname(__file__), "accounts")
)
yield self.buildStoreAndDirectory(
accounts=accountsFilePath.child("groupAccounts.xml"),
)
yield self.populate()
self.paths = {}
示例8: setUp
# 需要导入模块: from twext.python.filepath import CachingFilePath [as 别名]
# 或者: from twext.python.filepath.CachingFilePath import child [as 别名]
def setUp(self):
tempDir = FilePath(self.mktemp())
tempDir.makedirs()
tempFile = tempDir.child("test")
tempFile.touch()
self.propertyStore = PropertyStore("user01", lambda : tempFile)
self.propertyStore1 = self.propertyStore
self.propertyStore2 = PropertyStore("user01", lambda : tempFile)
self.propertyStore2._setPerUserUID("user02")
self.propertyStore2._setProxyUID("user02")
self.propertyStore3 = PropertyStore("user01", lambda : tempFile)
self.propertyStore3._setProxyUID("user03")
self.propertyStore4 = PropertyStore("user01", lambda : tempFile)
self.propertyStore4._setPerUserUID("user02")
self.propertyStore4._setProxyUID("user04")
示例9: buildStore
# 需要导入模块: from twext.python.filepath import CachingFilePath [as 别名]
# 或者: from twext.python.filepath.CachingFilePath import child [as 别名]
def buildStore(self, testCase, notifierFactory, directoryService=None, homes=None, enableJobProcessing=True):
"""
Do the necessary work to build a store for a particular test case.
@return: a L{Deferred} which fires with an L{IDataStore}.
"""
disableMemcacheForTest(testCase)
dbRoot = FilePath(self.sharedDBPath)
attachmentRoot = dbRoot.child("attachments")
# The directory will be given to us later via setDirectoryService
if self.sharedService is None:
ready = Deferred()
def getReady(connectionFactory, storageService):
self.makeAndCleanStore(
testCase, notifierFactory, directoryService, attachmentRoot, enableJobProcessing
).chainDeferred(ready)
return Service()
self.sharedService = self.createService(getReady)
self.sharedService.startService()
def startStopping():
log.info("Starting stopping.")
self.sharedService.unpauseMonitor()
return self.sharedService.stopService()
reactor.addSystemEventTrigger("before", "shutdown", startStopping)
result = ready
else:
result = self.makeAndCleanStore(
testCase, notifierFactory, directoryService, attachmentRoot, enableJobProcessing
)
def cleanUp():
def stopit():
self.sharedService.pauseMonitor()
return deferLater(reactor, 0.1, stopit)
testCase.addCleanup(cleanUp)
return result
示例10: test_triggerGroupCacherUpdate
# 需要导入模块: from twext.python.filepath import CachingFilePath [as 别名]
# 或者: from twext.python.filepath.CachingFilePath import child [as 别名]
def test_triggerGroupCacherUpdate(self):
"""
Verify triggerGroupCacherUpdate can read a pidfile and send a SIGHUP
"""
self.calledArgs = None
def killMethod(pid, sig):
self.calledArgs = (pid, sig)
class StubConfig(object):
def __init__(self, runRootPath):
self.RunRoot = runRootPath
runRootDir = FilePath(self.mktemp())
runRootDir.createDirectory()
pidFile = runRootDir.child("groupcacher.pid")
pidFile.setContent("1234")
testConfig = StubConfig(runRootDir.path)
triggerGroupCacherUpdate(testConfig, killMethod=killMethod)
self.assertEquals(self.calledArgs, (1234, signal.SIGHUP))
runRootDir.remove()
示例11: setUp
# 需要导入模块: from twext.python.filepath import CachingFilePath [as 别名]
# 或者: from twext.python.filepath.CachingFilePath import child [as 别名]
def setUp(self):
super(DeprovisionTestCase, self).setUp()
testRootPath = FilePath(__file__).sibling("deprovision")
template = testRootPath.child("caldavd.plist").getContent()
newConfig = template % {
"ServerRoot" : os.path.abspath(config.ServerRoot),
}
configFilePath = FilePath(os.path.join(config.ConfigRoot, "caldavd.plist"))
configFilePath.setContent(newConfig)
self.configFileName = configFilePath.path
config.load(self.configFileName)
origUsersFile = FilePath(__file__).sibling(
"deprovision").child("users-groups.xml")
copyUsersFile = FilePath(config.DataRoot).child("accounts.xml")
origUsersFile.copyTo(copyUsersFile)
origResourcesFile = FilePath(__file__).sibling(
"deprovision").child("resources-locations.xml")
copyResourcesFile = FilePath(config.DataRoot).child("resources.xml")
origResourcesFile.copyTo(copyResourcesFile)
origAugmentFile = FilePath(__file__).sibling(
"deprovision").child("augments.xml")
copyAugmentFile = FilePath(config.DataRoot).child("augments.xml")
origAugmentFile.copyTo(copyAugmentFile)
self.rootResource = getRootResource(config)
self.directory = self.rootResource.getDirectory()
# Make sure trial puts the reactor in the right state, by letting it
# run one reactor iteration. (Ignore me, please.)
d = Deferred()
reactor.callLater(0, d.callback, True)
return d
示例12: getRootResource
# 需要导入模块: from twext.python.filepath import CachingFilePath [as 别名]
# 或者: from twext.python.filepath.CachingFilePath import child [as 别名]
#.........这里部分代码省略.........
continue
try:
principal = schemeConfig["ServicePrincipal"]
if not principal:
credFactory = NegotiateCredentialFactory(
type="HTTP",
hostname=config.ServerHostName,
)
else:
credFactory = NegotiateCredentialFactory(
principal=principal,
)
except ValueError:
log.info("Could not start Kerberos")
continue
elif scheme == "digest":
credFactory = QopDigestCredentialFactory(
schemeConfig["Algorithm"],
schemeConfig["Qop"],
realm,
)
elif scheme == "basic":
credFactory = BasicCredentialFactory(realm)
elif scheme == "wiki":
pass
else:
log.error("Unknown scheme: %s" % (scheme,))
if credFactory:
credentialFactories.append(credFactory)
#
# Setup Resource hierarchy
#
log.info("Setting up document root at: %s"
% (config.DocumentRoot,))
log.info("Setting up principal collection: %r"
% (principalResourceClass,))
principalCollection = principalResourceClass("/principals/", directory)
#
# Configure NotifierFactory
#
if config.Notifications.Enabled:
notifierFactory = NotifierFactory(
config.Notifications.InternalNotificationHost,
config.Notifications.InternalNotificationPort,
)
else:
notifierFactory = None
if config.UseDatabase:
_dbRoot = CachingFilePath(config.DatabaseRoot)
_postgresService = PostgresService(_dbRoot, None, v1_schema, "caldav",
logFile=config.PostgresLogFile)
_newStore = CommonSQLDataStore(_postgresService.produceConnection,
notifierFactory, _dbRoot.child("attachments"), config.EnableCalDAV, config.EnableCardDAV)
else:
_newStore = CommonFileDataStore(FilePath(config.DocumentRoot),
notifierFactory, config.EnableCalDAV, config.EnableCardDAV)
if config.EnableCalDAV:
log.info("Setting up calendar collection: %r" % (calendarResourceClass,))
calendarCollection = calendarResourceClass(
directory,
"/calendars/",
_newStore,
)
if config.EnableCardDAV:
log.info("Setting up address book collection: %r" % (addressBookResourceClass,))
addressBookCollection = addressBookResourceClass(
directory,
"/addressbooks/",
_newStore,
)
directoryPath = os.path.join(config.DocumentRoot, config.DirectoryAddressBook.name)
if config.DirectoryAddressBook.Enabled and config.EnableSearchAddressBook:
log.info("Setting up directory address book: %r" % (directoryBackedAddressBookResourceClass,))
directoryBackedAddressBookCollection = directoryBackedAddressBookResourceClass(
principalCollections=(principalCollection,)
)
addSystemEventTrigger("after", "startup", directoryBackedAddressBookCollection.provisionDirectory)
else:
# remove /directory from previous runs that may have created it
try:
FilePath(directoryPath).remove()
log.info("Deleted: %s" % directoryPath)
except (OSError, IOError), e:
if e.errno != errno.ENOENT:
log.error("Could not delete: %s : %r" % (directoryPath, e,))
示例13: File
# 需要导入模块: from twext.python.filepath import CachingFilePath [as 别名]
# 或者: from twext.python.filepath.CachingFilePath import child [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():
#.........这里部分代码省略.........
示例14: HomeMigrationTests
# 需要导入模块: from twext.python.filepath import CachingFilePath [as 别名]
# 或者: from twext.python.filepath.CachingFilePath import child [as 别名]
class HomeMigrationTests(TestCase):
"""
Tests for L{UpgradeToDatabaseStep}.
"""
@inlineCallbacks
def setUp(self):
"""
Set up two stores to migrate between.
"""
# Add some files to the file store.
self.filesPath = CachingFilePath(self.mktemp())
self.filesPath.createDirectory()
fileStore = self.fileStore = CommonDataStore(
self.filesPath, {"push": StubNotifierFactory()}, TestStoreDirectoryService(), True, True
)
self.sqlStore = yield theStoreBuilder.buildStore(
self, StubNotifierFactory()
)
self.upgrader = UpgradeToDatabaseStep(self.fileStore, self.sqlStore)
requirements = CommonTests.requirements
extras = deriveValue(self, "extraRequirements", lambda t: {})
requirements = self.mergeRequirements(requirements, extras)
yield populateCalendarsFrom(requirements, fileStore)
md5s = CommonTests.md5s
yield resetCalendarMD5s(md5s, fileStore)
self.filesPath.child("calendars").child(
"__uids__").child("ho").child("me").child("home1").child(
".some-extra-data").setContent("some extra data")
requirements = ABCommonTests.requirements
yield populateAddressBooksFrom(requirements, fileStore)
md5s = ABCommonTests.md5s
yield resetAddressBookMD5s(md5s, fileStore)
self.filesPath.child("addressbooks").child(
"__uids__").child("ho").child("me").child("home1").child(
".some-extra-data").setContent("some extra data")
def mergeRequirements(self, a, b):
"""
Merge two requirements dictionaries together, modifying C{a} and
returning it.
@param a: Some requirements, in the format of
L{CommonTests.requirements}.
@type a: C{dict}
@param b: Some additional requirements, to be merged into C{a}.
@type b: C{dict}
@return: C{a}
@rtype: C{dict}
"""
for homeUID in b:
homereq = a.setdefault(homeUID, {})
homeExtras = b[homeUID]
for calendarUID in homeExtras:
calreq = homereq.setdefault(calendarUID, {})
calendarExtras = homeExtras[calendarUID]
calreq.update(calendarExtras)
return a
@withSpecialValue(
"extraRequirements",
{
"home1": {
"calendar_1": {
"bogus.ics": (
getModule("twistedcaldav").filePath.sibling("zoneinfo")
.child("EST.ics").getContent(),
CommonTests.metadata1
)
}
}
}
)
@inlineCallbacks
def test_unknownTypeNotMigrated(self):
"""
The only types of calendar objects that should get migrated are VEVENTs
and VTODOs. Other component types, such as free-standing VTIMEZONEs,
don't have a UID and can't be stored properly in the database, so they
should not be migrated.
"""
yield self.upgrader.stepWithResult(None)
txn = self.sqlStore.newTransaction()
self.addCleanup(txn.commit)
self.assertIdentical(
None,
(yield (yield (yield
(yield txn.calendarHomeWithUID("home1"))
.calendarWithName("calendar_1")))
.calendarObjectWithName("bogus.ics"))
)
#.........这里部分代码省略.........
示例15: import
# 需要导入模块: from twext.python.filepath import CachingFilePath [as 别名]
# 或者: from twext.python.filepath.CachingFilePath import child [as 别名]
from txdav.common.icommondatastore import ObjectResourceNameAlreadyExistsError
from txcarddav.iaddressbookstore import (
IAddressBookObject, IAddressBookHome,
IAddressBook, IAddressBookTransaction
)
from twistedcaldav.vcard import Component as VComponent
from twext.python.filepath import CachingFilePath as FilePath
from twext.web2.dav import davxml
from twext.web2.dav.element.base import WebDAVUnknownElement
storePath = FilePath(__file__).parent().child("addressbook_store")
homeRoot = storePath.child("ho").child("me").child("home1")
adbk1Root = homeRoot.child("addressbook_1")
addressbook1_objectNames = [
"1.vcf",
"2.vcf",
"3.vcf",
]
home1_addressbookNames = [
"addressbook_1",
"addressbook_2",
"addressbook_empty",
]