Adding boundary generation and tests
This commit is contained in:
parent
117f9f723f
commit
6c3ddf1b64
|
@ -1,3 +1,5 @@
|
|||
import binascii
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import urllib.parse
|
||||
|
@ -943,10 +945,17 @@ class Request(Message):
|
|||
return ()
|
||||
|
||||
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)
|
||||
if "content-type" not in self.headers:
|
||||
# Don't overwrite header if it already exists or it will destroy the boundary value
|
||||
self.headers["content-type"] = "multipart/form-data"
|
||||
|
||||
@property
|
||||
def multipart_form(self) -> multidict.MultiDictView[bytes, bytes]:
|
||||
|
|
|
@ -429,15 +429,9 @@ class TestRequestUtils:
|
|||
|
||||
def test_set_multipart_form(self):
|
||||
request = treq()
|
||||
request.multipart_form = [("file", "shell.jpg"), ("file_size", "1000")]
|
||||
assert request.headers["Content-Type"] == 'multipart/form-data'
|
||||
assert request.content is None
|
||||
|
||||
request = treq()
|
||||
request.headers["Content-Type"] = 'multipart/form-data; boundary=foo'
|
||||
request.multipart_form = [(b"file", b"shell.jpg"), (b"file_size", b"1000")]
|
||||
assert request.headers["Content-Type"] == 'multipart/form-data; boundary=foo'
|
||||
|
||||
assert request.headers["Content-Type"].startswith('multipart/form-data')
|
||||
assert list(request.multipart_form.items()) == [(b"file", b"shell.jpg"), (b"file_size", b"1000")]
|
||||
|
||||
class TestResponse:
|
||||
|
||||
|
|
Loading…
Reference in New Issue