本文整理汇总了Python中ZODB.blob.Blob.committed方法的典型用法代码示例。如果您正苦于以下问题:Python Blob.committed方法的具体用法?Python Blob.committed怎么用?Python Blob.committed使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ZODB.blob.Blob
的用法示例。
在下文中一共展示了Blob.committed方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: NamedBlobFile
# 需要导入模块: from ZODB.blob import Blob [as 别名]
# 或者: from ZODB.blob.Blob import committed [as 别名]
class NamedBlobFile(Persistent):
"""A file stored in a ZODB BLOB, with a filename"""
implements(INamedBlobFile)
filename = FieldProperty(INamedFile["filename"])
def __init__(self, data="", contentType="", filename=None):
if filename is not None and contentType in ("", "application/octet-stream"):
contentType = get_contenttype(filename=filename)
self.contentType = contentType
self._blob = Blob()
f = self._blob.open("w")
f.write("")
f.close()
self._setData(data)
self.filename = filename
def open(self, mode="r"):
if mode != "r" and "size" in self.__dict__:
del self.__dict__["size"]
return self._blob.open(mode)
def openDetached(self):
return open(self._blob.committed(), "rb")
def _setData(self, data):
if "size" in self.__dict__:
del self.__dict__["size"]
# Search for a storable that is able to store the data
dottedName = ".".join((data.__class__.__module__, data.__class__.__name__))
storable = getUtility(IStorage, name=dottedName)
storable.store(data, self._blob)
def _getData(self):
fp = self._blob.open("r")
data = fp.read()
fp.close()
return data
_data = property(_getData, _setData)
data = property(_getData, _setData)
@property
def size(self):
if "size" in self.__dict__:
return self.__dict__["size"]
reader = self._blob.open()
reader.seek(0, 2)
size = int(reader.tell())
reader.close()
self.__dict__["size"] = size
return size
def getSize(self):
return self.size
示例2: File
# 需要导入模块: from ZODB.blob import Blob [as 别名]
# 或者: from ZODB.blob.Blob import committed [as 别名]
#.........这里部分代码省略.........
self.mimetype = mimetype or "application/octet-stream"
if stream is not None:
if mimetype is USE_MAGIC:
hint = USE_MAGIC
else:
hint = None
self.upload(stream, mimetype_hint=hint)
def upload(self, stream, mimetype_hint=None):
""" Replace the current contents of this file's blob with the
contents of ``stream``. ``stream`` must be a filelike object (it
must have a ``read`` method that takes a size argument).
``mimetype_hint`` can be any of the following:
- ``None``, meaning don't reset the current mimetype. This is the
default. If you already know the file's mimetype, and you don't
want it divined from a filename or stream content, use ``None`` as
the ``mimetype_hint`` value, and set the ``mimetype`` attribute of
the file object directly before or after calling this method.
- A string containing a filename that has an extension; the mimetype
will be derived from the extension in the filename using the Python
``mimetypes`` module, and the result will be set as the mimetype
attribute of this object.
- The constant :attr:`pyramid.file.USE_MAGIC`, which will derive
the mimetype using the ``python-magic`` library based on the
stream's actual content. The result will be set as the mimetype
attribute of this object.
.. warning::
On non-Linux systems, successful use of
:attr:`substanced.file.USE_MAGIC` requires the installation
of additional dependencies. See :ref:`optional_dependencies`.
"""
if not stream:
stream = io.StringIO()
fp = self.blob.open("w")
first = True
use_magic = False
if mimetype_hint is USE_MAGIC:
use_magic = True
if magic is None: # pragma: no cover
warnings.warn(
"The python-magic library does not have its requisite "
"dependencies installed properly, therefore the "
'"USE_MAGIC" flag passed to this method has been ignored '
'(it has been converted to "None"). The mimetype of '
"substanced.file.File objects created may be incorrect as "
"a result."
)
use_magic = False
mimetype_hint = None
if not use_magic:
if mimetype_hint is not None:
mimetype, _ = mimetypes.guess_type(mimetype_hint, strict=False)
if mimetype is None:
mimetype = "application/octet-stream"
self.mimetype = mimetype
for chunk in chunks(stream):
if use_magic and first:
first = False
m = magic.Magic(mime=True)
mimetype = m.from_buffer(chunk)
self.mimetype = u(mimetype)
fp.write(chunk)
fp.close()
def get_response(self, **kw):
""" Return a WebOb-compatible response object which uses the blob
content as the stream data and the mimetype of the file as the
content type. The ``**kw`` arguments will be passed to the
``pyramid.response.FileResponse`` constructor as its keyword
arguments."""
if not "content_type" in kw:
kw["content_type"] = str(self.mimetype)
path = self.blob.committed()
response = FileResponse(path, **kw)
return response
def get_size(self):
""" Return the size in bytes of the data in the blob associated with
the file"""
return os.stat(self.blob.committed()).st_size
def get_etag(self):
""" Return a token identifying the "version" of the file.
"""
self._p_activate()
mine = self._p_serial
blob = self.blob._p_serial
if blob == z64:
self.blob._p_activate()
blob = self.blob._p_serial
return oid_repr(max(mine, blob))
示例3: NyBlobFile
# 需要导入模块: from ZODB.blob import Blob [as 别名]
# 或者: from ZODB.blob.Blob import committed [as 别名]
class NyBlobFile(Persistent):
"""Naaya container for files stored using ZODB Blob"""
implements(INyBlobFile)
def __init__(self, **kwargs):
kwargs.setdefault('filename', None)
kwargs.setdefault('content_type', 'application/octet-stream')
for key, value in kwargs.iteritems():
setattr(self, key, value)
self._blob = Blob()
def open(self):
return self._blob.open('r')
def open_iterator(self):
return filestream_iterator(self._blob.committed(), 'rb')
def open_write(self):
return self._blob.open('w')
def send_data(self, RESPONSE, as_attachment=True, set_filename=True,
REQUEST=None):
"""NyBlobFiles can also be served using X-Sendfile.
In order to do so, you need to set X-NaayaEnableSendfile header
to "on" by frontend server for each request.
Lighttpd.conf example (working in proxy mode)::
server.modules += ( "mod_setenv" )
setenv.add-request-header = ( "X-NaayaEnableSendfile" => "on" )
proxy-core.allow-x-sendfile = "enable"
"""
RESPONSE.setHeader('Content-Length', self.size)
RESPONSE.setHeader('Content-Type', self.content_type)
if as_attachment:
header_value = "attachment"
if set_filename:
utf8_fname = urllib.quote(self.filename)
header_value += ";filename*=UTF-8''%s" % utf8_fname
RESPONSE.setHeader('Content-Disposition', header_value)
# Test for enabling of X-SendFile
if REQUEST is not None:
ny_xsendfile = REQUEST.get_header("X-NaayaEnableSendfile")
if ny_xsendfile is not None and ny_xsendfile=="on":
RESPONSE.setHeader("X-Sendfile", self._current_filename())
return "[body should be replaced by front-end server]"
if hasattr(RESPONSE, '_streaming'):
return self.open_iterator()
else:
return self.open().read()
def _current_filename(self):
""" Convenience function that returns blob's filename """
try:
return self._blob.committed()
except BlobError:
return self._blob._p_blob_uncommitted
def __repr__(self):
return '<%(cls)s %(fname)r (%(mime)s, %(size)r bytes)>' % {
'cls': self.__class__.__name__,
'fname': self.filename,
'mime': self.content_type,
'size': self.size,
}
示例4: BlobValue
# 需要导入模块: from ZODB.blob import Blob [as 别名]
# 或者: from ZODB.blob.Blob import committed [as 别名]
class BlobValue(object):
"""A BlobValue is using a ZODB Blob to store data. It handles both
the zope.app.file and zope.file features. It can be used as a blob
attribute, for more complex object. It can also be used as a mixin
with a Persistent class.
"""
implements(IBlobFile)
filename = FieldProperty(IBlobFile['filename'])
mimeType = FieldProperty(IBlobFile['mimeType'])
parameters = FieldProperty(IBlobFile['parameters'])
def __init__(self, data='', contentType='',
filename=None, parameters=None):
if filename:
filename = clean_filename(filename)
self.filename = filename
if not contentType and filename:
self.mimeType, enc = guess_content_type(name=filename)
elif not contentType:
self.mimeType = "application/octet-stream"
else:
self.mimeType = contentType
if parameters is None:
parameters = {}
else:
parameters = dict(parameters)
self.parameters = parameters
self._blob = Blob()
self.data = data
@property
def contentType(self):
return self.mimeType
def open(self, mode="r"):
return self._blob.open(mode)
def openDetached(self):
return file(self._blob.committed(), 'rb')
def __len__(self):
if self._blob == "":
return 0
reader = self._blob.open()
reader.seek(0, 2)
size = reader.tell()
reader.close()
return size
@property
def size(self):
return int(self.__len__())
@apply
def data():
"""The blob property using a IFileStorage adapter
to write down the value.
"""
def get(self):
blob = self._blob.open('r')
data = blob.read()
blob.close()
return data
def set(self, value):
stored = queryMultiAdapter((self._blob, value), IFileStorage)
if stored is not True:
raise StorageError(
"An error occured during the blob storage. Check the "
"value type (%r). This value should implement IFile, "
"IString or IUnicode (see `dolmen.builtins`)."
% value.__class__)
return property(get, set)
@property
def physical_path(self):
try:
filename = self._blob.committed()
except BlobError:
# We retry, the data has now been commited
# if possible by the ZODB blob.
try:
filename = self._blob.committed()
except BlobError:
# The retry failed, we return None.
return None
return filename
示例5: File
# 需要导入模块: from ZODB.blob import Blob [as 别名]
# 或者: from ZODB.blob.Blob import committed [as 别名]
#.........这里部分代码省略.........
def __nonzero__(self):
return self.size > 0
def clear(self):
self.filename = u''
self.mimeType = u''
self.data = u''
self.disablePreview = u''
self.disablePrint = u''
# NOTE: remove record from previewsCatalog
getUtility(IPreviewsCatalog).remove(self)
def open(self, mode="r"):
try:
if 'w' in mode:
if 'size' in self.__dict__:
del self.__dict__['size']
self.modified = zope.datetime.parseDatetimetz(
str(datetime.now()))
return self._blob.open(mode)
except POSKeyError:
print "Found damaged FileField: %s" % (self.filename)
return False
def openPreview(self, mode="r"):
""" returns openPreview for preview
"""
preview = getUtility(IPreviewsCatalog).getPreview(self)
return preview.openPreview(mode)
def openDetached(self, n=0):
try:
return file(self._blob.committed(), 'rb')
except BlobError:
if n < 2:
transaction.commit()
return self.openDetached(n + 1)
def openPreviewDetached(self):
""" returns openPreviewDetached for preview
"""
preview = getUtility(IPreviewsCatalog).getPreview(self)
return preview.openPreviewDetached()
def _show(self, request, filename=None, contentDisposition="inline"):
response = request.response
if not self.mimeType:
response.setHeader('Content-Type', 'application/octet-stream')
else:
response.setHeader('Content-Type', self.mimeType)
response.setHeader('Content-Length', self.size)
modified = self.modified
header = request.getHeader('If-Modified-Since', None)
lmt = long(zope.datetime.time(modified.isoformat()))
if header is not None:
header = header.split(';')[0]
try:
mod_since = long(zope.datetime.time(header))
except:
示例6: PreviewRecord
# 需要导入模块: from ZODB.blob import Blob [as 别名]
# 或者: from ZODB.blob.Blob import committed [as 别名]
class PreviewRecord(Persistent):
interface.implements(IPreviewRecord)
def __init__(self, parent=None):
self.parent = parent
self.previewSize = 0
self._previewBlob = Blob()
@getproperty
def previewData(self):
""" returns preview data """
fp = self._previewBlob.open('r')
data = fp.read()
fp.close()
return data
@getproperty
def previewSize(self):
if 'previewSize' in self.__dict__:
return self.__dict__['previewSize']
else:
reader = self.openPreview()
try:
reader.seek(0,2)
size = int(reader.tell())
finally:
reader.close()
self.__dict__['previewSize'] = size
return size
@setproperty
def previewSize(self, value):
self.__dict__['previewSize'] = value
def openPreview(self, mode="r"):
try:
return self._previewBlob.open(mode)
except AttributeError:
self._previewBlob = Blob()
return self._previewBlob.open(mode)
def openPreviewDetached(self, n=0):
try:
return file(self._previewBlob.committed(), 'rb')
except BlobError:
if n < 2:
transaction.commit()
return self.openPreviewDetached(n + 1)
def generatePreview(self):
MAX_VALUE = getUtility(IPreviewsCatalog).maxValue * 1024 * 1024
size = 0
if self.parent.size < MAX_VALUE and not self.parent.disablePreview:
logger.info(
"Start generating preview for: %s" % self.parent.filename)
fp = self.openPreview('w')
ff = self.parent.open()
try:
fp.write(api.convert(
ff, 'application/x-shockwave-flash', self.parent.mimeType,
filename=self.parent.filename))
size = int(fp.tell())
except (ConverterException, OSError), e:
logger.warning(
'Error generating preview for %s: %s',
self.parent.filename, e)
except: