fields.py 支持中文文件上傳

from future import absolute_import
import email.utils
import mimetypes

from .packages import six

def guess_content_type(filename, default='application/octet-stream'):
"""
Guess the "Content-Type" of a file.

:param filename:
    The filename to guess the "Content-Type" of using :mod:`mimetypes`.
:param default:
    If no "Content-Type" can be guessed, default to `default`.
"""
if filename:
    return mimetypes.guess_type(filename)[0] or default
return default

def format_header_param(name, value):
"""
Helper function to format and quote a single header parameter.

Particularly useful for header parameters which might contain
non-ASCII values, like file names. This follows RFC 2231, as
suggested by RFC 2388 Section 4.4.

:param name:
    The name of the parameter, a string expected to be ASCII only.
:param value:
    The value of the parameter, provided as a unicode string.
"""
if not any(ch in value for ch in '"\\\r\n'):
    result = '%s="%s"' % (name, value)
    try:
        result.encode('ascii')
    except (UnicodeEncodeError, UnicodeDecodeError):
        pass
    else:
        return result
if not six.PY3 and isinstance(value, six.text_type):  # Python 2:
    value = value.encode('utf-8')
value = email.utils.encode_rfc2231(value, 'utf-8')
# value = '%s*=%s' % (name, value)
value = '%s="%s"' % (name, value.encode('utf-8'))
return value

class RequestField(object):
"""
A data container for request body parameters.

:param name:
    The name of this request field.
:param data:
    The data/value body.
:param filename:
    An optional filename of the request field.
:param headers:
    An optional dict-like object of headers to initially use for the field.
"""
def __init__(self, name, data, filename=None, headers=None):
    self._name = name
    self._filename = filename
    self.data = data
    self.headers = {}
    if headers:
        self.headers = dict(headers)

@classmethod
def from_tuples(cls, fieldname, value):
    """
    A :class:`~urllib3.fields.RequestField` factory from old-style tuple parameters.

    Supports constructing :class:`~urllib3.fields.RequestField` from
    parameter of key/value strings AND key/filetuple. A filetuple is a
    (filename, data, MIME type) tuple where the MIME type is optional.
    For example::

        'foo': 'bar',
        'fakefile': ('foofile.txt', 'contents of foofile'),
        'realfile': ('barfile.txt', open('realfile').read()),
        'typedfile': ('bazfile.bin', open('bazfile').read(), 'image/jpeg'),
        'nonamefile': 'contents of nonamefile field',

    Field names and filenames must be unicode.
    """
    if isinstance(value, tuple):
        if len(value) == 3:
            filename, data, content_type = value
        else:
            filename, data = value
            content_type = guess_content_type(filename)
    else:
        filename = None
        content_type = None
        data = value

    request_param = cls(fieldname, data, filename=filename)
    request_param.make_multipart(content_type=content_type)

    return request_param

def _render_part(self, name, value):
    """
    Overridable helper function to format a single header parameter.

    :param name:
        The name of the parameter, a string expected to be ASCII only.
    :param value:
        The value of the parameter, provided as a unicode string.
    """
    return format_header_param(name, value)

def _render_parts(self, header_parts):
    """
    Helper function to format and quote a single header.

    Useful for single headers that are composed of multiple items. E.g.,
    'Content-Disposition' fields.

    :param header_parts:
        A sequence of (k, v) typles or a :class:`dict` of (k, v) to format
        as `k1="v1"; k2="v2"; ...`.
    """
    parts = []
    iterable = header_parts
    if isinstance(header_parts, dict):
        iterable = header_parts.items()

    for name, value in iterable:
        if value:
            parts.append(self._render_part(name, value))

    return '; '.join(parts)

def render_headers(self):
    """
    Renders the headers for this request field.
    """
    lines = []

    sort_keys = ['Content-Disposition', 'Content-Type', 'Content-Location']
    for sort_key in sort_keys:
        if self.headers.get(sort_key, False):
            lines.append('%s: %s' % (sort_key, self.headers[sort_key]))

    for header_name, header_value in self.headers.items():
        if header_name not in sort_keys:
            if header_value:
                lines.append('%s: %s' % (header_name, header_value))

    lines.append('\r\n')
    return '\r\n'.join(lines)

def make_multipart(self, content_disposition=None, content_type=None,
                   content_location=None):
    """
    Makes this request field into a multipart request field.

    This method overrides "Content-Disposition", "Content-Type" and
    "Content-Location" headers to the request parameter.

    :param content_type:
        The 'Content-Type' of the request body.
    :param content_location:
        The 'Content-Location' of the request body.

    """
    self.headers['Content-Disposition'] = content_disposition or 'form-data'
    self.headers['Content-Disposition'] += '; '.join([
        '', self._render_parts(
            (('name', self._name), ('filename', self._filename))
        )
    ])
    self.headers['Content-Type'] = content_type
    self.headers['Content-Location'] = content_location
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末琅锻,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子樟澜,更是在濱河造成了極大的恐慌琐旁,老刑警劉巖涮阔,帶你破解...
    沈念sama閱讀 219,490評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異灰殴,居然都是意外死亡敬特,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門牺陶,熙熙樓的掌柜王于貴愁眉苦臉地迎上來伟阔,“玉大人,你說我怎么就攤上這事掰伸≈迓” “怎么了?”我有些...
    開封第一講書人閱讀 165,830評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵狮鸭,是天一觀的道長(zhǎng)合搅。 經(jīng)常有香客問我,道長(zhǎng)歧蕉,這世上最難降的妖魔是什么灾部? 我笑而不...
    開封第一講書人閱讀 58,957評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮惯退,結(jié)果婚禮上赌髓,老公的妹妹穿的比我還像新娘。我一直安慰自己催跪,他們只是感情好锁蠕,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,974評(píng)論 6 393
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著叠荠,像睡著了一般匿沛。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上榛鼎,一...
    開封第一講書人閱讀 51,754評(píng)論 1 307
  • 那天逃呼,我揣著相機(jī)與錄音鳖孤,去河邊找鬼。 笑死抡笼,一個(gè)胖子當(dāng)著我的面吹牛苏揣,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播推姻,決...
    沈念sama閱讀 40,464評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼平匈,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了藏古?” 一聲冷哼從身側(cè)響起增炭,我...
    開封第一講書人閱讀 39,357評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎拧晕,沒想到半個(gè)月后隙姿,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,847評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡厂捞,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,995評(píng)論 3 338
  • 正文 我和宋清朗相戀三年输玷,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片靡馁。...
    茶點(diǎn)故事閱讀 40,137評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡欲鹏,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出臭墨,到底是詐尸還是另有隱情赔嚎,我是刑警寧澤,帶...
    沈念sama閱讀 35,819評(píng)論 5 346
  • 正文 年R本政府宣布胧弛,位于F島的核電站尽狠,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏叶圃。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,482評(píng)論 3 331
  • 文/蒙蒙 一践图、第九天 我趴在偏房一處隱蔽的房頂上張望掺冠。 院中可真熱鬧,春花似錦码党、人聲如沸德崭。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)眉厨。三九已至,卻和暖如春兽狭,著一層夾襖步出監(jiān)牢的瞬間憾股,已是汗流浹背鹿蜀。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評(píng)論 1 272
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留服球,地道東北人茴恰。 一個(gè)月前我還...
    沈念sama閱讀 48,409評(píng)論 3 373
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像斩熊,于是被迫代替她去往敵國(guó)和親往枣。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,086評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理粉渠,服務(wù)發(fā)現(xiàn)分冈,斷路器,智...
    卡卡羅2017閱讀 134,672評(píng)論 18 139
  • pyspark.sql模塊 模塊上下文 Spark SQL和DataFrames的重要類: pyspark.sql...
    mpro閱讀 9,457評(píng)論 0 13
  • 身的外皮 一層一層 撕了又撕 無濟(jì)于事 糾扯不掉的疤結(jié) 在心的地方黑舊 痛的你清醒般的活著 重重的殼里 裹緊透徹的...
    樊小四閱讀 215評(píng)論 0 3
  • 東城漸覺春光好霸株〉癯粒縠皺波紋迎客棹。 綠楊煙外曉寒輕淳衙,紅杏枝頭春意鬧蘑秽。浮生長(zhǎng)恨歡娛少◇锱剩肯愛千金輕一笑肠牲。 為君持酒勸斜陽(yáng)...
    QDLCC閱讀 166評(píng)論 0 0
  • 你在夢(mèng)里等我時(shí),我被關(guān)在了睡眠的外面靴跛。 我能睡著的時(shí)候缀雳,夢(mèng)里卻已經(jīng)沒了人煙。 你怕吵醒我梢睛,輕輕地肥印,輕輕地,合上臥室...
    ProjectAlpha閱讀 228評(píng)論 0 2