私は、python2.7とpython3.5のhtmlファイルを提供するためにhttpserverを作成しました。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では上記のエラーが発生しました。
strをバイトに変換するのにbytearray(data, 'utf-8')
を使用できますが、htmlがwebで変更されています。
私の質問:使用2to3はツールなしpython2とのpython3をサポートしないファイルのエンコーディングを変更するために行う方法を 。
ファイルを読むためのより良い方法があり、python2とpython3で同じ方法でクライアントにコンテンツを送りましたか?
ありがとうございます。
あなたはPython 3を意味します。その場合は、単に戻り値を 'bytes(return_value、" ascii ")'に変換してください。 'if sys.version_info> =(3、):' –
ありがとうございます。 –