def test_encode(): data = [(b"file", b"shell.jpg"), (b"file_size", b"1000")] headers = Headers( content_type='multipart/form-data; boundary=127824672498') content = multipart.encode(headers, data) assert b'Content-Disposition: form-data; name="file"' in content assert b'Content-Type: text/plain; charset=utf-8\r\n\r\nshell.jpg\r\n\r\n--127824672498\r\n' in content assert b'1000\r\n\r\n--127824672498--\r\n' assert len(content) == 252 with pytest.raises(ValueError, match=r"boundary found in encoded string"): multipart.encode(headers, [(b"key", b"--127824672498")]) boundary = 'boundary茅莽' headers = Headers(content_type='multipart/form-data; boundary=' + boundary) result = multipart.encode(headers, data) assert result == b''
def _set_multipart_form(self, value): is_valid_content_type = self.headers.get( "content-type", "").lower().startswith("multipart/form-data") if not is_valid_content_type: """ Generate a random boundary here. See <https://datatracker.ietf.org/doc/html/rfc2046#section-5.1.1> for specifications on generating the boundary. """ boundary = "-" * 20 + binascii.hexlify(os.urandom(16)).decode() self.headers[ "content-type"] = f"multipart/form-data; boundary={boundary}" self.content = multipart.encode(self.headers, value)
def _set_multipart_form(self, value): self.content = multipart.encode(self.headers, value) self.headers["content-type"] = "multipart/form-data"