本文整理汇总了Python中OFS.Image.File.filename方法的典型用法代码示例。如果您正苦于以下问题:Python File.filename方法的具体用法?Python File.filename怎么用?Python File.filename使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类OFS.Image.File
的用法示例。
在下文中一共展示了File.filename方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: testBlobbableOFSFile
# 需要导入模块: from OFS.Image import File [as 别名]
# 或者: from OFS.Image.File import filename [as 别名]
def testBlobbableOFSFile(self):
obj = File('foo', 'Foo', getFile('plone.pdf'), 'application/pdf')
obj.filename = 'foo.pdf'
blobbable = IBlobbable(obj)
target = Blob()
blobbable.feed(target)
self.assertEqual(target.open('r').read(),
getFile('plone.pdf').read())
self.assertEqual(blobbable.filename(), 'foo.pdf')
self.assertEqual(blobbable.mimetype(), 'application/pdf')
示例2: test_uploadFile
# 需要导入模块: from OFS.Image import File [as 别名]
# 或者: from OFS.Image.File import filename [as 别名]
def test_uploadFile(self):
file = File('foo', 'Foo', getFile('plone.pdf'), 'application/pdf')
file.filename = 'foo.pdf'
myUpload = makeFileUpload(file, 'test.gif')
myUpload.method = 'GET'
view = VNCCollabUtilView(self.portal, myUpload)
self.assertRaises(Exception, lambda: view.uploadFile(myUpload))
myUpload = makeFileUpload(file, 'test.gif')
myUpload.method = 'POST'
myUpload.form = {}
headers, output, request = makeResponse(myUpload)
view = VNCCollabUtilView(self.portal, request)
result = view.uploadFile(file)
self.assertEqual(result, 'http://nohost/plone/foo.pdf/edit')
myUpload = makeFileUpload(file, 'test.gif')
myUpload.method = 'POST'
myUpload.form = {'ajax_call': True}
headers, output, request = makeResponse(myUpload)
view = VNCCollabUtilView(self.portal, request)
result = view.uploadFile(file)
self.assertEqual(result, 'http://nohost/plone/foo.pdf-1/edit')
示例3: open
# 需要导入模块: from OFS.Image import File [as 别名]
# 或者: from OFS.Image.File import filename [as 别名]
try:
proxy.invokeFactory('Section', 'test-folder')
except xmlrpclib.ProtocolError:
print sys.exc_info()[1]
except xmlrpclib.Fault:
print "The id is invalid - it is already in use." # most likely
proxy = xmlrpclib.ServerProxy(url + '/test-folder')
proxy.setTitle('Test folder')
proxy.setDescription('This is a test folder')
# create image
proxy = xmlrpclib.ServerProxy(url) # reset
#wrappedData = xmlrpclib.Binary(open('screenshot.png').read())
filename = 'screenshot.png'
data = open(filename).read()
fileData = File(filename, filename, data, 'application/octet-stream')
fileData.filename = filename
wrappedData = fileData
try:
proxy.invokeFactory('Image', 'screenshot.png')
except xmlrpclib.ProtocolError:
print sys.exc_info()[1]
except xmlrpclib.Fault:
print "The id is invalid - it is already in use." # most likely
proxy = xmlrpclib.ServerProxy(url + '/screenshot.png')
proxy.setTitle('This is an image')
try:
proxy.setImage(wrappedData) # XXX this fails
except:
print sys.exc_info()[1]
示例4: __iter__
# 需要导入模块: from OFS.Image import File [as 别名]
# 或者: from OFS.Image.File import filename [as 别名]
def __iter__(self):
for item in self.previous:
yield item
metadata = {}
if self.metadata:
metadataFile = open(self.metadata, 'rb')
reader = csv.DictReader(metadataFile, delimiter=self.delimiter)
if reader.fieldnames is None:
raise ValueError("Metadata CSV is empty.")
if len(reader.fieldnames) is 1 and self.delimiter not in reader.fieldnames[0]:
raise ValueError("Metadata CSV does not use the specified delimiter: %s" %(self.delimiter))
if 'path' not in reader.fieldnames:
raise ValueError("Metadata CSV file does not have a 'path' column.")
if self.strict:
field_count = len(reader.fieldnames)
for row in reader:
if self.strict and field_count != len(row):
raise ValueError("Found a row in Metadata CSV that has a different count of fields \
compared to first row: %s" %(row))
path = row['path']
data = row.copy()
del data['path']
metadata[path] = data
if self.requireMetadata and not metadata:
raise ValueError("Metadata is required, but metadata file %s not given or empty" % self.metadata)
if not os.path.exists(self.directory):
raise ValueError("Directory %s does not exist" % self.directory)
for dirpath, dirnames, filenames in os.walk(self.directory):
wrapData = self.wrapData
# Create folders first, if necessary
for dirname in dirnames:
dirPath = os.path.join(dirpath, dirname)
zodbPath = self.getZODBPath(dirPath)
if self.ignored(zodbPath)[1]:
continue
_type = self.folderType
item = {'_type': self.folderType,
'_path': zodbPath}
if zodbPath in metadata:
item.update(metadata[zodbPath])
yield item
# Then import files
for filename in filenames:
filePath = os.path.join(dirpath, filename)
zodbPath = self.getZODBPath(filePath)
if self.ignored(zodbPath)[1]:
continue
if self.metadata and os.path.abspath(filePath) == os.path.abspath(self.metadata):
continue
if self.requireMetadata and zodbPath not in metadata:
continue
if zodbPath in metadata and 'portal_type' in metadata[zodbPath] and \
metadata[zodbPath]['portal_type'] in ['News Item', 'Document', 'Event']:
# if portal_type is given in metadata.csv, use it!
_type = metadata[zodbPath]['portal_type']
mimeType = 'text/html'
fieldname = 'text'
wrapData = False
#if the file is an image: use the image field of the news item, otherwise use the text field
if _type == 'News Item':
basename, extension = os.path.splitext(filename)
if extension and extension.lower() in mimetypes.types_map and mimetypes.types_map[extension.lower()].startswith('image'):
mimeType = mimetypes.types_map[extension.lower()]
fieldname = self.imageField # the same of news
wrapData = self.wrapData
else:
# else make it File or Image
_type = self.fileType
fieldname = self.fileField
mimeType = self.defaultMimeType
# Try to guess mime type and content type
basename, extension = os.path.splitext(filename)
if extension and extension.lower() in mimetypes.types_map:
mimeType = mimetypes.types_map[extension.lower()]
if mimeType.startswith('image'):
_type = self.imageType
#.........这里部分代码省略.........
示例5: sync_contacts
# 需要导入模块: from OFS.Image import File [as 别名]
# 或者: from OFS.Image.File import filename [as 别名]
def sync_contacts(context, ldap_records, set_owner=False):
"""Synchronize the given ldap results """
# Statistics
created = 0
modified = 0
skipped = 0
failed = 0
deleted = 0
dn_contact_id_mapping = {}
ct = getToolByName(context, 'portal_catalog')
mapper = get_ldap_attribute_mapper()
dummy_contact = createContent('ftw.contacts.Contact')
dummy_contact_folder = createContent('ftw.contacts.ContactFolder')
# 1st pass: create or update profiles
for dn, entry in ldap_records:
if not dn:
continue
dn = dn.decode('unicode_escape').encode('iso8859-1').decode('utf-8')
# Only entries with a contact id
contact_id = entry.get(mapper.id(), [None, ])[0]
if not contact_id:
skipped += 1
logger.debug("Skipping entry '%s'. No contact id." % dn)
continue
# Get the normalzied name for the contact with the given id. This has
# to be done on a dummy folder because existing content would influence
# the resulting id.
contact_id = INameChooser(dummy_contact_folder).chooseName(
contact_id, dummy_contact)
dn_contact_id_mapping[dn] = contact_id
contact = context.unrestrictedTraverse(contact_id, None)
changed = False
is_new_object = False
# Check if we really got the wanted object.
if not IContact.providedBy(contact):
contact = None
# Create contact
if contact is None:
try:
contact = createContent('ftw.contacts.Contact')
contact.id = contact_id
addContentToContainer(context, contact)
is_new_object = True
# invalid id
except BadRequest:
failed += 1
logger.warn("Could not create contact '%s' (invalid id)."
% contact_id)
continue
# Update/set field values
IContactSchema(contact).ldap_dn = dn
field_mapping = dict(getFields(IContactSchema))
for ldap_name, field_name in mapper.mapping().items():
field = field_mapping.get(field_name, None)
if field is None:
raise NotImplementedError()
value = entry.get(ldap_name, [''])[0]
current_value = field.get(contact)
if IBlobWrapper.providedBy(current_value):
current_value = current_value.data
if current_value != value:
# Handle images
if INamedImageField.providedBy(field) and value:
infile = StringIO(value)
filename = '%s.jpg' % contact_id
value = File(filename, filename, infile, 'image/jpeg')
value.filename = filename
field.set(contact, value)
changed = True
# Update/set fields with custom updaters
custom_updaters = getAdapters((contact, entry),
provided=ILDAPCustomUpdater)
for name, updater in custom_updaters:
changed = updater.update()
if is_new_object:
if set_owner:
# Grant owner role to contact
contact.__ac_local_roles__ = None
contact.manage_setLocalRoles(contact_id, ['Owner'])
contact.reindexObjectSecurity()
#.........这里部分代码省略.........