Encoding & Charset Resolution
Relevant source files
The following files were used as context for generating this wiki page:
Encoding and charset resolution within the python-multipart project is primarily focused on two areas: parsing HTTP headers to extract character set parameters and decoding streaming data that has been transformed via Content-Transfer-Encoding (CTE). The system ensures that metadata like filenames and field values are correctly interpreted according to RFC specifications, such as RFC 2231 and RFC 2045.
The project employs a streaming architecture where data is decoded on-the-fly as it is written to the parser. This is achieved through specialized decoder classes that wrap internal file or field writers, handling complex encodings like Base64 and Quoted-Printable without requiring the entire payload to be loaded into memory.
Header Parsing and Option Extraction
The primary entry point for resolving encodings in headers is the parse_options_header function. This function decomposes complex header values, such as Content-Type or Content-Disposition, into a primary value and a dictionary of parameters.
Logic Flow for Header Resolution
- Input Normalization: The function accepts both
strandbytes. If bytes are provided, they are decoded usinglatin-1to maintain WSGI compliance. - RFC 2231 Support: The parser utilizes
email.message.Messageto handle extended parameter encodings (e.g.,param*=utf-8''encoded_val). - Sanitization: For
filenameparameters, it specifically handles legacy IE6 bugs by stripping full file paths to retrieve only the base filename.
Key Header Resolution Features
| Feature | Implementation Detail | Source Citation |
|---|---|---|
| RFC 2231 Continuations | Handled via email.message.Message.get_params(); includes protection against oversized indices. | multipart.py:150-155 |
| Case Insensitivity | Content-Transfer-Encoding and Header values are normalized to lowercase during comparison. | multipart.py:1022-1025, CHANGELOG.md:32 |
| Default Encoding | Assumes 7bit if Content-Transfer-Encoding is missing. | multipart.py:1022 |
Content-Transfer-Encoding (CTE) Decoders
When a multipart part specifies a Content-Transfer-Encoding, the FormParser instantiates a decoder to wrap the target Field or File object.
Decoder Architecture
Decoders maintain an internal cache to handle data chunks that do not align with encoding boundaries (e.g., Base64 requires groups of 4 characters).
- Base64Decoder: Decodes data using the standard
base64library. It caches trailing bytes if the input length is not a multiple of 4. - QuotedPrintableDecoder: Uses
binascii.a2b_qpto decode data. It caches trailing=characters to ensure escape sequences are not split acrosswrite()calls.
Decoder Implementation Details
# From python_multipart/decoders.py:59-79
def write(self, data: bytes) -> int:
if len(self.cache) > 0:
data = bytes(self.cache) + data
decode_len = (len(data) // 4) * 4
val = data[:decode_len]
if len(val) > 0:
try:
decoded = base64.b64decode(val)
except binascii.Error:
raise DecodeError("There was an error raised while decoding base64-encoded data.")
self.underlying.write(decoded)
remaining_len = len(data) % 4
if remaining_len > 0:
self.cache[:] = data[-remaining_len:]
else:
self.cache[:] = b""
return len(data)
Sources: python_multipart/decoders.py:59-79
Character Set Resolution in Multipart Parts
Charset resolution is applied during the transition from headers to part data. The FormParser extracts the charset from the Content-Type header of individual parts to ensure the Field or File objects are initialized with the correct metadata.
Charset Handling in Metadata
The system supports UTF-8 filenames in the Content-Disposition header, typically encoded via RFC 2231. The test suite validates this behavior by ensuring that multi-byte sequences in filenames are correctly captured and stored in the File object's file_name property.
Sources: tests/test_data/http/utf8_filename.yaml:1-8, python_multipart/multipart.py:159-177
Configuration Options
The FormParser behavior regarding encoding errors can be toggled via the config dictionary.
| Option | Type | Default | Description |
|---|---|---|---|
UPLOAD_ERROR_ON_BAD_CTE | bool | False | If True, raising a FormParserError when an unknown Content-Transfer-Encoding is encountered. |
Sources: python_multipart/multipart.py:904-905, python_multipart/multipart.py:1037-1043
Summary
Encoding & Charset Resolution in python-multipart is a robust, spec-compliant system that prioritizes streaming efficiency. By utilizing email.message for header parsing and implementing caching decoders for CTE, the library ensures that complex character sets and transfer encodings are handled transparently during the form parsing process.
Sources: python_multipart/multipart.py, python_multipart/decoders.py, tests/test_multipart.py