0

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
Mindaugas Jaraminas
  • 3,261
  • 2
  • 24
  • 37
  • Requests "data" converts the values to json format, ```True``` is a boolean and can't be converted(encoded). Try the string ```"True"``` instead; I've also found [this](https://www.programcreek.com/python/example/106102/requests_toolbelt.MultipartEncoder) collection of examples you may find useful (since the documentation is very basic). Good luck! – Xosrov Jan 16 '20 at 21:23
  • @Xosrov Yes you are right this is the only way as there is a limitation in library right now. – Mindaugas Jaraminas Jan 17 '20 at 10:18

1 Answers1

1

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)
Mindaugas Jaraminas
  • 3,261
  • 2
  • 24
  • 37