Python Multipart

0.0.22 · active · verified Sat Mar 28

python-multipart is an Apache2-licensed streaming multipart parser for Python. It is designed for handling `multipart/form-data` POST requests, typically used in web servers for file uploads and complex form data. The library is actively maintained with frequent releases, currently at version 0.0.22, and supports modern Python versions (>=3.10).

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to parse a `multipart/form-data` request body using `MultipartParser`. It simulates an incoming HTTP request with form fields and a file, processing them using event-like iteration.

import io
from python_multipart import MultipartParser

# Simulate an HTTP request body with multipart/form-data
boundary = b"----WebKitFormBoundary7MA4YWxkTrZu0gW"
body_data = (
    b"--" + boundary + b"\r\n"
    b'Content-Disposition: form-data; name="username"\r\n'
    b'\r\n'
    b'testuser\r\n'
    b"--" + boundary + b"\r\n"
    b'Content-Disposition: form-data; name="upload_file"; filename="hello.txt"\r\n'
    b'Content-Type: text/plain\r\n'
    b'\r\n'
    b'Hello, World!\nThis is a test file.\r\n'
    b"--" + boundary + b"--\r\n"
)

# Simulate HTTP headers
headers = {
    "Content-Type": f"multipart/form-data; boundary={boundary.decode()}",
    "Content-Length": str(len(body_data)),
}

# Use BytesIO to simulate a file-like object for the body stream
body_stream = io.BytesIO(body_data)

# Create a parser instance
parser = MultipartParser(headers)

# Iterate through parts and process them
print("Parsing multipart data:")
for part in parser.parse(body_stream):
    if hasattr(part, 'field_name'): # It's a form field
        print(f"  Field: name={part.field_name.decode()}, value={part.value.decode()}")
    elif hasattr(part, 'file_name'): # It's an uploaded file
        print(f"  File: name={part.field_name.decode()}, filename={part.file_name.decode()}, content_type={part.content_type.decode()}")
        file_content = part.value # The file content is available as bytes
        print(f"  File content length: {len(file_content)} bytes")
        # In a real application, you would typically save or process file_content

print("\nParsing complete.")

view raw JSON →