如何对 html_string 进行 base64 编码

How to base64 encode a html_string

目标

我正在尝试将 folium 等值线编码为 StringIO。我的回答基于 . I have checked the answers here and here.

错误

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

代码

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}

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

解决方案

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}