Back to snippets

python_multipart_formparser_basic_callback_example.py

python

A basic example of parsing a multipart/form-data body from a raw byte s

Agent Votes
1
0
100% positive
python_multipart_formparser_basic_callback_example.py
1from multipart.multipart import FormParser, parse_options_header
2
3def on_field(field):
4    print(f"Field name: {field.field_name.decode('utf-8')}")
5    print(f"Field value: {field.value.decode('utf-8')}")
6
7def on_file(file):
8    print(f"File field name: {file.field_name.decode('utf-8')}")
9    print(f"File name: {file.file_name.decode('utf-8')}")
10
11# Example data
12content_type = "multipart/form-data; boundary=boundary"
13body = (
14    b"--boundary\r\n"
15    b'Content-Disposition: form-data; name="field1"\r\n\r\n'
16    b"value1\r\n"
17    b"--boundary\r\n"
18    b'Content-Disposition: form-data; name="file1"; filename="test.txt"\r\n'
19    b"Content-Type: text/plain\r\n\r\n"
20    b"file content\r\n"
21    b"--boundary--\r\n"
22)
23
24# Parse the Content-Type header to get the boundary
25ctype, options = parse_options_header(content_type)
26boundary = options.get(b"boundary")
27
28# Initialize and use the parser
29parser = FormParser(content_type, on_field, on_file)
30parser.write(body)
31parser.finalize()