• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python contenttype.guess_content_type函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中zope.contenttype.guess_content_type函数的典型用法代码示例。如果您正苦于以下问题:Python guess_content_type函数的具体用法?Python guess_content_type怎么用?Python guess_content_type使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了guess_content_type函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:Conectivo,项目名称:Products.PloneFormGen,代码行数:35,代码来源:formMailerAdapter.py


示例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)
开发者ID:grodniewicz,项目名称:oship,代码行数:10,代码来源:testContentTypes.py


示例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")
开发者ID:pombredanne,项目名称:zope.contenttype,代码行数:11,代码来源:testContentTypes.py


示例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)
开发者ID:pombredanne,项目名称:zope.contenttype,代码行数:12,代码来源:testContentTypes.py


示例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)
开发者ID:pombredanne,项目名称:zope.contenttype,代码行数:13,代码来源:testContentTypes.py


示例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
开发者ID:collective,项目名称:Products.PFGDataGrid,代码行数:29,代码来源:datagridff.py


示例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)
开发者ID:austgl,项目名称:everydo-project,代码行数:29,代码来源:tramlinesupport.py


示例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)
开发者ID:Conectivo,项目名称:Products.PloneFormGen,代码行数:60,代码来源:saveDataAdapter.py


示例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)
开发者ID:resa89,项目名称:imusite,代码行数:7,代码来源:fileresource.py


示例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)
开发者ID:austgl,项目名称:everydo-project,代码行数:34,代码来源:tramlinesupport.py


示例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
开发者ID:goschtl,项目名称:zope,代码行数:27,代码来源:FSFile.py


示例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
开发者ID:piersg,项目名称:gs.group.member.invite.csv,代码行数:59,代码来源:csv2json.py


示例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
开发者ID:zopefoundation,项目名称:Zope,代码行数:59,代码来源:DTMLDocument.py


示例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
开发者ID:smcmahon,项目名称:Products.salesforcepfgadapter,代码行数:58,代码来源:salesforcepfgadapter.py


示例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
开发者ID:Goldmund-Wyldebeast-Wunderliebe,项目名称:Zope,代码行数:9,代码来源:Image.py


示例16: __init__

    def __init__(self, path, name):
        self.path = path
        self.__name__ = name
        with open(path, 'rb') as f:
            self.data = f.read()
        self.content_type = guess_content_type(path, self.data)[0]

        self.lmt = float(os.path.getmtime(path)) or time.time()
        self.lmh = formatdate(self.lmt, usegmt=True)
开发者ID:zopefoundation,项目名称:zope.browserresource,代码行数:9,代码来源:file.py


示例17: __call__

 def __call__(self, name, content_type, data):
     if not content_type and data:
         content_type, width, height = getImageInfo(data)
     if not content_type:
         content_type, encoding = guess_content_type(name, '', '')
     res = LocalFsFile(
         name, os.path.join(self.context.abspath, name), content_type)
     res.__parent__ = self.context
     return res
开发者ID:Zojax,项目名称:zojax.localfs,代码行数:9,代码来源:file.py


示例18: __init__

 def __init__(self, data='', content_type='', filename=None):
     self.data = data
     if filename is not None:
         self.filename = clean_filename(filename)
     if not content_type and filename:
         # If we handle large files, we don't want them read just
         # to guess the content type. We provide only the filename.
         self.content_type, enc = guess_content_type(name=filename)
     else:
         self.content_type = content_type
开发者ID:trollfot,项目名称:dolmen.file,代码行数:10,代码来源:file.py


示例19: __init__

    def __init__(self, path, name):
        self.path = path

        f = open(path, 'rb')
        self.data = f.read()
        f.close()
        self.content_type, enc = guess_content_type(path, self.data)
        self.__name__ = name
        self.lmt = float(os.path.getmtime(path)) or time.time()
        self.lmh = rfc1123_date(self.lmt)
开发者ID:abramhindle,项目名称:UnnaturalCodeFork,代码行数:10,代码来源:folder.py


示例20: my_guess_content_type

def my_guess_content_type(path, data):
    content_type, enc = guess_content_type(path, data)
    if content_type in ('text/plain', 'text/html'):
        if os.path.basename(path).endswith('.js-slimmed'):
            content_type = 'application/x-javascript'
        elif os.path.basename(path).find('.css-slimmed') > -1:
            # the find() covers both 'foo.css-slimmed' and
            # 'foo.css-slimmed-data64expanded'
            content_type = 'text/css'
    return content_type, enc
开发者ID:BillTheBest,项目名称:IssueTrackerProduct,代码行数:10,代码来源:__init__.py



注:本文中的zope.contenttype.guess_content_type函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python datetime.parseDatetimetz函数代码示例发布时间:2022-05-26
下一篇:
Python interfaces.IReadContainer类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap