如何对html_string

时间:2018-11-11 01:13:29

标签: python django base64 stringio

AIM

我正在尝试将folium色度编码为StringIO。我以related query为基础。我已经检查了答案herehere

错误

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}

1 个答案:

答案 0 :(得分:0)

经过反复试验,以下对我有用:

解决方案

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}