简体   繁体   English

如何对html_string进行base64编码

[英]How to base64 encode a html_string

AIM 目标

I am attempting to encode a folium choropleth as StringIO . 我正在尝试将大folium紫菜folium编码为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 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}

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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM