1
我写了一个httpserver来为python2.7和python3.5提供html文件。python3将str转换为字节式的obj而不使用编码
def do_GET(self):
...
#if resoure is api
data = json.dumps({'message':['thanks for your answer']})
#if resource is file name
with open(resource, 'rb') as f:
data = f.read()
self.send_response(response)
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
self.wfile.write(data) # this line raise TypeError: a bytes-like object is required, not 'str'
该代码在python2.7中工作,但在python 3中,它引发了上述错误。
我可以使用bytearray(data, 'utf-8')
将str转换为字节,但html在web中更改。
我的问题: 怎么做才能支持python2和python3不使用2to3的工具和不改变文件的编码。
有没有更好的方式来读取文件,并在python2和python3中以相同的方式将内容发送到客户端?
在此先感谢。
你的意思是在Python 3中。在这种情况下,仅在python中将返回值转换为'bytes(return_value,“ascii”)“。3.用'if if sys.version_info> =(3,):' –
谢谢。:-)测试版本, –