2018年9月13日 星期四

[python] WARNING:tornado.general:Invalid multipart/form-data

用 flask 自帶的 server,有時就是會發出 500 之後就無法動作,要重開一次。
想說試試用 tornado 來裝 flask。結果就發現一個 warning。

WARNING:tornado.general:Invalid multipart/form-data
查了一下,找到 tornado 原始碼 http://www.tornadoweb.org/en/stable/_modules/tornado/httputil.html,發現應該是 Content-Disposition 只要不是 form-data 就叫。
於是再找一下定義 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition

> Only the value form-data, as well as the optional directive name and filename, can be used in the HTTP context.
attachment 只能用在非 http 的情況。好吧,應該是要改成 form-data 才合規定。就改吧

## 同場加映
header 裡的的資料若是超過 ISO-8859-1 還是有救。
剛好在 Content-Disposition 定義找到
https://tools.ietf.org/html/rfc5987
ex: foo: bar; title*=UTF-8''%c2%a3%20and%20%e2%82%ac%20rates

## tornado 原始碼部份
def parse_multipart_form_data(boundary, data, arguments, files):
    """Parses a ``multipart/form-data`` body.

    The ``boundary`` and ``data`` parameters are both byte strings.
    The dictionaries given in the arguments and files parameters
    will be updated with the contents of the body.

    .. versionchanged:: 5.1

       Now recognizes non-ASCII filenames in RFC 2231/5987
       (``filename*=``) format.
    """
    # The standard allows for the boundary to be quoted in the header,
    # although it's rare (it happens at least for google app engine
    # xmpp).  I think we're also supposed to handle backslash-escapes
    # here but I'll save that until we see a client that uses them
    # in the wild.
    if boundary.startswith(b'"') and boundary.endswith(b'"'):
        boundary = boundary[1:-1]
    final_boundary_index = data.rfind(b"--" + boundary + b"--")
    if final_boundary_index == -1:
        gen_log.warning("Invalid multipart/form-data: no final boundary")
        return
    parts = data[:final_boundary_index].split(b"--" + boundary + b"\r\n")
    for part in parts:
        if not part:
            continue
        eoh = part.find(b"\r\n\r\n")
        if eoh == -1:
            gen_log.warning("multipart/form-data missing headers")
            continue
        headers = HTTPHeaders.parse(part[:eoh].decode("utf-8"))
        disp_header = headers.get("Content-Disposition", "")
        disposition, disp_params = _parse_header(disp_header)
        if disposition != "form-data" or not part.endswith(b"\r\n"):
            gen_log.warning("Invalid multipart/form-data")
            continue
        value = part[eoh + 4:-2]
        if not disp_params.get("name"):
            gen_log.warning("multipart/form-data value missing name")
            continue
        name = disp_params["name"]
        if disp_params.get("filename"):
            ctype = headers.get("Content-Type", "application/unknown")
            files.setdefault(name, []).append(HTTPFile(  # type: ignore
                filename=disp_params["filename"], body=value,
                content_type=ctype))
        else:
            arguments.setdefault(name, []).append(value)


沒有留言:

張貼留言