Submitting forms to HTTP
Sometimes you have to interact with HTML forms or upload files. This usually requires handling the multipart/form-data
encoding.
Forms can mix files and text data, and there can be multiple different fields within a form. Thus, it requires a way to express multiple fields in the same request and some of those fields can be binary files.
That's why encoding data in multipart can get tricky, but it's possible to roll out a basic recipe using only standard library tools that will work in most cases.
How to do it...
Here are the steps for this recipe:
multipart
itself requires tracking all the fields and files we want to encode and then performing the encoding itself.- We will rely on
io.BytesIO
to store all the resulting bytes:
import io import mimetypes import uuid class MultiPartForm: def __init__(self): self.fields = {} self.files = [] def __setitem__(self, name, value): self.fields[name] = value def add_file(self, field, filename...