0

AIM

I am attempting to encode a folium choropleth as StringIO. I am basing my answer of a related query. I have checked the answers here and here.

ERROR

AttributeError: 'bytes' object has no attribute 'encode'

CODE

views.py

def get_choropleth(self, request):
    # make choropleth ('m')
    html_string = m.get_root().render()
    f = StringIO(html_string)
    choropleth = base64.b64decode(f.read())
    choropleth = choropleth.encode('utf8') # causing error
    return {'choropleth':choropleth}
Darcy
  • 575
  • 2
  • 8
  • 21
  • 1
    simply try to replace `choropleth.encode('utf8')` by `choropleth.decode('utf8')` and please refer to the [documentation](https://docs.python.org/3.5/library/stdtypes.html#bytes.decode) – Chiheb Nexus Nov 11 '18 at 01:25
  • 1
    well `b'\xe0'.decode('latin')` will output `'à'`. So, maybe your string isn't really `utf8` compliant. – Chiheb Nexus Nov 11 '18 at 03:32

1 Answers1

0

After some trial-and-error, the following worked for me:

SOLUTION

def get_choropleth(self, request):
        # make choropleth ('m')
        html_string = m.get_root().render()
        encoded_bytes = html_string.encode('utf-8')
        encoded_bytes = base64.b64encode(encoded_bytes)
        encoded_bytes = encoded_bytes.decode('utf8') # decode the b64 bytes for Unicode
        choropleth = encoded_bytes
        return {'choropleth':choropleth}
Darcy
  • 575
  • 2
  • 8
  • 21