本文整理汇总了Python中zope.contenttype.guess_content_type函数的典型用法代码示例。如果您正苦于以下问题:Python guess_content_type函数的具体用法?Python guess_content_type怎么用?Python guess_content_type使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了guess_content_type函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_attachments
def get_attachments(self, fields, request):
"""Return all attachments uploaded in form.
"""
from ZPublisher.HTTPRequest import FileUpload
attachments = []
for field in fields:
if (field.isFileField() or field.Type() == 'DataGrid Field') \
and (getattr(self, 'showAll', True) \
or field.fgField.getName() in getattr(self, 'showFields', ())):
if field.Type() == 'DataGrid Field':
# check if it contains any File columns
for c in field.columnDefs:
if c['columnType'] == 'File':
for row in request.form.get('%s' % field.__name__, None):
if row['orderindex_'] != 'template_row_marker':
file = row[c['columnId']]
if file and isinstance(file, FileUpload) \
and file.filename != '':
file.seek(0) # rewind
data = file.read()
filename = file.filename
mimetype, enc = guess_content_type(filename, data, None)
attachments.append((filename, mimetype, enc, data))
else:
file = request.form.get('%s_file' % field.__name__, None)
if file and isinstance(file, FileUpload) and file.filename != '':
file.seek(0) # rewind
data = file.read()
filename = file.filename
mimetype, enc = guess_content_type(filename, data, None)
attachments.append((filename, mimetype, enc, data))
return attachments
示例2: test_add_two_files
def test_add_two_files(self):
ntypes = len(mimetypes.types_map)
contenttype.add_files([MIME_TYPES_1, MIME_TYPES_2])
ctype, encoding = contenttype.guess_content_type("foo.ztmt-1")
self.assert_(encoding is None)
self.assertEqual(ctype, "text/x-vnd.zope.test-mime-type-1")
ctype, encoding = contenttype.guess_content_type("foo.ztmt-2")
self.assert_(encoding is None)
self.assertEqual(ctype, "text/x-vnd.zope.test-mime-type-2")
self.check_types_count(2)
示例3: test_guess_content_type
def test_guess_content_type(self):
from zope.contenttype import add_files
from zope.contenttype import guess_content_type
filename = self._getFilename('mime.types-1')
add_files([filename])
ctype, encoding = guess_content_type(body=b'text file')
self.assertEqual(ctype, "text/plain")
ctype, encoding = guess_content_type(body=b'\001binary')
self.assertEqual(ctype, "application/octet-stream")
ctype, encoding = guess_content_type()
self.assertEqual(ctype, "text/x-unknown-content-type")
示例4: test_add_one_file
def test_add_one_file(self):
from zope.contenttype import add_files
from zope.contenttype import guess_content_type
filename = self._getFilename('mime.types-1')
add_files([filename])
ctype, encoding = guess_content_type("foo.ztmt-1")
self.assertTrue(encoding is None)
self.assertEqual(ctype, "text/x-vnd.zope.test-mime-type-1")
ctype, encoding = guess_content_type("foo.ztmt-1.gz")
self.assertEqual(encoding, "gzip")
self.assertEqual(ctype, "text/x-vnd.zope.test-mime-type-1")
self._check_types_count(1)
示例5: test_add_two_files
def test_add_two_files(self):
from zope.contenttype import add_files
from zope.contenttype import guess_content_type
filename1 = self._getFilename('mime.types-1')
filename2 = self._getFilename('mime.types-2')
add_files([filename1, filename2])
ctype, encoding = guess_content_type("foo.ztmt-1")
self.assertTrue(encoding is None)
self.assertEqual(ctype, "text/x-vnd.zope.test-mime-type-1")
ctype, encoding = guess_content_type("foo.ztmt-2")
self.assertTrue(encoding is None)
self.assertEqual(ctype, "text/x-vnd.zope.test-mime-type-2")
self._check_types_count(2)
示例6: htmlValue
def htmlValue(self, REQUEST):
""" return from REQUEST, this field's value in html.
"""
value = REQUEST.form.get(self.__name__, 'No Input')
header = ''
for col in self.columnDefs:
header += "<th>%s</th>" % col['columnTitle']
res = '<table class="listing"><thead><tr>%s</tr></thead><tbody>' % header
for adict in value:
if adict.get('orderindex_', '') != 'template_row_marker':
res += "<tr>"
for col in self.columnDefs:
akey = col['columnId']
if col['columnType'] == "File":
file = adict[akey]
file.seek(0)
fdata = file.read()
filename = file.filename
mimetype, enc = guess_content_type(filename, fdata, None)
out = "%s %s: %s bytes" % (filename, mimetype, len(fdata))
res = "%s\n<td>%s</td>" % (res, cgi.escape(out))
else:
res = "%s\n<td>%s</td>" % (res, cgi.escape(adict[akey]))
res += "</tr>"
return "%s</tbody></table>" % res
示例7: setImage
def setImage(self, value, refresh_exif=True, **kwargs):
request = self.REQUEST
tramlined = request.get('HTTP_X_TRAMLINED', '')
if not tramlined or (value == ''):
self.o_setImage(value, refresh_exif, **kwargs)
else:
fileinfo = value.read().split('|', 1)
filepath = fileinfo[0]
filesize = fileinfo[-1]
filename = value.filename
mimetype, enc = guess_content_type(filename)
self.tramline_size = int(filesize)
if self.tramline_size > 32000000:
raise "上传的文件大小超过 30M 限制,上传失败!"
self.setContentType(mimetype)
#用于修订IE的文件带路径问题
#不能用setFilename,它会失效,因为通过tramline后,图片为空,
#ImageField不会生成空的图片
title = filename.split("\\")[-1]
self.setTitle(title)
tramline_ok = request.response.getHeader('tramline_ok') or ''
if tramline_ok:
tramline_ok += '|'
tramline_ok += '%s:%s:%s' % (filepath,\
'/'.join(self.getPhysicalPath()), 's')
event.notify(ObjectEditedEvent(self))
request.response.setHeader('tramline_ok', tramline_ok)
示例8: onSuccess
def onSuccess(self, fields, REQUEST=None, loopstop=False):
# """
# saves data.
# """
if LP_SAVE_TO_CANONICAL and not loopstop:
# LinguaPlone functionality:
# check to see if we're in a translated
# form folder, but not the canonical version.
parent = self.aq_parent
if safe_hasattr(parent, 'isTranslation') and \
parent.isTranslation() and not parent.isCanonical():
# look in the canonical version to see if there is
# a matching (by id) save-data adapter.
# If so, call its onSuccess method
cf = parent.getCanonical()
target = cf.get(self.getId())
if target is not None and target.meta_type == 'FormSaveDataAdapter':
target.onSuccess(fields, REQUEST, loopstop=True)
return
from ZPublisher.HTTPRequest import FileUpload
data = []
for f in fields:
showFields = getattr(self, 'showFields', [])
if showFields and f.id not in showFields:
continue
if f.isFileField():
file = REQUEST.form.get('%s_file' % f.fgField.getName())
if isinstance(file, FileUpload) and file.filename != '':
file.seek(0)
fdata = file.read()
filename = file.filename
mimetype, enc = guess_content_type(filename, fdata, None)
if mimetype.find('text/') >= 0:
# convert to native eols
fdata = fdata.replace('\x0d\x0a', '\n').replace('\x0a', '\n').replace('\x0d', '\n')
data.append('%s:%s:%s:%s' % (filename, mimetype, enc, fdata))
else:
data.append('%s:%s:%s:Binary upload discarded' % (filename, mimetype, enc))
else:
data.append('NO UPLOAD')
elif not f.isLabel():
val = REQUEST.form.get(f.fgField.getName(), '')
if not type(val) in StringTypes:
# Zope has marshalled the field into
# something other than a string
val = str(val)
data.append(val)
if self.ExtraData:
for f in self.ExtraData:
if f == 'dt':
data.append(str(DateTime()))
else:
data.append(getattr(REQUEST, f, ''))
self._addDataRow(data)
示例9: getContents
def getContents(self):
##print "***** READ", self.path
f = open(self.path, 'rb')
data = f.read()
f.close()
content_type, enc = guess_content_type(self.path, data)
return dict(data = data, content_type = content_type)
示例10: setFile
def setFile(self, value, **kwargs):
request = self.REQUEST
tramlined = request.get('HTTP_X_TRAMLINED', '')
if not tramlined or (value == ''):
self.o_setFile(value, **kwargs)
else:
fileinfo = value.read().split('|', 1)
filepath = fileinfo[0]
filesize = fileinfo[-1]
filename = value.filename
mimetype, enc = guess_content_type(filename)
self.tramline_size = int(filesize)
if self.tramline_size > 32000000:
raise "上传的文件大小超过 30M 限制,上传失败!"
self.setContentType(mimetype)
#用于修订IE的文件带路径问题
title = filename.split("\\")[-1]
self.setFilename(title)
self.setTitle(title)
# 是否只上传1个文件?
tramline_ok = request.response.getHeader('tramline_ok') or ''
# 不是第一文件了,需要用分隔符合并起来
if tramline_ok:
tramline_ok += '|'
tramline_ok += '%s:%s:%s' % (filepath,\
'/'.join(self.getPhysicalPath()), '')
event.notify(ObjectEditedEvent(self))
request.response.setHeader('tramline_ok', tramline_ok)
示例11: _get_content_type
def _get_content_type(self, file, body, id, content_type=None):
# Consult self.content_type first, this is either
# the default (unknown/unknown) or it got a value from a
# .metadata file
default_type = 'unknown/unknown'
if getattr(self, 'content_type', default_type) != default_type:
return self.content_type
# Next, look at file headers
headers=getattr(file, 'headers', None)
if headers and headers.has_key('content-type'):
content_type=headers['content-type']
else:
# Last resort: Use the (imperfect) content type guessing
# mechanism from OFS.Image, which ultimately uses the
# Python mimetypes module.
if not isinstance(body, basestring):
body = body.data
content_type, enc=guess_content_type(
getattr(file, 'filename',id), body, content_type)
if (enc is None
and (content_type.startswith('text/') or
content_type.startswith('application/'))
and body.startswith(codecs.BOM_UTF8)):
content_type += '; charset=utf-8'
return content_type
示例12: actual_process
def actual_process(self, data):
cols = data['columns']
csv = BytesIO(data['csv']) # The file is Bytes, encoded.
encoding = self.guess_encoding(data['csv'])
# TODO: Delivery?
try:
dialect = Sniffer().sniff(csv.readline(), [',', '\t'])
except err:
dialect = excel
csv.seek(0)
reader = UnicodeDictReader(csv, cols, encoding=encoding, dialect=dialect)
profiles = []
retval = None
try:
next(reader) # Skip the first row (the header)
except UnicodeDecodeError as e:
t = guess_content_type(body=data['csv'])[0]
msg = 'The file is different from what is required. (It '\
'appears to be a {0} file.) Please check that you '\
'selected the correct CSV file.'
m = {'status': -2,
'message': [msg.format(t.split('/')[0]), str(e), t]}
retval = to_json(m)
except StopIteration:
msg = 'The file appears to be empty. Please check that you '\
'generated the CSV file correctly.'
m = {'status': -5, 'message': [msg, 'no-rows']}
retval = to_json(m)
else:
rowCount = 0
for row in reader:
rowCount += 1
if len(row) != len(cols):
# *Technically* the number of columns in CSV rows can be
# arbitary. However, I am enforcing a strict
# interpretation for sanity's sake.
msg = 'Row {0} had {1} columns, rather than {2}. ' \
'Please check the file.'
# Name hack.
m = {'status': -3,
'message': [msg.format(rowCount, len(row),
len(cols))]}
retval = to_json(m)
profiles = []
# --=mpj17=-- I think this is the first time I have used
# break in actual code. Wow.
break
profiles.append(row)
if profiles and (not retval):
retval = to_json(profiles)
elif (not profiles) and not(retval):
msg = 'No rows were found in the CSV file. '\
'Please check that you selected the correct CSV file.'
m = {'status': -4,
'message': [msg, 'no-rows']}
retval = to_json(m)
assert retval, 'No retval'
return retval
示例13: __call__
def __call__(self, client=None, REQUEST={}, RESPONSE=None, **kw):
"""Render the document with the given client object.
o If supplied, use REQUEST mapping, Response, and key word arguments.
"""
if not self._cache_namespace_keys:
data = self.ZCacheable_get(default=_marker)
if data is not _marker:
# Return cached results.
return data
__traceback_supplement__ = (PathTracebackSupplement, self)
kw['document_id'] = self.getId()
kw['document_title'] = self.title
if hasattr(self, 'aq_explicit'):
bself = self.aq_explicit
else:
bself = self
security = getSecurityManager()
security.addContext(self)
try:
if client is None:
# Called as subtemplate, so don't need error propagation!
r = HTML.__call__(self, bself, REQUEST, **kw)
if RESPONSE is None:
result = r
else:
result = decapitate(r, RESPONSE)
if not self._cache_namespace_keys:
self.ZCacheable_set(result)
return result
r = HTML.__call__(self, (client, bself), REQUEST, **kw)
if RESPONSE is None or not isinstance(r, str):
if not self._cache_namespace_keys:
self.ZCacheable_set(r)
return r
finally:
security.removeContext(self)
have_key = RESPONSE.headers.__contains__
if not (have_key('content-type') or have_key('Content-Type')):
if 'content_type' in self.__dict__:
c = self.content_type
else:
encoding = getattr(self, 'encoding', default_encoding)
if six.PY2 and not isinstance(r, six.text_type):
# Prevent double-encoding edge cases under Python 2
r = r.decode(encoding)
c, e = guess_content_type(self.getId(), r.encode(encoding))
RESPONSE.setHeader('Content-Type', c)
result = decapitate(r, RESPONSE)
if not self._cache_namespace_keys:
self.ZCacheable_set(result)
return result
示例14: _buildSObjectFromForm
def _buildSObjectFromForm(self, fields, REQUEST=None):
""" Used by the onSuccess handler to convert the fields from the form
into the fields to be stored in Salesforce.
Also munges dates into the required (mm/dd/yyyy) format.
"""
logger.debug('Calling _buildSObjectFromForm()')
formPath = aq_parent(self).getPhysicalPath()
sObject = dict(type=self.SFObjectType)
for field in fields:
formFieldPath = field.getPhysicalPath()
formFieldValue = REQUEST.form.get(field.getFieldFormName())
if field.meta_type == 'FormDateField':
if formFieldValue:
formFieldValue = DateTime(formFieldValue + ' GMT+0').HTML4()
else:
# we want to throw this value away rather than pass along
# to salesforce, which would ultimately raise a SoapFaultError
# due to invalid xsd:dateTime formatting
continue
elif field.isFileField():
file = formFieldValue
if file and isinstance(file, FileUpload) and file.filename != '':
file.seek(0) # rewind
data = file.read()
filename = file.filename
mimetype, enc = guess_content_type(filename, data, None)
from base64 import encodestring
formFieldValue = encodestring(data)
filenameFieldName = self._getSFFieldForFormField(list(formFieldPath) + ['filename'], formPath)
if filenameFieldName:
sObject[filenameFieldName] = filename
mimetypeFieldName = self._getSFFieldForFormField(list(formFieldPath) + ['mimetype'], formPath)
if mimetypeFieldName:
sObject[mimetypeFieldName] = mimetype
salesforceFieldName = self._getSFFieldForFormField(formFieldPath, formPath)
if not salesforceFieldName:
# We haven't found a mapping to a Salesforce field.
continue
if 'creationMode' in self.Schema() and self.getCreationMode() == 'update' and formFieldValue == '':
# The adapter is in update mode and one of the fields has a value
# of an empty string. If that field is nillable in Salesforce, we
# should set its value to None so that it gets cleared.
salesforceField = self._querySFFieldsForType()[salesforceFieldName]
if getattr(salesforceField, 'nillable', False):
formFieldValue = None
elif formFieldValue is None:
# The form field was left blank and we therefore
# don't care about passing along that value, since
# the Salesforce object field may have it's own ideas
# about data types and or default values.
continue
sObject[salesforceFieldName] = formFieldValue
return sObject
示例15: _get_content_type
def _get_content_type(self, file, body, id, content_type=None):
headers=getattr(file, 'headers', None)
if headers and 'content-type' in headers:
content_type=headers['content-type']
else:
if not isinstance(body, str): body=body.data
content_type, enc=guess_content_type(
getattr(file, 'filename',id), body, content_type)
return content_type