|
| 1 | +import base64 |
| 2 | +import quopri |
| 3 | +from typing import List, Tuple, Dict, Union |
| 4 | +from email.mime import multipart, nonmultipart |
| 5 | +from email.message import _unquotevalue, Message |
| 6 | +import collections |
| 7 | + |
| 8 | + |
| 9 | +class MIMEFormdata(nonmultipart.MIMENonMultipart): |
| 10 | + def __init__(self, keyname, *args, **kwargs): |
| 11 | + super(MIMEFormdata, self).__init__(*args, **kwargs) |
| 12 | + self.add_header("Content-Disposition", f'form-data; name="{keyname}"') |
| 13 | + del self["MIME-Version"] |
| 14 | + |
| 15 | + |
| 16 | +class MIMEMultipart(multipart.MIMEMultipart): |
| 17 | + def __init__(self): |
| 18 | + super().__init__("form-data") |
| 19 | + del self["MIME-Version"] |
| 20 | + |
| 21 | + def _write_headers(self, generator): |
| 22 | + pass |
| 23 | + |
| 24 | + |
| 25 | +from .parameter import encode_parameter |
| 26 | + |
| 27 | + |
| 28 | +def parameters_from_multipart(data, media, rbq): |
| 29 | + params = list() |
| 30 | + for k in data.__fields_set__: |
| 31 | + v = getattr(data, k) |
| 32 | + ct = "text/plain" |
| 33 | + |
| 34 | + if (p := media.schema_.properties.get(k, None)) is not None: |
| 35 | + """OpenAPI 3.0 - Special Considerations for multipart Content""" |
| 36 | + if p.type == "array": |
| 37 | + p = p.items |
| 38 | + if p.type == "string" and ( |
| 39 | + p.format in ("binary", "base64") or getattr(p, "contentEncoding", None) is not None |
| 40 | + ): |
| 41 | + ct = "application/octet-stream" |
| 42 | + elif p.type == "object": |
| 43 | + ct = "application/json" |
| 44 | + |
| 45 | + if (e := media.encoding.get(k, None)) != None: |
| 46 | + ct = e.contentType or ct |
| 47 | + style = e.style or "form" |
| 48 | + explode = e.explode if e.explode is not None else (True if style == "form" else False) |
| 49 | + allowReserved = e.allowReserved or False |
| 50 | + headers = {name: rbq[name] for name in e.headers.keys() if name in rbq} |
| 51 | + else: |
| 52 | + allowReserved = False |
| 53 | + style = "form" |
| 54 | + explode = True |
| 55 | + headers = dict() |
| 56 | + |
| 57 | + m = media.schema_.properties[k] |
| 58 | + if isinstance(v, list): |
| 59 | + for i in v: |
| 60 | + r = encode_parameter(k, i, style, explode, allowReserved, "query", m.items) |
| 61 | + params.append((k, ct, r, headers, m.items)) |
| 62 | + else: |
| 63 | + r = encode_parameter(k, v, style, explode, allowReserved, "query", m) |
| 64 | + params.append((k, ct, r, headers, m)) |
| 65 | + return params |
| 66 | + |
| 67 | + |
| 68 | +def parameters_from_urlencoded(data: "BaseModel", media: "Media"): |
| 69 | + params = collections.defaultdict(lambda: list()) |
| 70 | + for k in data.__fields_set__: |
| 71 | + v = getattr(data, k) |
| 72 | + |
| 73 | + if (e := media.encoding.get(k, None)) != None: |
| 74 | + explode = e.explode |
| 75 | + allowReserved = e.allowReserved |
| 76 | + style = e.style |
| 77 | + else: |
| 78 | + explode = True |
| 79 | + allowReserved = False |
| 80 | + style = "form" |
| 81 | + |
| 82 | + m = media.schema_.properties[k] |
| 83 | + if isinstance(v, list): |
| 84 | + for i in v: |
| 85 | + r = encode_parameter(k, i, style, explode, allowReserved, "query", m.items) |
| 86 | + params[k].append(r) |
| 87 | + else: |
| 88 | + r = encode_parameter(k, v, style, explode, allowReserved, "query", m) |
| 89 | + params[k].append(r) |
| 90 | + return params |
| 91 | + |
| 92 | + |
| 93 | +def encode_content(data, codec): |
| 94 | + """ |
| 95 | + … supports all encodings defined in [RFC4648], including “base64” and “base64url”, as well as “quoted-printable” from [RFC2045]. |
| 96 | + :param data: |
| 97 | + :param codec: |
| 98 | + :return: |
| 99 | + """ |
| 100 | + if codec in ["base16", "base32", "base64", "base64url"]: |
| 101 | + if codec == "base16": |
| 102 | + r = base64.b16encode(data) |
| 103 | + elif codec == "base32": |
| 104 | + r = base64.b32encode(data) |
| 105 | + elif codec == "base64": |
| 106 | + r = base64.b64encode(data) |
| 107 | + elif codec == "base64url": |
| 108 | + r = base64.urlsafe_b64encode(data).rstrip(b"=") |
| 109 | + return r.decode() |
| 110 | + elif codec == "quoted-printable": |
| 111 | + return quopri.encodestring(data) |
| 112 | + else: |
| 113 | + raise ValueError(f"unsupported codec {codec}") |
| 114 | + |
| 115 | + |
| 116 | +def encode_multipart_parameters(fields: List[Tuple[str, str, Union[str, bytes], Dict[str, str], "Schema"]]): |
| 117 | + """ |
| 118 | + As shown in |
| 119 | + https://julien.danjou.info/handling-multipart-form-data-python/ |
| 120 | +
|
| 121 | + :param fields: |
| 122 | + :return: |
| 123 | + """ |
| 124 | + m = MIMEMultipart() |
| 125 | + |
| 126 | + for (field, ct, value, headers, schema) in fields: |
| 127 | + type, subtype, params = decode_content_type(ct) |
| 128 | + |
| 129 | + if type in ["image", "audio", "application"]: |
| 130 | + if isinstance(value, bytes): |
| 131 | + v = value |
| 132 | + else: |
| 133 | + v = value.encode() |
| 134 | + |
| 135 | + codec = "base64" |
| 136 | + |
| 137 | + if hasattr(schema, "contentEncoding"): |
| 138 | + """OpenAPI 3.1""" |
| 139 | + if schema.contentEncoding: |
| 140 | + codec = schema.contentEncoding |
| 141 | + headers["Content-Encoding"] = codec |
| 142 | + else: |
| 143 | + """OpenAPI 3.0""" |
| 144 | + |
| 145 | + data = encode_content(v, codec) |
| 146 | + |
| 147 | + elif type in ["text", "rfc822"]: |
| 148 | + data = value |
| 149 | + else: |
| 150 | + type, subtype = "text", "plain" |
| 151 | + data = value |
| 152 | + |
| 153 | + env = MIMEFormdata(field, type, subtype) |
| 154 | + |
| 155 | + for header, value in headers.items(): |
| 156 | + env.add_header(header, value) |
| 157 | + |
| 158 | + for k, v in params: |
| 159 | + env.set_param(k, v, "Content-Type") |
| 160 | + |
| 161 | + env.set_payload(data) |
| 162 | + |
| 163 | + m.attach(env) |
| 164 | + |
| 165 | + return m |
| 166 | + |
| 167 | + |
| 168 | +def decode_content_type(value: str) -> Tuple[str, str, List[Tuple[str, str]]]: |
| 169 | + """ |
| 170 | + msg = Message._get_params_preserve({"content-type": value}, header="content-type", failobj=None) |
| 171 | + ct, *params = list(map(lambda x: (x[0], _unquotevalue(x[1])) if x[0].lower() == x[0] else x, msg)) |
| 172 | + """ |
| 173 | + m = Message() |
| 174 | + m.add_header("content-type", value) |
| 175 | + ct, *params = m.get_params() |
| 176 | + |
| 177 | + type, _, subtype = ct[0].partition("/") |
| 178 | + return type, subtype, params |
0 commit comments