我是python的新手,据我所知,我收到了这个元组错误:
Traceback (most recent call last):
File "/home/cambria/Main.py", line 10, in <module>
main()
File "/home/cambria/Main.py", line 5, in main
respons3 = api.get_summoner_by_name('hi im gosan')
File "/home/cambria/RiotAPI.py", line 31, in get_summoner_by_name
return self._request(api_url)
File "/home/cambria/RiotAPI.py", line 12, in _request
for key, value in params.items():
AttributeError: 'tuple' object has no attribute 'items'
在
def _request(self, api_url, params=()):
args = {'api_key': self.api_key}
for key, value in params.items():
if key not in args:
args[key] = value
response = requests.get(
Consts.URL['base'].format(
proxy=self.region,
region=self.region,
url=api_url
),
params=args
)
print response.url
return response.json()
这是我收到的唯一一个我真的不太了解的错误。这是因为我的参数上没有.items
吗?或者我把它初始化为空字典?
编辑1:尝试过修补元组和物品但是没有运气,我的错误信息如下
Traceback (most recent call last):
File "/home/cambria/Desktop/api/Main.py", line 10, in <module>
main()
File "/home/cambria/Desktop/api/Main.py", line 5, in main
respons3 = api.get_summoner_by_name('hi im gosan')
File "/home/cambria/Desktop/api/RiotAPI.py", line 33, in get_summoner_by_name
return self._request(api_url)
File "/home/cambria/Desktop/api/RiotAPI.py", line 23, in _request
params=args
File "/home/cambria/.local/lib/python2.7/site-packages/requests/api.py", line 69, in get
return request('get', url, params=params, **kwargs)
File "/home/cambria/.local/lib/python2.7/site-packages/requests/api.py", line 50, in request
response = session.request(method=method, url=url, **kwargs)
File "/home/cambria/.local/lib/python2.7/site-packages/requests/sessions.py", line 465, in request
resp = self.send(prep, **send_kwargs)
File "/home/cambria/.local/lib/python2.7/site-packages/requests/sessions.py", line 573, in send
r = adapter.send(request, **kwargs)
File "/home/cambria/.local/lib/python2.7/site-packages/requests/adapters.py", line 415, in send
raise ConnectionError(err, request=request)
ConnectionError: ('Connection aborted.', gaierror(-2, 'Name or service not known'))
>>>
据我所知并且已经搜索过,这是python REQUESTS没有完全通过的结果? 和我的新代码如下,
def _request(self, api_url, params=None): #edit
if params is None: #edit
params = {} #edit
args = {'api_key': self.api_key}
for key, value in params.items(): #remove?? since there is no .items()?
if key not in args:
args[key] = value
response = requests.get(
Consts.URL['base'].format(
proxy=self.region,
region=self.region,
url=api_url
),
params=args
)
print response.url
return response.json()
答案 0 :(得分:1)
您的代码希望params
为dict {}
(或者使用.items
方法)。你已经通过了一个元组()
。这两者并不相同。
默认情况下将params
设置为None
,并在需要时传递。
def _request(self, api_url, params=None):
params = params if params is not None else {}
...
或者期待一个元组列表,而不是一个字典。
def _request(self, api_url, params=()):
for key, value in params:
...
答案 1 :(得分:1)
元组()
没有名为items
的方法。你可能把它误认为字典。按如下方式更改代码:
def _request(self, api_url, params=None):
if params is None:
params = {}
...