Search code examples
python-3.xpython-requestspython-requests-toolbelt

How to encode data in Python 3.7 using requests_toolbelt


In my request, I have some Boolean values and numbers. Here is a simple example:

import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
m = MultipartEncoder(
    fields={'field0': 'value', 'field1': True,
            'field2': ('filename', 'test', 'text/plain')}
    )
r = requests.post('http://httpbin.org/post', data=m, headers={'Content-Type': m.content_type})
print(r.text)

I get an error:

 File "<stdin>", line 3, in <module>
  File "/usr/local/lib/python3.7/site-packages/requests_toolbelt/multipart/encoder.py", line 125, in __init__
    self._prepare_parts()
  File "/usr/local/lib/python3.7/site-packages/requests_toolbelt/multipart/encoder.py", line 246, in _prepare_parts
    self.parts = [Part.from_field(f, enc) for f in self._iter_fields()]
  File "/usr/local/lib/python3.7/site-packages/requests_toolbelt/multipart/encoder.py", line 246, in <listcomp>
    self.parts = [Part.from_field(f, enc) for f in self._iter_fields()]
  File "/usr/local/lib/python3.7/site-packages/requests_toolbelt/multipart/encoder.py", line 494, in from_field
    body = coerce_data(field.data, encoding)
  File "/usr/local/lib/python3.7/site-packages/requests_toolbelt/multipart/encoder.py", line 472, in coerce_data
    return CustomBytesIO(data, encoding)
  File "/usr/local/lib/python3.7/site-packages/requests_toolbelt/multipart/encoder.py", line 535, in __init__
    buffer = encode_with(buffer, encoding)
  File "/usr/local/lib/python3.7/site-packages/requests_toolbelt/multipart/encoder.py", line 416, in encode_with
    return string.encode(encoding)
AttributeError: 'bool' object has no attribute 'encode'

I am unsing:

  • requests_toolbelt v.0.9.1
  • requests v.2.22.0

Solution

  • As currently, library requests_toolbelt is very limited the best solution is to convert everything to a string. Here is an example:

    import requests
    from requests_toolbelt.multipart.encoder import MultipartEncoder
    m = MultipartEncoder(
        fields={'field0': 'value', 'field1': str(True),
                'field2': ('filename', 'test', 'text/plain')}
        )
    r = requests.post('http://httpbin.org/post', data=m, headers={'Content-Type': m.content_type})
    print(r.text)