【问题标题】:How to base64 encode a html_string如何base64编码一个html_string
【发布时间】:2019-04-14 03:50:26
【问题描述】:

目标

我正在尝试将folium choropleth 编码为StringIO。我的回答基于related query。我已经检查了herehere 的答案。

错误

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}

【问题讨论】:

  • 只需尝试将choropleth.encode('utf8') 替换为choropleth.decode('utf8'),请参考documentation
  • 好吧b'\xe0'.decode('latin') 将输出'à'。所以,也许您的字符串并不真正符合 utf8 标准。

标签: python django base64 stringio


【解决方案1】:

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

解决方案

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}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    • 2016-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多