web-dev-qa-db-ja.com

Python 3 urllibはTypeErrorを生成します:POSTデータはバイトまたはバイトのイテレート可能です。 str型にすることはできません

動作しているPython 2.7コードをPython 3コードに変換しようとしていますが、urllibリクエストモジュールからタイプエラーを受信して​​います。

組み込みの2to3 Pythonツールを使用して、以下の作業urllibおよびurllib2 Python 2.7コードを変換しました。

_import urllib2
import urllib

url = "https://www.customdomain.com"
d = dict(parameter1="value1", parameter2="value2")

req = urllib2.Request(url, data=urllib.urlencode(d))
f = urllib2.urlopen(req)
resp = f.read()
_

2to3モジュールからの出力は、以下のPython 3コードでした。

_import urllib.request, urllib.error, urllib.parse

url = "https://www.customdomain.com"
d = dict(parameter1="value1", parameter2="value2")

req = urllib.request.Request(url, data=urllib.parse.urlencode(d))
f = urllib.request.urlopen(req)
resp = f.read()
_

Python 3コードを実行すると、次のエラーが生成されます。

_---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-56-206954140899> in <module>()
      5 
      6 req = urllib.request.Request(url, data=urllib.parse.urlencode(d))
----> 7 f = urllib.request.urlopen(req)
      8 resp = f.read()

C:\Users\Admin\Anaconda3\lib\urllib\request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)
    159     else:
    160         opener = _opener
--> 161     return opener.open(url, data, timeout)
    162 
    163 def install_opener(opener):

C:\Users\Admin\Anaconda3\lib\urllib\request.py in open(self, fullurl, data, timeout)
    459         for processor in self.process_request.get(protocol, []):
    460             meth = getattr(processor, meth_name)
--> 461             req = meth(req)
    462 
    463         response = self._open(req, data)

C:\Users\Admin\Anaconda3\lib\urllib\request.py in do_request_(self, request)
   1110                 msg = "POST data should be bytes or an iterable of bytes. " \
   1111                       "It cannot be of type str."
-> 1112                 raise TypeError(msg)
   1113             if not request.has_header('Content-type'):
   1114                 request.add_unredirected_header(

TypeError: POST data should be bytes or an iterable of bytes. It cannot be of type str.
_

日付のエンコードについて言及した他の2つのチケット( ticket1 および ticket2 )も読んでいます。

f = urllib.request.urlopen(req)f = urllib.request.urlopen(req.encode('utf-8'))に変更すると、次のエラーを受け取りました:_AttributeError: 'Request' object has no attribute 'encode'_

Python 3コードを機能させる方法にこだわっています。手伝っていただけませんか?

27
Greg

docsから、urlencodeからのparams出力は、データとしてurlopenに送信される前にバイトにエンコードされることに注意してください:

data = urllib.parse.urlencode(d).encode("utf-8")
req = urllib.request.Request(url)
with urllib.request.urlopen(req,data=data) as f:
    resp = f.read()
    print(resp)
44

これを試して:

url = 'https://www.customdomain.com'
d = dict(parameter1="value1", parameter2="value2")

f = urllib.parse.urlencode(d)
f = f.encode('utf-8')

req = urllib.request.Request(url, f)

あなたの問題はあなたが辞書を扱っていた方法にあります。

5
Leb

ZOHO CRM API V2でpythonリクエストモジュールを使用しました。問題なく動作しました。GETリクエストを使用したサンプル作業コードを次に示します。

import json
import requests

# API methods - https://www.zoho.com/crm/developer/docs/api/api-methods.html
# getrecords API Call
module_name = 'Deals'
authtoken = '*****'
api_url = "https://crm.zoho.com/crm/private/json/"+module_name+"/getRecords?authtoken="+authtoken+"&scope=crmapi&fromIndex=1&toIndex=2"

# GET Request
request_response = requests.get(
    url=api_url
    )
print(json.dumps(json.loads(request_response.text), sort_keys=True, indent=4, separators=(",", ": ")))
json_response = json.loads(request_response.text)
0