本文整理汇总了Python中twext.python.filepath.CachingFilePath.exists方法的典型用法代码示例。如果您正苦于以下问题:Python CachingFilePath.exists方法的具体用法?Python CachingFilePath.exists怎么用?Python CachingFilePath.exists使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twext.python.filepath.CachingFilePath
的用法示例。
在下文中一共展示了CachingFilePath.exists方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from twext.python.filepath import CachingFilePath [as 别名]
# 或者: from twext.python.filepath.CachingFilePath import exists [as 别名]
def __init__(self, params, alwaysStat=False):
defaults = {
'xmlFile' : None,
'directoryBackedAddressBook': None,
'recordTypes' : (
self.recordType_users,
self.recordType_groups,
self.recordType_locations,
self.recordType_resources,
),
'cacheTimeout' : 30,
'realmName' : '/Search',
}
ignored = None
params = self.getParams(params, defaults, ignored)
self._recordTypes = params['recordTypes']
self.realmName = params['realmName']
super(XMLDirectoryService, self).__init__(params['cacheTimeout'])
xmlFile = fullServerPath(config.DataRoot, params.get("xmlFile"))
if type(xmlFile) is str:
xmlFile = FilePath(xmlFile)
if not xmlFile.exists():
xmlFile.setContent("""<?xml version="1.0" encoding="utf-8"?>
<accounts realm="%s">
</accounts>
""" % (self.realmName,))
uid = -1
if config.UserName:
try:
uid = pwd.getpwnam(config.UserName).pw_uid
except KeyError:
self.log_error("User not found: %s" % (config.UserName,))
gid = -1
if config.GroupName:
try:
gid = grp.getgrnam(config.GroupName).gr_gid
except KeyError:
self.log_error("Group not found: %s" % (config.GroupName,))
if uid != -1 and gid != -1:
os.chown(xmlFile.path, uid, gid)
self.xmlFile = xmlFile
self._fileInfo = None
self._lastCheck = 0
self._alwaysStat = alwaysStat
self.directoryBackedAddressBook = params.get('directoryBackedAddressBook')
self._accounts()
示例2: ready
# 需要导入模块: from twext.python.filepath import CachingFilePath [as 别名]
# 或者: from twext.python.filepath.CachingFilePath import exists [as 别名]
def ready(self, createDatabaseConn, createDatabaseCursor):
"""
Subprocess is ready. Time to initialize the subservice.
If the database has not been created and there is a dump file,
then the dump file is imported.
"""
if self.resetSchema:
try:
createDatabaseCursor.execute(
"drop database {}".format(self.databaseName)
)
except pgdb.DatabaseError:
pass
try:
createDatabaseCursor.execute(
"create database {} with encoding 'UTF8'"
.format(self.databaseName)
)
except:
# database already exists
executeSQL = False
else:
# database does not yet exist; if dump file exists, execute it,
# otherwise execute schema
executeSQL = True
sqlToExecute = self.schema
if self.importFileName:
importFilePath = CachingFilePath(self.importFileName)
if importFilePath.exists():
sqlToExecute = importFilePath.getContent()
createDatabaseCursor.close()
createDatabaseConn.close()
if executeSQL:
connection = self.produceConnection()
cursor = connection.cursor()
cursor.execute(sqlToExecute)
connection.commit()
connection.close()
if self.shutdownDeferred is None:
# Only continue startup if we've not begun shutdown
self.subServiceFactory(
self.produceConnection, self
).setServiceParent(self)
示例3: test_quitAfterUpgradeStep
# 需要导入模块: from twext.python.filepath import CachingFilePath [as 别名]
# 或者: from twext.python.filepath.CachingFilePath import exists [as 别名]
def test_quitAfterUpgradeStep(self):
triggerFileName = "stop_after_upgrade"
triggerFile = FilePath(triggerFileName)
self.pps.addStep(
StepOne(self._record, False)
).addStep(
StepTwo(self._record, False)
).addStep(
QuitAfterUpgradeStep(triggerFile.path, reactor=self.clock)
).addStep(
StepFour(self._record, True)
)
triggerFile.setContent("")
self.pps.startService()
self.assertEquals(self.history,
['one success', 'two success', 'four failure',
('serviceCreator', None, 'storageService')])
self.assertFalse(triggerFile.exists())
示例4: File
# 需要导入模块: from twext.python.filepath import CachingFilePath [as 别名]
# 或者: from twext.python.filepath.CachingFilePath import exists [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():
#.........这里部分代码省略.........
示例5: AttachmentStorageTransport
# 需要导入模块: from twext.python.filepath import CachingFilePath [as 别名]
# 或者: from twext.python.filepath.CachingFilePath import exists [as 别名]
class AttachmentStorageTransport(StorageTransportBase):
_TEMPORARY_UPLOADS_DIRECTORY = "Temporary"
def __init__(self, attachment, contentType, dispositionName, creating=False, migrating=False):
super(AttachmentStorageTransport, self).__init__(
attachment, contentType, dispositionName)
fileDescriptor, fileName = self._temporaryFile()
# Wrap the file descriptor in a file object we can write to
self._file = os.fdopen(fileDescriptor, "w")
self._path = CachingFilePath(fileName)
self._hash = hashlib.md5()
self._creating = creating
self._migrating = migrating
self._txn.postAbort(self.aborted)
def _temporaryFile(self):
"""
Returns a (file descriptor, absolute path) tuple for a temporary file within
the Attachments/Temporary directory (creating the Temporary subdirectory
if it doesn't exist). It is the caller's responsibility to remove the
file.
"""
attachmentRoot = self._txn._store.attachmentsPath
tempUploadsPath = attachmentRoot.child(self._TEMPORARY_UPLOADS_DIRECTORY)
if not tempUploadsPath.exists():
tempUploadsPath.createDirectory()
return tempfile.mkstemp(dir=tempUploadsPath.path)
@property
def _txn(self):
return self._attachment._txn
def aborted(self):
"""
Transaction aborted - clean up temp files.
"""
if self._path.exists():
self._path.remove()
def write(self, data):
if isinstance(data, buffer):
data = str(data)
self._file.write(data)
self._hash.update(data)
@inlineCallbacks
def loseConnection(self):
"""
Note that when self._migrating is set we only care about the data and don't need to
do any quota checks/adjustments.
"""
# FIXME: this should be synchronously accessible; IAttachment should
# have a method for getting its parent just as CalendarObject/Calendar
# do.
# FIXME: If this method isn't called, the transaction should be
# prevented from committing successfully. It's not valid to have an
# attachment that doesn't point to a real file.
home = (yield self._txn.calendarHomeWithResourceID(self._attachment._ownerHomeID))
oldSize = self._attachment.size()
newSize = self._file.tell()
self._file.close()
# Check max size for attachment
if not self._migrating and newSize > config.MaximumAttachmentSize:
self._path.remove()
if self._creating:
yield self._attachment._internalRemove()
raise AttachmentSizeTooLarge()
# Check overall user quota
if not self._migrating:
allowed = home.quotaAllowedBytes()
if allowed is not None and allowed < ((yield home.quotaUsedBytes())
+ (newSize - oldSize)):
self._path.remove()
if self._creating:
yield self._attachment._internalRemove()
raise QuotaExceeded()
self._path.moveTo(self._attachment._path)
yield self._attachment.changed(
self._contentType,
self._dispositionName,
self._hash.hexdigest(),
newSize
)
#.........这里部分代码省略.........