The BaseParser is the foundation for all streaming parsers in this library. It uses a callback-based system to notify the consumer of parsing events without copying data unnecessarily.
Callbacks are registered via set_callback(name, func). There are two types of callbacks:
- Notification callbacks: Called with no arguments (e.g.,
on_start, on_end). - Data callbacks: Called with
(data, start, end), where data[start:end] represents the slice of interest. This avoids expensive data copying.
Common callback names include start, data, end, field_start, field_name, field_data, field_end, part_begin, part_data, part_end, header_begin, header_field, header_value, header_end, headers_finished, and on_end.
from python_multipart.multipart import BaseParser
class MyParser(BaseParser):
def __init__(self, callbacks):
super().__init__()
self.callbacks = callbacks
# Example usage pattern for a consumer of a parser:
def my_data_handler(data, start, end):
print(f"Found data: {data[start:end]}")
# The parser would then be used by calling .write(chunk) in a loop