【问题标题】:How to access field names in MultipartDecoder如何访问 MultipartDecoder 中的字段名称
【发布时间】:2020-06-07 18:45:34
【问题描述】:

我正在使用 request-toolbelt 解码通过 HTTP POST 请求提交的表单字段。我成功地实例化了MultipartDecoder,就像描述的here 一样。现在我想通过发送请求时给它们的名称访问表单字段。

我能够得到这样的字段的名称

from requests_toolbelt.multipart import decoder
multipart_string = b"--ce560532019a77d83195f9e9873e16a1\r\nContent-Disposition: form-data; name=\"author\"\r\n\r\nJohn Smith\r\n--ce560532019a77d83195f9e9873e16a1\r\nContent-Disposition: form-data; name=\"file\"; filename=\"example2.txt\"\r\nContent-Type: text/plain\r\nExpires: 0\r\n\r\nHello World\r\n--ce560532019a77d83195f9e9873e16a1--\r\n"
content_type = "multipart/form-data; boundary=ce560532019a77d83195f9e9873e16a1"
decoder = decoder.MultipartDecoder(multipart_string, content_type)
field_name = decoder.parts[0].headers[b'Content-Disposition'].decode().split(';')[1].split('=')[1]

但这似乎完全错误。访问表单字段名称的常用方法是什么?

【问题讨论】:

    标签: python-requests multipartform-data


    【解决方案1】:

    我在下面使用它来解码该方法的结果:

        lst = []
    for part in decoder.MultipartDecoder(postdata.encode('utf-8'), content_type_header).parts:
        disposition = part.headers[b'Content-Disposition']
        params = {}
        for dispPart in str(disposition).split(';'):
            kv = dispPart.split('=', 2)
            params[str(kv[0]).strip()] = str(kv[1]).strip('\"\'\t \r\n') if len(kv)>1 else str(kv[0]).strip()
        type = part.headers[b'Content-Type'] if b'Content-Type' in part.headers else None
        lst.append({'content': part.content, "type": type, "params": params})
    

    我假设因为它是一个标准的 Mime 标头,所以有些函数可以做同样的事情,但代码也更少。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-17
      • 2016-11-26
      • 1970-01-01
      • 1970-01-01
      • 2021-02-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-07
      相关资源
      最近更新 更多