Python 添加需要3个参数而不仅仅是key/value的\u头
我遇到以下错误消息:Python 添加需要3个参数而不仅仅是key/value的\u头,python,urllib2,request-headers,Python,Urllib2,Request Headers,我遇到以下错误消息: TypeError:add\u header()正好接受3个参数(给定2个) 使用这些参数时: testService(“SomeServiceName”、“POST”、“[redated valid url]”、('Content-type'、'application/json')、[redated valid json]) 通常,这个错误意味着我没有将“self”作为参数传递,但是由于这个方法不是在类中调用的,我不知道该怎么办。我尝试将self作为参数传入参数和方法内部
TypeError:add\u header()正好接受3个参数(给定2个)
使用这些参数时:
testService(“SomeServiceName”、“POST”、“[redated valid url]”、('Content-type'、'application/json')、[redated valid json])
通常,这个错误意味着我没有将“self”作为参数传递,但是由于这个方法不是在类中调用的,我不知道该怎么办。我尝试将self作为参数传入参数和方法内部。我试着把标题用括号和括号括起来。当我传递“self”时,我得到错误消息self未定义,当我使用括号而不是括号时,我得到与上面相同的错误
有谁有神奇的Python调试技能吗?非常感谢您抽出时间来查看此信息
def testService(name, verb, url, header="", requestBody=""):
#Log out the name of the request we're testing
if (name is not None) or (name.strip() is not ""):
print "Checking " + name + "\n\n"
# Make URL with StoreNumber
if (url is not None) or (url is not ""):
testUrl = url
# If specified verb is GET
if verb.strip().upper() == "GET":
# Create request
req = urllib2.Request(testUrl)
print "Making request with URL: " + testUrl + "\n\n"
# Send request
try:
response = urllib2.urlopen(req)
# If service returns 200 Okay
print "Connection to " + name + " Service successful. Returned with code " + str(response.code) + "\n\n"
# Log response
print "Response: " + response.read() + "\n\n"
# Handle exceptions
# If HTTP Error
except HTTPError as e:
if hasattr(e, 'reason'):
print name + ' failed to reach a server.'
print 'Reason: ', e.reason
elif hasattr(e, 'code'):
print e.code
elif hasattr(e, 'message'):
print e.message
pass
# If URL was the problem
except URLError as e:
if hasattr(e, 'reason'):
print name + ' failed to reach a server.'
if str(e.reason) == "[Errno 11004] getaddrinfo failed":
print "[Errno 11004] getaddrinfo failed with bad url: " + testUrl + "\n\n"
else:
print 'Reason: ', e.reason
elif hasattr(e, 'code'):
print 'Error code: ', e.code
elif hasattr(e, 'message'):
print e.message
pass
# If specified verb was POST
elif verb.strip().upper() == "POST":
# Check for None requestBody
if (requestBody is not None) or (requestBody.strip() is not ""):
data = urllib.urlencode(requestBody)
# Create request
req = urllib2.Request(testUrl, data)
# Check for header
if (header is not None) or (header.strip() is not ""):
req.add_header(header)
# YO YO THE BELOW CODE IS INCOMPLETE PLEASE FINISH
# Log request with URL and Data
print "Making request with URL: " + testUrl + " and data: THIS PART IS UNFINISHED PLEASE FINISH ME \n\n"
try:
response = urllib2.urlopen(req)
# If service returns 200 Okay
print "Connection to " + name + " Service successful. Returned with code " + str(response.code) + "\n\n"
# Log response
print "Response: " + response.read() + "\n\n"
# Handle exceptions
# If HTTP Error
except HTTPError as e:
if hasattr(e, 'code'):
print e.code
elif hasattr(e, 'message'):
print e.message
elif hasattr(e, 'reason'):
print name + ' failed to reach a server.'
print 'Reason: ', e.reason
pass
except URLError as e:
if hasattr(e, 'reason'):
print name + ' failed to reach a server.'
if str(e.reason) == "[Errno 11004] getaddrinfo failed":
print "[Errno 11004] getaddrinfo failed with bad url: " + url + "\n\n"
else:
print 'Reason: ', e.reason
elif hasattr(e, 'code'):
print 'Error code: ', e.code
elif hasattr(e, 'message'):
print e.message
pass
# Header non-existent in testService call
else:
print "Service header not provided. Exiting program"
sys.exit()
# Requesty Body not present in testService call
else:
print "Service request body not provided in code. Exiting program"
sys.exit()
# If specified verb is not supported (Currently only GET and POST are supported)
else:
print name + " Service written with HTTP verb other than GET or POST. Exiting program"
sys.exit()
else:
print "Service url not provided in code. Exiting program"
sys.exit()
else:
print "Service name not provided in code. Exiting program"
sys.exit()
从中,add_头
接受两个参数。您使用一个参数调用它,一个具有两个值的元组
你应该做什么:
req.add_header(key, value)
您当前正在执行的操作,因为您将头作为元组获取:
req.add_header((key, value,)) # aka passing a tuple with both arguments to the key parameter
您需要解压缩元组:
req.add_header(header[0], header[1])
或者更好地使用运算符(*
):
此外,您正在使用空字符串作为
标题
的默认参数,当提供它时,它是一个元组。您可能应该将默认值更改为元组或None
您的标题是一个2元组:
('Content-Type', 'application/json')
您正在尝试这样做:
req.add_header('Content-Type', 'application/json')
但实际上,你正在这样做:
req.add_header(('Content-Type', 'application/json'))
请注意,您只传递了一个参数——一个元组,而不是两个,一个键和一个值
若要修复此问题,请在使用*
(非正式的“splat”)操作符传递标题时,将其解压缩:
req.add_header(*header)
请查看文档:
虽然函数需要一个键和一个值,但只传递一个对象。因为您是在req对象上调用它,所以也传递了隐式的“self”
您可以通过两种方式调用此函数:
req.add_header(key, value)
urllib2.Request.add_header(req, key, value) # explicitly passing the reference instead of self
我不确定您是否希望传递的字符串被视为键或值,但添加另一个参数(或使header参数采用dict,然后在for循环中适当拆分)应该可以解决这个问题。例如(删除了不相关的代码):
工作完美。非常感谢你!我喜欢splat操作符。
req.add_header(key, value)
urllib2.Request.add_header(req, key, value) # explicitly passing the reference instead of self
def testService(name, verb, url, header=None, requestBody=""):
if header is None:
header = {}
for key, value in header.iteritems():
req.add_header(key, value)