Skip to content

API Reference

Classes

BaseParser

This class is the base class for all parsers. It contains the logic for calling and adding callbacks.

A callback can be one of two different forms. "Notification callbacks" are callbacks that are called when something happens - for example, when a new part of a multipart message is encountered by the parser. "Data callbacks" are called when we get some sort of data - for example, part of the body of a multipart chunk. Notification callbacks are called with no parameters, whereas data callbacks are called with three, as follows::

data_callback(data, start, end)

The "data" parameter is a bytestring (i.e. "foo" on Python 2, or b"foo" on Python 3). "start" and "end" are integer indexes into the "data" string that represent the data of interest. Thus, in a data callback, the slice data[start:end] represents the data that the callback is "interested in". The callback is not passed a copy of the data, since copying severely hurts performance.

Source code in python_multipart/multipart.py
class BaseParser:
    """This class is the base class for all parsers.  It contains the logic for
    calling and adding callbacks.

    A callback can be one of two different forms.  "Notification callbacks" are
    callbacks that are called when something happens - for example, when a new
    part of a multipart message is encountered by the parser.  "Data callbacks"
    are called when we get some sort of data - for example, part of the body of
    a multipart chunk.  Notification callbacks are called with no parameters,
    whereas data callbacks are called with three, as follows::

        data_callback(data, start, end)

    The "data" parameter is a bytestring (i.e. "foo" on Python 2, or b"foo" on
    Python 3).  "start" and "end" are integer indexes into the "data" string
    that represent the data of interest.  Thus, in a data callback, the slice
    `data[start:end]` represents the data that the callback is "interested in".
    The callback is not passed a copy of the data, since copying severely hurts
    performance.
    """

    def __init__(self) -> None:
        self.logger = logging.getLogger(__name__)
        self.callbacks: QuerystringCallbacks | OctetStreamCallbacks | MultipartCallbacks = {}

    def callback(
        self, name: CallbackName, data: bytes | None = None, start: int | None = None, end: int | None = None
    ) -> None:
        """This function calls a provided callback with some data.  If the
        callback is not set, will do nothing.

        Args:
            name: The name of the callback to call (as a string).
            data: Data to pass to the callback.  If None, then it is assumed that the callback is a notification
                callback, and no parameters are given.
            end: An integer that is passed to the data callback.
            start: An integer that is passed to the data callback.
        """
        on_name = "on_" + name
        func = self.callbacks.get(on_name)
        if func is None:
            return
        func = cast("Callable[..., Any]", func)
        # Depending on whether we're given a buffer...
        if data is not None:
            # Don't do anything if we have start == end.
            if start is not None and start == end:
                return

            self.logger.debug("Calling %s with data[%d:%d]", on_name, start, end)
            func(data, start, end)
        else:
            self.logger.debug("Calling %s with no data", on_name)
            func()

    def set_callback(self, name: CallbackName, new_func: Callable[..., Any] | None) -> None:
        """Update the function for a callback.  Removes from the callbacks dict
        if new_func is None.

        :param name: The name of the callback to call (as a string).

        :param new_func: The new function for the callback.  If None, then the
                         callback will be removed (with no error if it does not
                         exist).
        """
        if new_func is None:
            self.callbacks.pop("on_" + name, None)  # type: ignore[misc]
        else:
            self.callbacks["on_" + name] = new_func  # type: ignore[literal-required]

    def close(self) -> None:
        pass  # pragma: no cover

    def finalize(self) -> None:
        pass  # pragma: no cover

    def __repr__(self) -> str:
        return "%s()" % self.__class__.__name__

Functions

callback(name, data=None, start=None, end=None)

This function calls a provided callback with some data. If the callback is not set, will do nothing.

Args: name: The name of the callback to call (as a string). data: Data to pass to the callback. If None, then it is assumed that the callback is a notification callback, and no parameters are given. end: An integer that is passed to the data callback. start: An integer that is passed to the data callback.

Source code in python_multipart/multipart.py
def callback(
    self, name: CallbackName, data: bytes | None = None, start: int | None = None, end: int | None = None
) -> None:
    """This function calls a provided callback with some data.  If the
    callback is not set, will do nothing.

    Args:
        name: The name of the callback to call (as a string).
        data: Data to pass to the callback.  If None, then it is assumed that the callback is a notification
            callback, and no parameters are given.
        end: An integer that is passed to the data callback.
        start: An integer that is passed to the data callback.
    """
    on_name = "on_" + name
    func = self.callbacks.get(on_name)
    if func is None:
        return
    func = cast("Callable[..., Any]", func)
    # Depending on whether we're given a buffer...
    if data is not None:
        # Don't do anything if we have start == end.
        if start is not None and start == end:
            return

        self.logger.debug("Calling %s with data[%d:%d]", on_name, start, end)
        func(data, start, end)
    else:
        self.logger.debug("Calling %s with no data", on_name)
        func()
set_callback(name, new_func)

Update the function for a callback. Removes from the callbacks dict if new_func is None.

Parameters:

Name Type Description Default
name CallbackName

The name of the callback to call (as a string).

required
new_func Callable[..., Any] | None

The new function for the callback. If None, then the callback will be removed (with no error if it does not exist).

required
Source code in python_multipart/multipart.py
def set_callback(self, name: CallbackName, new_func: Callable[..., Any] | None) -> None:
    """Update the function for a callback.  Removes from the callbacks dict
    if new_func is None.

    :param name: The name of the callback to call (as a string).

    :param new_func: The new function for the callback.  If None, then the
                     callback will be removed (with no error if it does not
                     exist).
    """
    if new_func is None:
        self.callbacks.pop("on_" + name, None)  # type: ignore[misc]
    else:
        self.callbacks["on_" + name] = new_func  # type: ignore[literal-required]

FormParser

This class is the all-in-one form parser. Given all the information necessary to parse a form, it will instantiate the correct parser, create the proper :class:Field and :class:File classes to store the data that is parsed, and call the two given callbacks with each field and file as they become available.

Args: content_type: The Content-Type of the incoming request. This is used to select the appropriate parser. on_field: The callback to call when a field has been parsed and is ready for usage. See above for parameters. on_file: The callback to call when a file has been parsed and is ready for usage. See above for parameters. on_end: An optional callback to call when all fields and files in a request has been parsed. Can be None. boundary: If the request is a multipart/form-data request, this should be the boundary of the request, as given in the Content-Type header, as a bytestring. file_name: If the request is of type application/octet-stream, then the body of the request will not contain any information about the uploaded file. In such cases, you can provide the file name of the uploaded file manually. FileClass: The class to use for uploaded files. Defaults to :class:File, but you can provide your own class if you wish to customize behaviour. The class will be instantiated as FileClass(file_name, field_name), and it must provide the following functions:: - file_instance.write(data) - file_instance.finalize() - file_instance.close() FieldClass: The class to use for uploaded fields. Defaults to :class:Field, but you can provide your own class if you wish to customize behaviour. The class will be instantiated as FieldClass(field_name), and it must provide the following functions:: - field_instance.write(data) - field_instance.finalize() - field_instance.close() - field_instance.set_none() config: Configuration to use for this FormParser. The default values are taken from the DEFAULT_CONFIG value, and then any keys present in this dictionary will overwrite the default values.

Source code in python_multipart/multipart.py
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
class FormParser:
    """This class is the all-in-one form parser.  Given all the information
    necessary to parse a form, it will instantiate the correct parser, create
    the proper :class:`Field` and :class:`File` classes to store the data that
    is parsed, and call the two given callbacks with each field and file as
    they become available.

    Args:
        content_type: The Content-Type of the incoming request.  This is used to select the appropriate parser.
        on_field: The callback to call when a field has been parsed and is ready for usage.  See above for parameters.
        on_file: The callback to call when a file has been parsed and is ready for usage.  See above for parameters.
        on_end: An optional callback to call when all fields and files in a request has been parsed.  Can be None.
        boundary: If the request is a multipart/form-data request, this should be the boundary of the request, as given
            in the Content-Type header, as a bytestring.
        file_name: If the request is of type application/octet-stream, then the body of the request will not contain any
            information about the uploaded file.  In such cases, you can provide the file name of the uploaded file
            manually.
        FileClass: The class to use for uploaded files.  Defaults to :class:`File`, but you can provide your own class
            if you wish to customize behaviour.  The class will be instantiated as FileClass(file_name, field_name), and
            it must provide the following functions::
                - file_instance.write(data)
                - file_instance.finalize()
                - file_instance.close()
        FieldClass: The class to use for uploaded fields.  Defaults to :class:`Field`, but you can provide your own
            class if you wish to customize behaviour.  The class will be instantiated as FieldClass(field_name), and it
            must provide the following functions::
                - field_instance.write(data)
                - field_instance.finalize()
                - field_instance.close()
                - field_instance.set_none()
        config: Configuration to use for this FormParser.  The default values are taken from the DEFAULT_CONFIG value,
            and then any keys present in this dictionary will overwrite the default values.
    """

    #: This is the default configuration for our form parser.
    #: Note: all file sizes should be in bytes.
    DEFAULT_CONFIG: FormParserConfig = {
        "MAX_BODY_SIZE": float("inf"),
        "MAX_MEMORY_FILE_SIZE": 1 * 1024 * 1024,
        "UPLOAD_DIR": None,
        "UPLOAD_KEEP_FILENAME": False,
        "UPLOAD_KEEP_EXTENSIONS": False,
        # Error on invalid Content-Transfer-Encoding?
        "UPLOAD_ERROR_ON_BAD_CTE": False,
    }

    def __init__(
        self,
        content_type: str,
        on_field: OnFieldCallback | None,
        on_file: OnFileCallback | None,
        on_end: Callable[[], None] | None = None,
        boundary: bytes | str | None = None,
        file_name: bytes | None = None,
        FileClass: type[FileProtocol] = File,
        FieldClass: type[FieldProtocol] = Field,
        config: dict[Any, Any] = {},
    ) -> None:
        self.logger = logging.getLogger(__name__)

        # Save variables.
        self.content_type = content_type
        self.boundary = boundary
        self.bytes_received = 0
        self.parser = None

        # Save callbacks.
        self.on_field = on_field
        self.on_file = on_file
        self.on_end = on_end

        # Save classes.
        self.FileClass = File
        self.FieldClass = Field

        # Set configuration options.
        self.config: FormParserConfig = self.DEFAULT_CONFIG.copy()
        self.config.update(config)  # type: ignore[typeddict-item]

        parser: OctetStreamParser | MultipartParser | QuerystringParser | None = None

        # Depending on the Content-Type, we instantiate the correct parser.
        if content_type == "application/octet-stream":
            file: FileProtocol = None  # type: ignore

            def on_start() -> None:
                nonlocal file
                file = FileClass(file_name, None, config=cast("FileConfig", self.config))

            def on_data(data: bytes, start: int, end: int) -> None:
                nonlocal file
                file.write(data[start:end])

            def _on_end() -> None:
                nonlocal file
                # Finalize the file itself.
                file.finalize()

                # Call our callback.
                if on_file:
                    on_file(file)

                # Call the on-end callback.
                if self.on_end is not None:
                    self.on_end()

            # Instantiate an octet-stream parser
            parser = OctetStreamParser(
                callbacks={"on_start": on_start, "on_data": on_data, "on_end": _on_end},
                max_size=self.config["MAX_BODY_SIZE"],
            )

        elif content_type == "application/x-www-form-urlencoded" or content_type == "application/x-url-encoded":
            name_buffer: list[bytes] = []

            f: FieldProtocol | None = None

            def on_field_start() -> None:
                pass

            def on_field_name(data: bytes, start: int, end: int) -> None:
                name_buffer.append(data[start:end])

            def on_field_data(data: bytes, start: int, end: int) -> None:
                nonlocal f
                if f is None:
                    f = FieldClass(b"".join(name_buffer))
                    del name_buffer[:]
                f.write(data[start:end])

            def on_field_end() -> None:
                nonlocal f
                # Finalize and call callback.
                if f is None:
                    # If we get here, it's because there was no field data.
                    # We create a field, set it to None, and then continue.
                    f = FieldClass(b"".join(name_buffer))
                    del name_buffer[:]
                    f.set_none()

                f.finalize()
                if on_field:
                    on_field(f)
                f = None

            def _on_end() -> None:
                if self.on_end is not None:
                    self.on_end()

            # Instantiate parser.
            parser = QuerystringParser(
                callbacks={
                    "on_field_start": on_field_start,
                    "on_field_name": on_field_name,
                    "on_field_data": on_field_data,
                    "on_field_end": on_field_end,
                    "on_end": _on_end,
                },
                max_size=self.config["MAX_BODY_SIZE"],
            )

        elif content_type == "multipart/form-data":
            if boundary is None:
                self.logger.error("No boundary given")
                raise FormParserError("No boundary given")

            header_name: list[bytes] = []
            header_value: list[bytes] = []
            headers: dict[bytes, bytes] = {}

            f_multi: FileProtocol | FieldProtocol | None = None
            writer = None
            is_file = False

            def on_part_begin() -> None:
                # Reset headers in case this isn't the first part.
                nonlocal headers
                headers = {}

            def on_part_data(data: bytes, start: int, end: int) -> None:
                nonlocal writer
                assert writer is not None
                writer.write(data[start:end])
                # TODO: check for error here.

            def on_part_end() -> None:
                nonlocal f_multi, is_file
                assert f_multi is not None
                f_multi.finalize()
                if is_file:
                    if on_file:
                        on_file(f_multi)
                else:
                    if on_field:
                        on_field(cast("FieldProtocol", f_multi))

            def on_header_field(data: bytes, start: int, end: int) -> None:
                header_name.append(data[start:end])

            def on_header_value(data: bytes, start: int, end: int) -> None:
                header_value.append(data[start:end])

            def on_header_end() -> None:
                headers[b"".join(header_name)] = b"".join(header_value)
                del header_name[:]
                del header_value[:]

            def on_headers_finished() -> None:
                nonlocal is_file, f_multi, writer
                # Reset the 'is file' flag.
                is_file = False

                # Parse the content-disposition header.
                # TODO: handle mixed case
                content_disp = headers.get(b"Content-Disposition")
                disp, options = parse_options_header(content_disp)

                # Get the field and filename.
                field_name = options.get(b"name")
                file_name = options.get(b"filename")
                # TODO: check for errors

                # Create the proper class.
                if file_name is None:
                    f_multi = FieldClass(field_name)
                else:
                    f_multi = FileClass(file_name, field_name, config=cast("FileConfig", self.config))
                    is_file = True

                # Parse the given Content-Transfer-Encoding to determine what
                # we need to do with the incoming data.
                # TODO: check that we properly handle 8bit / 7bit encoding.
                transfer_encoding = headers.get(b"Content-Transfer-Encoding", b"7bit")

                if transfer_encoding in (b"binary", b"8bit", b"7bit"):
                    writer = f_multi

                elif transfer_encoding == b"base64":
                    writer = Base64Decoder(f_multi)

                elif transfer_encoding == b"quoted-printable":
                    writer = QuotedPrintableDecoder(f_multi)

                else:
                    self.logger.warning("Unknown Content-Transfer-Encoding: %r", transfer_encoding)
                    if self.config["UPLOAD_ERROR_ON_BAD_CTE"]:
                        raise FormParserError('Unknown Content-Transfer-Encoding "{!r}"'.format(transfer_encoding))
                    else:
                        # If we aren't erroring, then we just treat this as an
                        # unencoded Content-Transfer-Encoding.
                        writer = f_multi

            def _on_end() -> None:
                nonlocal writer
                assert writer is not None
                writer.finalize()
                if self.on_end is not None:
                    self.on_end()

            # Instantiate a multipart parser.
            parser = MultipartParser(
                boundary,
                callbacks={
                    "on_part_begin": on_part_begin,
                    "on_part_data": on_part_data,
                    "on_part_end": on_part_end,
                    "on_header_field": on_header_field,
                    "on_header_value": on_header_value,
                    "on_header_end": on_header_end,
                    "on_headers_finished": on_headers_finished,
                    "on_end": _on_end,
                },
                max_size=self.config["MAX_BODY_SIZE"],
            )

        else:
            self.logger.warning("Unknown Content-Type: %r", content_type)
            raise FormParserError("Unknown Content-Type: {}".format(content_type))

        self.parser = parser

    def write(self, data: bytes) -> int:
        """Write some data.  The parser will forward this to the appropriate
        underlying parser.

        Args:
            data: The data to write.

        Returns:
            The number of bytes processed.
        """
        self.bytes_received += len(data)
        # TODO: check the parser's return value for errors?
        assert self.parser is not None
        return self.parser.write(data)

    def finalize(self) -> None:
        """Finalize the parser."""
        if self.parser is not None and hasattr(self.parser, "finalize"):
            self.parser.finalize()

    def close(self) -> None:
        """Close the parser."""
        if self.parser is not None and hasattr(self.parser, "close"):
            self.parser.close()

    def __repr__(self) -> str:
        return "{}(content_type={!r}, parser={!r})".format(self.__class__.__name__, self.content_type, self.parser)

Functions

close()

Close the parser.

Source code in python_multipart/multipart.py
def close(self) -> None:
    """Close the parser."""
    if self.parser is not None and hasattr(self.parser, "close"):
        self.parser.close()
finalize()

Finalize the parser.

Source code in python_multipart/multipart.py
def finalize(self) -> None:
    """Finalize the parser."""
    if self.parser is not None and hasattr(self.parser, "finalize"):
        self.parser.finalize()
write(data)

Write some data. The parser will forward this to the appropriate underlying parser.

Args: data: The data to write.

Returns: The number of bytes processed.

Source code in python_multipart/multipart.py
def write(self, data: bytes) -> int:
    """Write some data.  The parser will forward this to the appropriate
    underlying parser.

    Args:
        data: The data to write.

    Returns:
        The number of bytes processed.
    """
    self.bytes_received += len(data)
    # TODO: check the parser's return value for errors?
    assert self.parser is not None
    return self.parser.write(data)

MultipartParser

Bases: BaseParser

This class is a streaming multipart/form-data parser.

Callback Name Parameters Description
on_part_begin None Called when a new part of the multipart message is encountered.
on_part_data data, start, end Called when a portion of a part's data is encountered.
on_part_end None Called when the end of a part is reached.
on_header_begin None Called when we've found a new header in a part of a multipart message
on_header_field data, start, end Called each time an additional portion of a header is read (i.e. the part of the header that is before the colon; the "Foo" in "Foo: Bar").
on_header_value data, start, end Called when we get data for a header.
on_header_end None Called when the current header is finished - i.e. we've reached the newline at the end of the header.
on_headers_finished None Called when all headers are finished, and before the part data starts.
on_end None Called when the parser is finished parsing all data.

Args: boundary: The multipart boundary. This is required, and must match what is given in the HTTP request - usually in the Content-Type header. callbacks: A dictionary of callbacks. See the documentation for BaseParser. max_size: The maximum size of body to parse. Defaults to infinity - i.e. unbounded.

Source code in python_multipart/multipart.py
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
class MultipartParser(BaseParser):
    """This class is a streaming multipart/form-data parser.

    | Callback Name      | Parameters      | Description |
    |--------------------|-----------------|-------------|
    | on_part_begin      | None            | Called when a new part of the multipart message is encountered. |
    | on_part_data       | data, start, end| Called when a portion of a part's data is encountered. |
    | on_part_end        | None            | Called when the end of a part is reached. |
    | on_header_begin    | None            | Called when we've found a new header in a part of a multipart message |
    | on_header_field    | data, start, end| Called each time an additional portion of a header is read (i.e. the part of the header that is before the colon; the "Foo" in "Foo: Bar"). |
    | on_header_value    | data, start, end| Called when we get data for a header. |
    | on_header_end      | None            | Called when the current header is finished - i.e. we've reached the newline at the end of the header. |
    | on_headers_finished| None            | Called when all headers are finished, and before the part data starts. |
    | on_end             | None            | Called when the parser is finished parsing all data. |

    Args:
        boundary: The multipart boundary.  This is required, and must match what is given in the HTTP request - usually in the Content-Type header.
        callbacks: A dictionary of callbacks.  See the documentation for [`BaseParser`][python_multipart.BaseParser].
        max_size: The maximum size of body to parse.  Defaults to infinity - i.e. unbounded.
    """  # noqa: E501

    def __init__(
        self, boundary: bytes | str, callbacks: MultipartCallbacks = {}, max_size: float = float("inf")
    ) -> None:
        # Initialize parser state.
        super().__init__()
        self.state = MultipartState.START
        self.index = self.flags = 0

        self.callbacks = callbacks

        if not isinstance(max_size, Number) or max_size < 1:
            raise ValueError("max_size must be a positive number, not %r" % max_size)
        self.max_size = max_size
        self._current_size = 0

        # Setup marks.  These are used to track the state of data received.
        self.marks: dict[str, int] = {}

        # Save our boundary.
        if isinstance(boundary, str):  # pragma: no cover
            boundary = boundary.encode("latin-1")
        self.boundary = b"\r\n--" + boundary

    def write(self, data: bytes) -> int:
        """Write some data to the parser, which will perform size verification,
        and then parse the data into the appropriate location (e.g. header,
        data, etc.), and pass this on to the underlying callback.  If an error
        is encountered, a MultipartParseError will be raised.  The "offset"
        attribute on the raised exception will be set to the offset of the byte
        in the input chunk that caused the error.

        Args:
            data: The data to write to the parser.

        Returns:
            The number of bytes written.
        """
        # Handle sizing.
        data_len = len(data)
        if (self._current_size + data_len) > self.max_size:
            # We truncate the length of data that we are to process.
            new_size = int(self.max_size - self._current_size)
            self.logger.warning(
                "Current size is %d (max %d), so truncating data length from %d to %d",
                self._current_size,
                self.max_size,
                data_len,
                new_size,
            )
            data_len = new_size

        l = 0
        try:
            l = self._internal_write(data, data_len)
        finally:
            self._current_size += l

        return l

    def _internal_write(self, data: bytes, length: int) -> int:
        # Get values from locals.
        boundary = self.boundary

        # Get our state, flags and index.  These are persisted between calls to
        # this function.
        state = self.state
        index = self.index
        flags = self.flags

        # Our index defaults to 0.
        i = 0

        # Set a mark.
        def set_mark(name: str) -> None:
            self.marks[name] = i

        # Remove a mark.
        def delete_mark(name: str, reset: bool = False) -> None:
            self.marks.pop(name, None)

        # Helper function that makes calling a callback with data easier. The
        # 'remaining' parameter will callback from the marked value until the
        # end of the buffer, and reset the mark, instead of deleting it.  This
        # is used at the end of the function to call our callbacks with any
        # remaining data in this chunk.
        def data_callback(name: CallbackName, end_i: int, remaining: bool = False) -> None:
            marked_index = self.marks.get(name)
            if marked_index is None:
                return

            # Otherwise, we call it from the mark to the current byte we're
            # processing.
            if end_i <= marked_index:
                # There is no additional data to send.
                pass
            elif marked_index >= 0:
                # We are emitting data from the local buffer.
                self.callback(name, data, marked_index, end_i)
            else:
                # Some of the data comes from a partial boundary match.
                # and requires look-behind.
                # We need to use self.flags (and not flags) because we care about
                # the state when we entered the loop.
                lookbehind_len = -marked_index
                if lookbehind_len <= len(boundary):
                    self.callback(name, boundary, 0, lookbehind_len)
                elif self.flags & FLAG_PART_BOUNDARY:
                    lookback = boundary + b"\r\n"
                    self.callback(name, lookback, 0, lookbehind_len)
                elif self.flags & FLAG_LAST_BOUNDARY:
                    lookback = boundary + b"--\r\n"
                    self.callback(name, lookback, 0, lookbehind_len)
                else:  # pragma: no cover (error case)
                    self.logger.warning("Look-back buffer error")

                if end_i > 0:
                    self.callback(name, data, 0, end_i)
            # If we're getting remaining data, we have got all the data we
            # can be certain is not a boundary, leaving only a partial boundary match.
            if remaining:
                self.marks[name] = end_i - length
            else:
                self.marks.pop(name, None)

        # For each byte...
        while i < length:
            c = data[i]

            if state == MultipartState.START:
                # Skip leading newlines
                if c == CR or c == LF:
                    i += 1
                    self.logger.debug("Skipping leading CR/LF at %d", i)
                    continue

                # index is used as in index into our boundary.  Set to 0.
                index = 0

                # Move to the next state, but decrement i so that we re-process
                # this character.
                state = MultipartState.START_BOUNDARY
                i -= 1

            elif state == MultipartState.START_BOUNDARY:
                # Check to ensure that the last 2 characters in our boundary
                # are CRLF.
                if index == len(boundary) - 2:
                    if c != CR:
                        # Error!
                        msg = "Did not find CR at end of boundary (%d)" % (i,)
                        self.logger.warning(msg)
                        e = MultipartParseError(msg)
                        e.offset = i
                        raise e

                    index += 1

                elif index == len(boundary) - 2 + 1:
                    if c != LF:
                        msg = "Did not find LF at end of boundary (%d)" % (i,)
                        self.logger.warning(msg)
                        e = MultipartParseError(msg)
                        e.offset = i
                        raise e

                    # The index is now used for indexing into our boundary.
                    index = 0

                    # Callback for the start of a part.
                    self.callback("part_begin")

                    # Move to the next character and state.
                    state = MultipartState.HEADER_FIELD_START

                else:
                    # Check to ensure our boundary matches
                    if c != boundary[index + 2]:
                        msg = "Expected boundary character %r, got %r at index %d" % (boundary[index + 2], c, index + 2)
                        self.logger.warning(msg)
                        e = MultipartParseError(msg)
                        e.offset = i
                        raise e

                    # Increment index into boundary and continue.
                    index += 1

            elif state == MultipartState.HEADER_FIELD_START:
                # Mark the start of a header field here, reset the index, and
                # continue parsing our header field.
                index = 0

                # Set a mark of our header field.
                set_mark("header_field")

                # Notify that we're starting a header if the next character is
                # not a CR; a CR at the beginning of the header will cause us
                # to stop parsing headers in the MultipartState.HEADER_FIELD state,
                # below.
                if c != CR:
                    self.callback("header_begin")

                # Move to parsing header fields.
                state = MultipartState.HEADER_FIELD
                i -= 1

            elif state == MultipartState.HEADER_FIELD:
                # If we've reached a CR at the beginning of a header, it means
                # that we've reached the second of 2 newlines, and so there are
                # no more headers to parse.
                if c == CR and index == 0:
                    delete_mark("header_field")
                    state = MultipartState.HEADERS_ALMOST_DONE
                    i += 1
                    continue

                # Increment our index in the header.
                index += 1

                # If we've reached a colon, we're done with this header.
                if c == COLON:
                    # A 0-length header is an error.
                    if index == 1:
                        msg = "Found 0-length header at %d" % (i,)
                        self.logger.warning(msg)
                        e = MultipartParseError(msg)
                        e.offset = i
                        raise e

                    # Call our callback with the header field.
                    data_callback("header_field", i)

                    # Move to parsing the header value.
                    state = MultipartState.HEADER_VALUE_START

                elif c not in TOKEN_CHARS_SET:
                    msg = "Found invalid character %r in header at %d" % (c, i)
                    self.logger.warning(msg)
                    e = MultipartParseError(msg)
                    e.offset = i
                    raise e

            elif state == MultipartState.HEADER_VALUE_START:
                # Skip leading spaces.
                if c == SPACE:
                    i += 1
                    continue

                # Mark the start of the header value.
                set_mark("header_value")

                # Move to the header-value state, reprocessing this character.
                state = MultipartState.HEADER_VALUE
                i -= 1

            elif state == MultipartState.HEADER_VALUE:
                # If we've got a CR, we're nearly done our headers.  Otherwise,
                # we do nothing and just move past this character.
                if c == CR:
                    data_callback("header_value", i)
                    self.callback("header_end")
                    state = MultipartState.HEADER_VALUE_ALMOST_DONE

            elif state == MultipartState.HEADER_VALUE_ALMOST_DONE:
                # The last character should be a LF.  If not, it's an error.
                if c != LF:
                    msg = "Did not find LF character at end of header " "(found %r)" % (c,)
                    self.logger.warning(msg)
                    e = MultipartParseError(msg)
                    e.offset = i
                    raise e

                # Move back to the start of another header.  Note that if that
                # state detects ANOTHER newline, it'll trigger the end of our
                # headers.
                state = MultipartState.HEADER_FIELD_START

            elif state == MultipartState.HEADERS_ALMOST_DONE:
                # We're almost done our headers.  This is reached when we parse
                # a CR at the beginning of a header, so our next character
                # should be a LF, or it's an error.
                if c != LF:
                    msg = f"Did not find LF at end of headers (found {c!r})"
                    self.logger.warning(msg)
                    e = MultipartParseError(msg)
                    e.offset = i
                    raise e

                self.callback("headers_finished")
                state = MultipartState.PART_DATA_START

            elif state == MultipartState.PART_DATA_START:
                # Mark the start of our part data.
                set_mark("part_data")

                # Start processing part data, including this character.
                state = MultipartState.PART_DATA
                i -= 1

            elif state == MultipartState.PART_DATA:
                # We're processing our part data right now.  During this, we
                # need to efficiently search for our boundary, since any data
                # on any number of lines can be a part of the current data.

                # Save the current value of our index.  We use this in case we
                # find part of a boundary, but it doesn't match fully.
                prev_index = index

                # Set up variables.
                boundary_length = len(boundary)
                data_length = length

                # If our index is 0, we're starting a new part, so start our
                # search.
                if index == 0:
                    # The most common case is likely to be that the whole
                    # boundary is present in the buffer.
                    # Calling `find` is much faster than iterating here.
                    i0 = data.find(boundary, i, data_length)
                    if i0 >= 0:
                        # We matched the whole boundary string.
                        index = boundary_length - 1
                        i = i0 + boundary_length - 1
                    else:
                        # No match found for whole string.
                        # There may be a partial boundary at the end of the
                        # data, which the find will not match.
                        # Since the length should to be searched is limited to
                        # the boundary length, just perform a naive search.
                        i = max(i, data_length - boundary_length)

                        # Search forward until we either hit the end of our buffer,
                        # or reach a potential start of the boundary.
                        while i < data_length - 1 and data[i] != boundary[0]:
                            i += 1

                    c = data[i]

                # Now, we have a couple of cases here.  If our index is before
                # the end of the boundary...
                if index < boundary_length:
                    # If the character matches...
                    if boundary[index] == c:
                        # The current character matches, so continue!
                        index += 1
                    else:
                        index = 0

                # Our index is equal to the length of our boundary!
                elif index == boundary_length:
                    # First we increment it.
                    index += 1

                    # Now, if we've reached a newline, we need to set this as
                    # the potential end of our boundary.
                    if c == CR:
                        flags |= FLAG_PART_BOUNDARY

                    # Otherwise, if this is a hyphen, we might be at the last
                    # of all boundaries.
                    elif c == HYPHEN:
                        flags |= FLAG_LAST_BOUNDARY

                    # Otherwise, we reset our index, since this isn't either a
                    # newline or a hyphen.
                    else:
                        index = 0

                # Our index is right after the part boundary, which should be
                # a LF.
                elif index == boundary_length + 1:
                    # If we're at a part boundary (i.e. we've seen a CR
                    # character already)...
                    if flags & FLAG_PART_BOUNDARY:
                        # We need a LF character next.
                        if c == LF:
                            # Unset the part boundary flag.
                            flags &= ~FLAG_PART_BOUNDARY

                            # We have identified a boundary, callback for any data before it.
                            data_callback("part_data", i - index)
                            # Callback indicating that we've reached the end of
                            # a part, and are starting a new one.
                            self.callback("part_end")
                            self.callback("part_begin")

                            # Move to parsing new headers.
                            index = 0
                            state = MultipartState.HEADER_FIELD_START
                            i += 1
                            continue

                        # We didn't find an LF character, so no match.  Reset
                        # our index and clear our flag.
                        index = 0
                        flags &= ~FLAG_PART_BOUNDARY

                    # Otherwise, if we're at the last boundary (i.e. we've
                    # seen a hyphen already)...
                    elif flags & FLAG_LAST_BOUNDARY:
                        # We need a second hyphen here.
                        if c == HYPHEN:
                            # We have identified a boundary, callback for any data before it.
                            data_callback("part_data", i - index)
                            # Callback to end the current part, and then the
                            # message.
                            self.callback("part_end")
                            self.callback("end")
                            state = MultipartState.END
                        else:
                            # No match, so reset index.
                            index = 0

                # Otherwise, our index is 0.  If the previous index is not, it
                # means we reset something, and we need to take the data we
                # thought was part of our boundary and send it along as actual
                # data.
                if index == 0 and prev_index > 0:
                    # Overwrite our previous index.
                    prev_index = 0

                    # Re-consider the current character, since this could be
                    # the start of the boundary itself.
                    i -= 1

            elif state == MultipartState.END:
                # Do nothing and just consume a byte in the end state.
                if c not in (CR, LF):
                    self.logger.warning("Consuming a byte '0x%x' in the end state", c)  # pragma: no cover

            else:  # pragma: no cover (error case)
                # We got into a strange state somehow!  Just stop processing.
                msg = "Reached an unknown state %d at %d" % (state, i)
                self.logger.warning(msg)
                e = MultipartParseError(msg)
                e.offset = i
                raise e

            # Move to the next byte.
            i += 1

        # We call our callbacks with any remaining data.  Note that we pass
        # the 'remaining' flag, which sets the mark back to 0 instead of
        # deleting it, if it's found.  This is because, if the mark is found
        # at this point, we assume that there's data for one of these things
        # that has been parsed, but not yet emitted.  And, as such, it implies
        # that we haven't yet reached the end of this 'thing'.  So, by setting
        # the mark to 0, we cause any data callbacks that take place in future
        # calls to this function to start from the beginning of that buffer.
        data_callback("header_field", length, True)
        data_callback("header_value", length, True)
        data_callback("part_data", length - index, True)

        # Save values to locals.
        self.state = state
        self.index = index
        self.flags = flags

        # Return our data length to indicate no errors, and that we processed
        # all of it.
        return length

    def finalize(self) -> None:
        """Finalize this parser, which signals to that we are finished parsing.

        Note: It does not currently, but in the future, it will verify that we
        are in the final state of the parser (i.e. the end of the multipart
        message is well-formed), and, if not, throw an error.
        """
        # TODO: verify that we're in the state MultipartState.END, otherwise throw an
        # error or otherwise state that we're not finished parsing.
        pass

    def __repr__(self) -> str:
        return f"{self.__class__.__name__}(boundary={self.boundary!r})"

Functions

finalize()

Finalize this parser, which signals to that we are finished parsing.

Note: It does not currently, but in the future, it will verify that we are in the final state of the parser (i.e. the end of the multipart message is well-formed), and, if not, throw an error.

Source code in python_multipart/multipart.py
def finalize(self) -> None:
    """Finalize this parser, which signals to that we are finished parsing.

    Note: It does not currently, but in the future, it will verify that we
    are in the final state of the parser (i.e. the end of the multipart
    message is well-formed), and, if not, throw an error.
    """
    # TODO: verify that we're in the state MultipartState.END, otherwise throw an
    # error or otherwise state that we're not finished parsing.
    pass
write(data)

Write some data to the parser, which will perform size verification, and then parse the data into the appropriate location (e.g. header, data, etc.), and pass this on to the underlying callback. If an error is encountered, a MultipartParseError will be raised. The "offset" attribute on the raised exception will be set to the offset of the byte in the input chunk that caused the error.

Args: data: The data to write to the parser.

Returns: The number of bytes written.

Source code in python_multipart/multipart.py
def write(self, data: bytes) -> int:
    """Write some data to the parser, which will perform size verification,
    and then parse the data into the appropriate location (e.g. header,
    data, etc.), and pass this on to the underlying callback.  If an error
    is encountered, a MultipartParseError will be raised.  The "offset"
    attribute on the raised exception will be set to the offset of the byte
    in the input chunk that caused the error.

    Args:
        data: The data to write to the parser.

    Returns:
        The number of bytes written.
    """
    # Handle sizing.
    data_len = len(data)
    if (self._current_size + data_len) > self.max_size:
        # We truncate the length of data that we are to process.
        new_size = int(self.max_size - self._current_size)
        self.logger.warning(
            "Current size is %d (max %d), so truncating data length from %d to %d",
            self._current_size,
            self.max_size,
            data_len,
            new_size,
        )
        data_len = new_size

    l = 0
    try:
        l = self._internal_write(data, data_len)
    finally:
        self._current_size += l

    return l

OctetStreamParser

Bases: BaseParser

This parser parses an octet-stream request body and calls callbacks when incoming data is received. Callbacks are as follows:

Callback Name Parameters Description
on_start None Called when the first data is parsed.
on_data data, start, end Called for each data chunk that is parsed.
on_end None Called when the parser is finished parsing all data.

Args: callbacks: A dictionary of callbacks. See the documentation for BaseParser. max_size: The maximum size of body to parse. Defaults to infinity - i.e. unbounded.

Source code in python_multipart/multipart.py
class OctetStreamParser(BaseParser):
    """This parser parses an octet-stream request body and calls callbacks when
    incoming data is received.  Callbacks are as follows:

    | Callback Name  | Parameters      | Description                                         |
    |----------------|-----------------|-----------------------------------------------------|
    | on_start       | None            | Called when the first data is parsed.               |
    | on_data        | data, start, end| Called for each data chunk that is parsed.           |
    | on_end         | None            | Called when the parser is finished parsing all data.|

    Args:
        callbacks: A dictionary of callbacks.  See the documentation for [`BaseParser`][python_multipart.BaseParser].
        max_size: The maximum size of body to parse.  Defaults to infinity - i.e. unbounded.
    """

    def __init__(self, callbacks: OctetStreamCallbacks = {}, max_size: float = float("inf")):
        super().__init__()
        self.callbacks = callbacks
        self._started = False

        if not isinstance(max_size, Number) or max_size < 1:
            raise ValueError("max_size must be a positive number, not %r" % max_size)
        self.max_size: int | float = max_size
        self._current_size = 0

    def write(self, data: bytes) -> int:
        """Write some data to the parser, which will perform size verification,
        and then pass the data to the underlying callback.

        Args:
            data: The data to write to the parser.

        Returns:
            The number of bytes written.
        """
        if not self._started:
            self.callback("start")
            self._started = True

        # Truncate data length.
        data_len = len(data)
        if (self._current_size + data_len) > self.max_size:
            # We truncate the length of data that we are to process.
            new_size = int(self.max_size - self._current_size)
            self.logger.warning(
                "Current size is %d (max %d), so truncating data length from %d to %d",
                self._current_size,
                self.max_size,
                data_len,
                new_size,
            )
            data_len = new_size

        # Increment size, then callback, in case there's an exception.
        self._current_size += data_len
        self.callback("data", data, 0, data_len)
        return data_len

    def finalize(self) -> None:
        """Finalize this parser, which signals to that we are finished parsing,
        and sends the on_end callback.
        """
        self.callback("end")

    def __repr__(self) -> str:
        return "%s()" % self.__class__.__name__

Functions

finalize()

Finalize this parser, which signals to that we are finished parsing, and sends the on_end callback.

Source code in python_multipart/multipart.py
def finalize(self) -> None:
    """Finalize this parser, which signals to that we are finished parsing,
    and sends the on_end callback.
    """
    self.callback("end")
write(data)

Write some data to the parser, which will perform size verification, and then pass the data to the underlying callback.

Args: data: The data to write to the parser.

Returns: The number of bytes written.

Source code in python_multipart/multipart.py
def write(self, data: bytes) -> int:
    """Write some data to the parser, which will perform size verification,
    and then pass the data to the underlying callback.

    Args:
        data: The data to write to the parser.

    Returns:
        The number of bytes written.
    """
    if not self._started:
        self.callback("start")
        self._started = True

    # Truncate data length.
    data_len = len(data)
    if (self._current_size + data_len) > self.max_size:
        # We truncate the length of data that we are to process.
        new_size = int(self.max_size - self._current_size)
        self.logger.warning(
            "Current size is %d (max %d), so truncating data length from %d to %d",
            self._current_size,
            self.max_size,
            data_len,
            new_size,
        )
        data_len = new_size

    # Increment size, then callback, in case there's an exception.
    self._current_size += data_len
    self.callback("data", data, 0, data_len)
    return data_len

QuerystringParser

Bases: BaseParser

This is a streaming querystring parser. It will consume data, and call the callbacks given when it has data.

Callback Name Parameters Description
on_field_start None Called when a new field is encountered.
on_field_name data, start, end Called when a portion of a field's name is encountered.
on_field_data data, start, end Called when a portion of a field's data is encountered.
on_field_end None Called when the end of a field is encountered.
on_end None Called when the parser is finished parsing all data.

Args: callbacks: A dictionary of callbacks. See the documentation for BaseParser. strict_parsing: Whether or not to parse the body strictly. Defaults to False. If this is set to True, then the behavior of the parser changes as the following: if a field has a value with an equal sign (e.g. "foo=bar", or "foo="), it is always included. If a field has no equals sign (e.g. "...&name&..."), it will be treated as an error if 'strict_parsing' is True, otherwise included. If an error is encountered, then a QuerystringParseError will be raised. max_size: The maximum size of body to parse. Defaults to infinity - i.e. unbounded.

Source code in python_multipart/multipart.py
class QuerystringParser(BaseParser):
    """This is a streaming querystring parser.  It will consume data, and call
    the callbacks given when it has data.

    | Callback Name  | Parameters      | Description                                         |
    |----------------|-----------------|-----------------------------------------------------|
    | on_field_start | None            | Called when a new field is encountered.             |
    | on_field_name  | data, start, end| Called when a portion of a field's name is encountered. |
    | on_field_data  | data, start, end| Called when a portion of a field's data is encountered. |
    | on_field_end   | None            | Called when the end of a field is encountered.      |
    | on_end         | None            | Called when the parser is finished parsing all data.|

    Args:
        callbacks: A dictionary of callbacks.  See the documentation for [`BaseParser`][python_multipart.BaseParser].
        strict_parsing: Whether or not to parse the body strictly.  Defaults to False.  If this is set to True, then the
            behavior of the parser changes as the following: if a field has a value with an equal sign
            (e.g. "foo=bar", or "foo="), it is always included.  If a field has no equals sign (e.g. "...&name&..."),
            it will be treated as an error if 'strict_parsing' is True, otherwise included.  If an error is encountered,
            then a [`QuerystringParseError`][python_multipart.exceptions.QuerystringParseError] will be raised.
        max_size: The maximum size of body to parse.  Defaults to infinity - i.e. unbounded.
    """  # noqa: E501

    state: QuerystringState

    def __init__(
        self, callbacks: QuerystringCallbacks = {}, strict_parsing: bool = False, max_size: float = float("inf")
    ) -> None:
        super().__init__()
        self.state = QuerystringState.BEFORE_FIELD
        self._found_sep = False

        self.callbacks = callbacks

        # Max-size stuff
        if not isinstance(max_size, Number) or max_size < 1:
            raise ValueError("max_size must be a positive number, not %r" % max_size)
        self.max_size: int | float = max_size
        self._current_size = 0

        # Should parsing be strict?
        self.strict_parsing = strict_parsing

    def write(self, data: bytes) -> int:
        """Write some data to the parser, which will perform size verification,
        parse into either a field name or value, and then pass the
        corresponding data to the underlying callback.  If an error is
        encountered while parsing, a QuerystringParseError will be raised.  The
        "offset" attribute of the raised exception will be set to the offset in
        the input data chunk (NOT the overall stream) that caused the error.

        Args:
            data: The data to write to the parser.

        Returns:
            The number of bytes written.
        """
        # Handle sizing.
        data_len = len(data)
        if (self._current_size + data_len) > self.max_size:
            # We truncate the length of data that we are to process.
            new_size = int(self.max_size - self._current_size)
            self.logger.warning(
                "Current size is %d (max %d), so truncating data length from %d to %d",
                self._current_size,
                self.max_size,
                data_len,
                new_size,
            )
            data_len = new_size

        l = 0
        try:
            l = self._internal_write(data, data_len)
        finally:
            self._current_size += l

        return l

    def _internal_write(self, data: bytes, length: int) -> int:
        state = self.state
        strict_parsing = self.strict_parsing
        found_sep = self._found_sep

        i = 0
        while i < length:
            ch = data[i]

            # Depending on our state...
            if state == QuerystringState.BEFORE_FIELD:
                # If the 'found_sep' flag is set, we've already encountered
                # and skipped a single separator.  If so, we check our strict
                # parsing flag and decide what to do.  Otherwise, we haven't
                # yet reached a separator, and thus, if we do, we need to skip
                # it as it will be the boundary between fields that's supposed
                # to be there.
                if ch == AMPERSAND or ch == SEMICOLON:
                    if found_sep:
                        # If we're parsing strictly, we disallow blank chunks.
                        if strict_parsing:
                            e = QuerystringParseError("Skipping duplicate ampersand/semicolon at %d" % i)
                            e.offset = i
                            raise e
                        else:
                            self.logger.debug("Skipping duplicate ampersand/semicolon at %d", i)
                    else:
                        # This case is when we're skipping the (first)
                        # separator between fields, so we just set our flag
                        # and continue on.
                        found_sep = True
                else:
                    # Emit a field-start event, and go to that state.  Also,
                    # reset the "found_sep" flag, for the next time we get to
                    # this state.
                    self.callback("field_start")
                    i -= 1
                    state = QuerystringState.FIELD_NAME
                    found_sep = False

            elif state == QuerystringState.FIELD_NAME:
                # Try and find a separator - we ensure that, if we do, we only
                # look for the equal sign before it.
                sep_pos = data.find(b"&", i)
                if sep_pos == -1:
                    sep_pos = data.find(b";", i)

                # See if we can find an equals sign in the remaining data.  If
                # so, we can immediately emit the field name and jump to the
                # data state.
                if sep_pos != -1:
                    equals_pos = data.find(b"=", i, sep_pos)
                else:
                    equals_pos = data.find(b"=", i)

                if equals_pos != -1:
                    # Emit this name.
                    self.callback("field_name", data, i, equals_pos)

                    # Jump i to this position.  Note that it will then have 1
                    # added to it below, which means the next iteration of this
                    # loop will inspect the character after the equals sign.
                    i = equals_pos
                    state = QuerystringState.FIELD_DATA
                else:
                    # No equals sign found.
                    if not strict_parsing:
                        # See also comments in the QuerystringState.FIELD_DATA case below.
                        # If we found the separator, we emit the name and just
                        # end - there's no data callback at all (not even with
                        # a blank value).
                        if sep_pos != -1:
                            self.callback("field_name", data, i, sep_pos)
                            self.callback("field_end")

                            i = sep_pos - 1
                            state = QuerystringState.BEFORE_FIELD
                        else:
                            # Otherwise, no separator in this block, so the
                            # rest of this chunk must be a name.
                            self.callback("field_name", data, i, length)
                            i = length

                    else:
                        # We're parsing strictly.  If we find a separator,
                        # this is an error - we require an equals sign.
                        if sep_pos != -1:
                            e = QuerystringParseError(
                                "When strict_parsing is True, we require an "
                                "equals sign in all field chunks. Did not "
                                "find one in the chunk that starts at %d" % (i,)
                            )
                            e.offset = i
                            raise e

                        # No separator in the rest of this chunk, so it's just
                        # a field name.
                        self.callback("field_name", data, i, length)
                        i = length

            elif state == QuerystringState.FIELD_DATA:
                # Try finding either an ampersand or a semicolon after this
                # position.
                sep_pos = data.find(b"&", i)
                if sep_pos == -1:
                    sep_pos = data.find(b";", i)

                # If we found it, callback this bit as data and then go back
                # to expecting to find a field.
                if sep_pos != -1:
                    self.callback("field_data", data, i, sep_pos)
                    self.callback("field_end")

                    # Note that we go to the separator, which brings us to the
                    # "before field" state.  This allows us to properly emit
                    # "field_start" events only when we actually have data for
                    # a field of some sort.
                    i = sep_pos - 1
                    state = QuerystringState.BEFORE_FIELD

                # Otherwise, emit the rest as data and finish.
                else:
                    self.callback("field_data", data, i, length)
                    i = length

            else:  # pragma: no cover (error case)
                msg = "Reached an unknown state %d at %d" % (state, i)
                self.logger.warning(msg)
                e = QuerystringParseError(msg)
                e.offset = i
                raise e

            i += 1

        self.state = state
        self._found_sep = found_sep
        return len(data)

    def finalize(self) -> None:
        """Finalize this parser, which signals to that we are finished parsing,
        if we're still in the middle of a field, an on_field_end callback, and
        then the on_end callback.
        """
        # If we're currently in the middle of a field, we finish it.
        if self.state == QuerystringState.FIELD_DATA:
            self.callback("field_end")
        self.callback("end")

    def __repr__(self) -> str:
        return "{}(strict_parsing={!r}, max_size={!r})".format(
            self.__class__.__name__, self.strict_parsing, self.max_size
        )

Functions

finalize()

Finalize this parser, which signals to that we are finished parsing, if we're still in the middle of a field, an on_field_end callback, and then the on_end callback.

Source code in python_multipart/multipart.py
def finalize(self) -> None:
    """Finalize this parser, which signals to that we are finished parsing,
    if we're still in the middle of a field, an on_field_end callback, and
    then the on_end callback.
    """
    # If we're currently in the middle of a field, we finish it.
    if self.state == QuerystringState.FIELD_DATA:
        self.callback("field_end")
    self.callback("end")
write(data)

Write some data to the parser, which will perform size verification, parse into either a field name or value, and then pass the corresponding data to the underlying callback. If an error is encountered while parsing, a QuerystringParseError will be raised. The "offset" attribute of the raised exception will be set to the offset in the input data chunk (NOT the overall stream) that caused the error.

Args: data: The data to write to the parser.

Returns: The number of bytes written.

Source code in python_multipart/multipart.py
def write(self, data: bytes) -> int:
    """Write some data to the parser, which will perform size verification,
    parse into either a field name or value, and then pass the
    corresponding data to the underlying callback.  If an error is
    encountered while parsing, a QuerystringParseError will be raised.  The
    "offset" attribute of the raised exception will be set to the offset in
    the input data chunk (NOT the overall stream) that caused the error.

    Args:
        data: The data to write to the parser.

    Returns:
        The number of bytes written.
    """
    # Handle sizing.
    data_len = len(data)
    if (self._current_size + data_len) > self.max_size:
        # We truncate the length of data that we are to process.
        new_size = int(self.max_size - self._current_size)
        self.logger.warning(
            "Current size is %d (max %d), so truncating data length from %d to %d",
            self._current_size,
            self.max_size,
            data_len,
            new_size,
        )
        data_len = new_size

    l = 0
    try:
        l = self._internal_write(data, data_len)
    finally:
        self._current_size += l

    return l

Functions

create_form_parser(headers, on_field, on_file, trust_x_headers=False, config={})

This function is a helper function to aid in creating a FormParser instances. Given a dictionary-like headers object, it will determine the correct information needed, instantiate a FormParser with the appropriate values and given callbacks, and then return the corresponding parser.

Args: headers: A dictionary-like object of HTTP headers. The only required header is Content-Type. on_field: Callback to call with each parsed field. on_file: Callback to call with each parsed file. trust_x_headers: Whether or not to trust information received from certain X-Headers - for example, the file name from X-File-Name. config: Configuration variables to pass to the FormParser.

Source code in python_multipart/multipart.py
def create_form_parser(
    headers: dict[str, bytes],
    on_field: OnFieldCallback | None,
    on_file: OnFileCallback | None,
    trust_x_headers: bool = False,
    config: dict[Any, Any] = {},
) -> FormParser:
    """This function is a helper function to aid in creating a FormParser
    instances.  Given a dictionary-like headers object, it will determine
    the correct information needed, instantiate a FormParser with the
    appropriate values and given callbacks, and then return the corresponding
    parser.

    Args:
        headers: A dictionary-like object of HTTP headers.  The only required header is Content-Type.
        on_field: Callback to call with each parsed field.
        on_file: Callback to call with each parsed file.
        trust_x_headers: Whether or not to trust information received from certain X-Headers - for example, the file
            name from X-File-Name.
        config: Configuration variables to pass to the FormParser.
    """
    content_type: str | bytes | None = headers.get("Content-Type")
    if content_type is None:
        logging.getLogger(__name__).warning("No Content-Type header given")
        raise ValueError("No Content-Type header given!")

    # Boundaries are optional (the FormParser will raise if one is needed
    # but not given).
    content_type, params = parse_options_header(content_type)
    boundary = params.get(b"boundary")

    # We need content_type to be a string, not a bytes object.
    content_type = content_type.decode("latin-1")

    # File names are optional.
    file_name = headers.get("X-File-Name")

    # Instantiate a form parser.
    form_parser = FormParser(content_type, on_field, on_file, boundary=boundary, file_name=file_name, config=config)

    # Return our parser.
    return form_parser

parse_form(headers, input_stream, on_field, on_file, chunk_size=1048576)

This function is useful if you just want to parse a request body, without too much work. Pass it a dictionary-like object of the request's headers, and a file-like object for the input stream, along with two callbacks that will get called whenever a field or file is parsed.

Args: headers: A dictionary-like object of HTTP headers. The only required header is Content-Type. input_stream: A file-like object that represents the request body. The read() method must return bytestrings. on_field: Callback to call with each parsed field. on_file: Callback to call with each parsed file. chunk_size: The maximum size to read from the input stream and write to the parser at one time. Defaults to 1 MiB.

Source code in python_multipart/multipart.py
def parse_form(
    headers: dict[str, bytes],
    input_stream: SupportsRead,
    on_field: OnFieldCallback | None,
    on_file: OnFileCallback | None,
    chunk_size: int = 1048576,
) -> None:
    """This function is useful if you just want to parse a request body,
    without too much work.  Pass it a dictionary-like object of the request's
    headers, and a file-like object for the input stream, along with two
    callbacks that will get called whenever a field or file is parsed.

    Args:
        headers: A dictionary-like object of HTTP headers.  The only required header is Content-Type.
        input_stream: A file-like object that represents the request body. The read() method must return bytestrings.
        on_field: Callback to call with each parsed field.
        on_file: Callback to call with each parsed file.
        chunk_size: The maximum size to read from the input stream and write to the parser at one time.
            Defaults to 1 MiB.
    """
    # Create our form parser.
    parser = create_form_parser(headers, on_field, on_file)

    # Read chunks of 1MiB and write to the parser, but never read more than
    # the given Content-Length, if any.
    content_length: int | float | bytes | None = headers.get("Content-Length")
    if content_length is not None:
        content_length = int(content_length)
    else:
        content_length = float("inf")
    bytes_read = 0

    while True:
        # Read only up to the Content-Length given.
        max_readable = int(min(content_length - bytes_read, chunk_size))
        buff = input_stream.read(max_readable)

        # Write to the parser and update our length.
        parser.write(buff)
        bytes_read += len(buff)

        # If we get a buffer that's smaller than the size requested, or if we
        # have read up to our content length, we're done.
        if len(buff) != max_readable or bytes_read == content_length:
            break

    # Tell our parser that we're done writing data.
    parser.finalize()

Classes

DecodeError

Bases: ParseError

This exception is raised when there is a decoding error - for example with the Base64Decoder or QuotedPrintableDecoder.

Source code in python_multipart/exceptions.py
class DecodeError(ParseError):
    """This exception is raised when there is a decoding error - for example
    with the Base64Decoder or QuotedPrintableDecoder.
    """

FileError

Bases: FormParserError, OSError

Exception class for problems with the File class.

Source code in python_multipart/exceptions.py
class FileError(FormParserError, OSError):
    """Exception class for problems with the File class."""

FormParserError

Bases: ValueError

Base error class for our form parser.

Source code in python_multipart/exceptions.py
class FormParserError(ValueError):
    """Base error class for our form parser."""

MultipartParseError

Bases: ParseError

This is a specific error that is raised when the MultipartParser detects an error while parsing.

Source code in python_multipart/exceptions.py
class MultipartParseError(ParseError):
    """This is a specific error that is raised when the MultipartParser detects
    an error while parsing.
    """

ParseError

Bases: FormParserError

This exception (or a subclass) is raised when there is an error while parsing something.

Source code in python_multipart/exceptions.py
class ParseError(FormParserError):
    """This exception (or a subclass) is raised when there is an error while
    parsing something.
    """

    #: This is the offset in the input data chunk (*NOT* the overall stream) in
    #: which the parse error occurred.  It will be -1 if not specified.
    offset = -1

QuerystringParseError

Bases: ParseError

This is a specific error that is raised when the QuerystringParser detects an error while parsing.

Source code in python_multipart/exceptions.py
class QuerystringParseError(ParseError):
    """This is a specific error that is raised when the QuerystringParser
    detects an error while parsing.
    """