當前位置: 首頁>>代碼示例>>Python>>正文


Python mimetypes.guess_type方法代碼示例

本文整理匯總了Python中mimetypes.guess_type方法的典型用法代碼示例。如果您正苦於以下問題:Python mimetypes.guess_type方法的具體用法?Python mimetypes.guess_type怎麽用?Python mimetypes.guess_type使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在mimetypes的用法示例。


在下文中一共展示了mimetypes.guess_type方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: post

# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_type [as 別名]
def post(self, endpoint, args, data=None, files=None, filename=None,
             mode=None):
        if mode == 'nojsondumps':
            headers = {'Content-type': 'application/x-www-form-urlencoded; charset=utf-8'}
            r = requests.post(endpoint, params=args, data=data, headers=headers)
        elif files is None:
            headers = {'Content-type': 'application/json; charset=utf-8'}
            r = requests.post(endpoint, params=args, json=data, headers=headers)
        elif files is not None:
            mimetype = mimetypes.guess_type(files)[0]
            file = {filename: (files, open(files, 'rb'), mimetype)}
            r = requests.post(endpoint, params=args, json=data, files=file)
        r_json = r.json()
        if r_json.get('success'):
            return r_json
        else:
            raise MarketoException(r_json['errors'][0]) 
開發者ID:jepcastelein,項目名稱:marketo-rest-python,代碼行數:19,代碼來源:http_lib.py

示例2: encode_multipart_formdata

# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_type [as 別名]
def encode_multipart_formdata(files):
    """Return (content_type, body) ready for httplib.HTTP instance.

    files: a sequence of (name, filename, value) tuples for multipart uploads.
    filename can be a string or a tuple ('filename string', 'encoding')
    """
    BOUNDARY = '________ThIs_Is_tHe_bouNdaRY_$'
    L = []
    for key, filename, value in files:
        L.append('--' + BOUNDARY)

        fn_key, encoded = encode_filename(filename)
        tmpl = \
            'Content-Disposition: form-data; name="{key}"; {fn_key}={encoded}'
        L.append(tmpl.format(**locals()))
        ct = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
        L.append('Content-Type: %s' % ct)
        L.append('')
        L.append(value)
    L.append('--' + BOUNDARY + '--')
    L.append('')
    body = '\r\n'.join(L)
    content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
    return content_type, body 
開發者ID:cherrypy,項目名稱:cherrypy,代碼行數:26,代碼來源:test_http.py

示例3: upload_files

# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_type [as 別名]
def upload_files(self, *filenames):
        """ Upload files using form """
        # The ExitStack closes files for us when the with block exits
        with contextlib.ExitStack() as stack:
            files = {}
            for i, filename in enumerate(filenames):
                open_file = stack.enter_context(open(filename, 'rb'))
                mime_type, _ = mimetypes.guess_type(filename)
                if not mime_type or mime_type.split('/')[0] != 'image':
                    raise ValueError(
                        'Unknown image file type {}'.format(mime_type))

                name = os.path.basename(filename)
                try:
                    # until https://github.com/shazow/urllib3/issues/303 is
                    # resolved, only use the filename if it is Latin-1 safe
                    name.encode('latin1')
                except UnicodeEncodeError:
                    name = 'justfilename'
                files['file-upload[{}]'.format(i)] = (
                    name, open_file, mime_type)
            return self._perform(files=files) 
開發者ID:theirix,項目名稱:ptpimg-uploader,代碼行數:24,代碼來源:ptpimg_uploader.py

示例4: send_file

# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_type [as 別名]
def send_file(self, file_path, stream_id):
        """
        Send a file, obeying the rules of HTTP/2 flow control.
        """
        filesize = os.stat(file_path).st_size
        content_type, content_encoding = mimetypes.guess_type(file_path)
        response_headers = [
            (':status', '200'),
            ('content-length', str(filesize)),
            ('server', 'curio-h2'),
        ]
        if content_type:
            response_headers.append(('content-type', content_type))
        if content_encoding:
            response_headers.append(('content-encoding', content_encoding))

        self.conn.send_headers(stream_id, response_headers)
        await self.sock.sendall(self.conn.data_to_send())

        with open(file_path, 'rb', buffering=0) as f:
            await self._send_file_data(f, stream_id) 
開發者ID:python-hyper,項目名稱:hyper-h2,代碼行數:23,代碼來源:curio-server.py

示例5: sendFile

# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_type [as 別名]
def sendFile(self, file_path, stream_id):
        filesize = os.stat(file_path).st_size
        content_type, content_encoding = mimetypes.guess_type(
            file_path.decode('utf-8')
        )
        response_headers = [
            (':status', '200'),
            ('content-length', str(filesize)),
            ('server', 'twisted-h2'),
        ]
        if content_type:
            response_headers.append(('content-type', content_type))
        if content_encoding:
            response_headers.append(('content-encoding', content_encoding))

        self.conn.send_headers(stream_id, response_headers)
        self.transport.write(self.conn.data_to_send())

        f = open(file_path, 'rb')
        d = self._send_file(f, stream_id)
        d.addErrback(functools.partial(close_file, f)) 
開發者ID:python-hyper,項目名稱:hyper-h2,代碼行數:23,代碼來源:twisted-server.py

示例6: open_local_file

# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_type [as 別名]
def open_local_file(self, req):
        host = req.get_host()
        file = req.get_selector()
        localfile = url2pathname(file)
        stats = os.stat(localfile)
        size = stats[stat.ST_SIZE]
        modified = rfc822.formatdate(stats[stat.ST_MTIME])
        mtype = mimetypes.guess_type(file)[0]
        stats = os.stat(localfile)
        headers = mimetools.Message(StringIO(
            'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
            (mtype or 'text/plain', size, modified)))
        if host:
            host, port = splitport(host)
        if not host or \
           (not port and socket.gethostbyname(host) in self.get_names()):
            return addinfourl(open(localfile, 'rb'),
                              headers, 'file:'+file)
        raise URLError('file not on local host') 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:21,代碼來源:urllib2.py

示例7: upload_a_picture

# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_type [as 別名]
def upload_a_picture(picture):
    assert os.path.exists(picture)
    name = os.path.split(picture)[1]
    mimetype, _ = guess_type(name)
    assert mimetype
    if not mimetype.startswith('image'):
        raise ValueError('Cannot upload file: {}, which is not picture'.format(name))

    uptoken = get_uptoken()
    with open(picture, 'rb') as fp:
        files = {'token': (None, uptoken), 'file': (name, fp, mimetype)}
        res = requests.post(ENDPOINTS['picture_upload'], files=files)
    if res.status_code == 200:
        result = res.json()
        if result['success']:
            return result['key']
        else:
            raise RuntimeError('Picture upload fail')
    res.raise_for_status() 
開發者ID:Sorosliu1029,項目名稱:Jike-Metro,代碼行數:21,代碼來源:utils.py

示例8: get_content_type

# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_type [as 別名]
def get_content_type(self):
        """返回這個請求使用的 ``Content-Type`` 頭.

        .. versionadded:: 3.1
        """
        mime_type, encoding = mimetypes.guess_type(self.absolute_path)
        # per RFC 6713, use the appropriate type for a gzip compressed file
        if encoding == "gzip":
            return "application/gzip"
        # As of 2015-07-21 there is no bzip2 encoding defined at
        # http://www.iana.org/assignments/media-types/media-types.xhtml
        # So for that (and any other encoding), use octet-stream.
        elif encoding is not None:
            return "application/octet-stream"
        elif mime_type is not None:
            return mime_type
        # if mime_type not detected, use application/octet-stream
        else:
            return "application/octet-stream" 
開發者ID:tao12345666333,項目名稱:tornado-zh,代碼行數:21,代碼來源:web.py

示例9: testdata_scheme

# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_type [as 別名]
def testdata_scheme(qapp):
    try:
        global _qute_scheme_handler
        from qutebrowser.browser.webengine import webenginequtescheme
        from PyQt5.QtWebEngineWidgets import QWebEngineProfile
        webenginequtescheme.init()
        _qute_scheme_handler = webenginequtescheme.QuteSchemeHandler(
            parent=qapp)
        _qute_scheme_handler.install(QWebEngineProfile.defaultProfile())
    except ImportError:
        pass

    @qutescheme.add_handler('testdata')
    def handler(url):  # pylint: disable=unused-variable
        file_abs = os.path.abspath(os.path.dirname(__file__))
        filename = os.path.join(file_abs, os.pardir, 'end2end',
                                url.path().lstrip('/'))
        with open(filename, 'rb') as f:
            data = f.read()

        mimetype, _encoding = mimetypes.guess_type(filename)
        return mimetype, data 
開發者ID:qutebrowser,項目名稱:qutebrowser,代碼行數:24,代碼來源:fixtures.py

示例10: upload_doc

# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_type [as 別名]
def upload_doc(session, section_id, data_path, doc):
    doc_path = get_doc_path(data_path, doc)

    print('Processing %s%s (%s)' % (doc.location, doc.title, doc.guid))

    with ZipFile(doc_path) as zip_file:
        html_content, src_file_names = clean_html(zip_file.read('index.html'), doc)

        if len(src_file_names) > 5:
            print('Upload may failed if images more than 5')

        data_send = {
            'Presentation': (None, html_content, mimetypes.guess_type('index.html')[0])
        }

        for name in src_file_names:
            data_send[name] = (None, zip_file.read('index_files/' + name), mimetypes.guess_type(name)[0])

    resp = session.post(API_BASE + '/sections/%s/pages' % section_id, files=data_send)
    resp.raise_for_status() 
開發者ID:CzBiX,項目名稱:WizNote-to-OneNote,代碼行數:22,代碼來源:onenote.py

示例11: asgi_send_file

# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_type [as 別名]
def asgi_send_file(
    send, filepath, filename=None, content_type=None, chunk_size=4096
):
    headers = {}
    if filename:
        headers["Content-Disposition"] = 'attachment; filename="{}"'.format(filename)
    first = True
    async with aiofiles.open(str(filepath), mode="rb") as fp:
        if first:
            await asgi_start(
                send,
                200,
                headers,
                content_type or guess_type(str(filepath))[0] or "text/plain",
            )
            first = False
        more_body = True
        while more_body:
            chunk = await fp.read(chunk_size)
            more_body = len(chunk) == chunk_size
            await send(
                {"type": "http.response.body", "body": chunk, "more_body": more_body}
            ) 
開發者ID:simonw,項目名稱:datasette,代碼行數:25,代碼來源:asgi.py

示例12: async_callback_download

# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_type [as 別名]
def async_callback_download(path, ext, receiver):
    if path is None:
        return
    mimetype, _ = mimetypes.guess_type(path)
    if not mimetype:
        return
    mime = mimetype.split('/')[0]
    f = tgl.send_file
    if ext == "gif" or ext == "webp" or mime == "text":
        f = tgl.send_document
    elif mime == "image":
        f = tgl.send_image
    elif mime == "audio":
        f = tgl.send_audio
    elif mime == "video":
        f = tgl.send_video
        print("Sending file with mime {} from path {}".format(mimetype, path))
    f(receiver, path, utils.cb_rmp(path)) 
開發者ID:rockneurotiko,項目名稱:pybotgram,代碼行數:20,代碼來源:media.py

示例13: synchronous

# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_type [as 別名]
def synchronous(url, ext, receiver):
    path = ''
    try:
        path = utils.download_to_file(url, ext)
    except:
        print("Error downloading {}".format(url))
        return
    mimetype, _ = mimetypes.guess_type(path)
    if not mimetype:
        return
    mime = mimetype.split('/')[0]
    f = tgl.send_file
    if ext == "gif" or ext == "webp" or mime == "text":
        f = tgl.send_document
    elif mime == "image":
        f = tgl.send_image
    elif mime == "audio":
        f = tgl.send_audio
    elif mime == "video":
        f = tgl.send_video
    print("Sending file with mime {} from path {}".format(mimetype, path))
    f(receiver, path, utils.cb_rmp(path)) 
開發者ID:rockneurotiko,項目名稱:pybotgram,代碼行數:24,代碼來源:media.py

示例14: add_file

# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_type [as 別名]
def add_file(self, name, file, filename=None, content_type=None):
        """Adds a new file to the dict.  `file` can be a file name or
        a :class:`file`-like or a :class:`FileStorage` object.

        :param name: the name of the field.
        :param file: a filename or :class:`file`-like object
        :param filename: an optional filename
        :param content_type: an optional content type
        """
        if isinstance(file, FileStorage):
            value = file
        else:
            if isinstance(file, string_types):
                if filename is None:
                    filename = file
                file = open(file, "rb")
            if filename and content_type is None:
                content_type = (
                    mimetypes.guess_type(filename)[0] or "application/octet-stream"
                )
            value = FileStorage(file, filename, name, content_type)

        self.add(name, value) 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:25,代碼來源:datastructures.py

示例15: get_type_headers

# 需要導入模塊: import mimetypes [as 別名]
# 或者: from mimetypes import guess_type [as 別名]
def get_type_headers(filename, data):
    """
    Get the HTTP headers used for downloading or previewing the file.

    If the file is html, it will return headers which make browser start
    downloading.

    :param filename: file name string
    :param data: file data string
    """
    mimetype, encoding = guess_type(filename, data)
    if not mimetype:
        return None
    headers = {str("X-Content-Type-Options"): "nosniff"}
    if "html" in mimetype or "javascript" in mimetype or "svg" in mimetype:
        mimetype = "application/octet-stream"
        headers[str("Content-Disposition")] = "attachment"
    if encoding:
        mimetype += "; charset={encoding}".format(encoding=encoding)
    headers[str("Content-Type")] = mimetype
    return headers 
開發者ID:Pagure,項目名稱:pagure,代碼行數:23,代碼來源:mimetype.py


注:本文中的mimetypes.guess_type方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。