2017-05-26 11 views
0

誰かが2.xxから3.6に次のコードを翻訳するのを助けてくれますか?私は、urllib2ライブラリが変更されたという事実から私が抱いている問題を信じています。Python 2.xxから3.6への翻訳

from urllib2 import Request, urlopen 

values = """ 
    { 
    "carrierCode": "fedex", 
    "serviceCode": null, 
    "packageCode": null, 
    "fromPostalCode": "78703", 
    "toState": "DC", 
    "toCountry": "US", 
    "toPostalCode": "20500", 
    "toCity": "Washington", 
    "weight": { 
     "value": 3, 
     "units": "ounces" 
    }, 
    "dimensions": { 
     "units": "inches", 
     "length": 7, 
     "width": 5, 
     "height": 6 
    }, 
    "confirmation": "delivery", 
    "residential": false 
    } 
""" 

headers = { 
    'Content-Type': 'application/json', 
    'Authorization': '< Enter your Basic Authorization string here >' 
} 
request = Request('https://ssapi.shipstation.com/shipments/getrates', 
data=values, headers=headers) 

response_body = urlopen(request).read() 
print response_body 

私は@tmadamによってコードへの提案の編集をしたし、今、次のエラーを取得しています:

トレースバック(最新の呼び出しの最後): ファイル「C:/ユーザー/マップ/ の の中のPycharmProjects/Reverb/SSAPI.py "の行37を参照してください。" C:¥Users¥map¥AppData¥Local¥Programs¥Python¥Python36-32¥lib¥urllib¥program¥ file: "C:¥Users¥map¥AppData¥Local¥Programs¥Python¥Python36-32¥lib¥urllib¥request"を入力してください。 py "、ライン524、オープン中 req = meth(req) ファイル "C:\ Users \ map \ AppData \ Local \ Programs \ Python \ Python36-32 \ lib \ urllib \ request.py"、行1248、do_request_ raise TypeError(msg) TypeError:POSTデータは、バイト、繰り返し可能なバイト、またはファイルオブジェクトでなければなりません。それは型strであることはできません。

これはなぜ起こっているのですか?

答えて

0

Requesturlopenはあなたの輸入を変更する場合は、まだあなたのスクリプトを使用することができます。3.
pythonでurllib.requestの一部です:

from urllib.request import Request, urlopen 

また、印刷は、だから、そのようにそれを使用するのpython 3の機能です:

print(response_body) 
+0

こんにちは@tmadamこれらの編集は行っていますが、現在エラーが発生しています。私はこのエラーを反映するために以前の投稿を編集しました。何か案は? – bhess

+0

はい、POSTデータはバイトである必要があります。 'values = values.encode(" utf-8 ")'のように 'values'をエンコードした場合、この問題を解決できます。 –