当我运行以下python代码(abc.py)时,我总是得到一个类型错误,如下所示:
./abc.py activatelink alphabeta
Type Error: ['alphabeta']
我的代码:
#!/usr/bin/python
import urllib2
from urllib2 import URLError
from urllib2 import HTTPError
import requests
import urllib
import json
import time
import os
import sys
import hashlib
def activate_user(link):
print invoke_rest('GET', link)
def invoke_rest(request_type, rest_url, payload, headers):
try:
api_url = rest_url
if request_type == 'GET':
r = requests.get(api_url)
to_ret = {'code':r.status_code, 'reply':r.text}
return to_ret
elif request_type == 'POST':
r = requests.post(api_url, data=payload, headers=headers)
to_ret = {'code':r.status_code, 'reply':r.text}
return to_ret
else:
return "Invalid request type ", request_type
except Exception, e:
return "Exception:", e, " in getting the API call"
def help():
print ('Usage: %s { activate | help }', os.path.basename(sys.argv[0])
if __name__ == '__main__':
actions = {'activatelink': activate_user, 'help': help}
try:
action = str(sys.argv[1])
except IndexError:
print "IndexError: ", sys.argv[1]
action = 'help'
args = sys.argv[2:]
try:
actions[action](*args)
except (KeyError):
print "Key Error:", args
help()
except (TypeError):
print "Type Error:", args
help()
我做错了吗?我添加了除了activatelink之外的其他一些功能,它们运行正常,任何人都可以指出这里有什么问题吗?
答案 0 :(得分:6)
您的invoke_rest()
函数需要四个参数:
def invoke_rest(request_type, rest_url, payload, headers):
但你只传了两个:
print invoke_rest('GET', link)
提出TypeError
例外:
>>> def invoke_rest(request_type, rest_url, payload, headers):
... pass
...
>>> invoke_rest('GET', 'alphabeta')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: invoke_rest() takes exactly 4 arguments (2 given)
也许您希望这两个额外的参数(payload
和headers
)是可选的。如果是,请将它们设为关键字参数,并将其默认值设置为None
:
def invoke_rest(request_type, rest_url, payload=None, headers=None):
requests
库很好。