2016-12-01 5 views
1

私は、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で変更されています。

enter image description here

私の質問:使用2to3はツールなしpython2とのpython3をサポートしないファイルのエンコーディングを変更するために行う方法を

ファイルを読むためのより良い方法があり、python2とpython3で同じ方法でクライアントにコンテンツを送りましたか?

ありがとうございます。

答えて

1

あなただけではないテキストモードでは、バイナリモードでファイルを開くことがあります。

with open(resource,"rb") as f: 
    data = f.read() 

そして、dataのpython 3でbytesオブジェクトであり、そしてパイソン2でstr、および両方のバージョンで動作します。

このコードがWindowsのボックスに当たった場合、それはまだ機能します(テキストモードで開くと、画像のようなバイナリファイルがエンドライン終了変換のために破損します)。

+0

あなたはPython 3を意味します。その場合は、単に戻り値を 'bytes(return_value、" ascii ")'に変換してください。 'if sys.version_info> =(3、):' –

+0

ありがとうございます。 –

関連する問題