python - add_header 期望 3 个参数而不只是键/值

标签 python urllib2 request-headers

我遇到了这个错误信息:

TypeError: add_header() 正好接受 3 个参数(给定 2 个)

使用这些参数时:

testService("SomeServiceName", "POST", "[编辑有效 url]", ('Content-type','application/json'), [编辑有效 json])

通常此错误意味着我没有将“self”作为参数传递,但看到此方法在类中被调用,我不确定该怎么做。我试过在参数和方法内部将 self 作为参数传递。我试过将 header 括在方括号和圆括号中。当我传递“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()

最佳答案

来自documentation , add_header 接受两个参数。你用一个参数调用它,一个有两个值的元组。

你应该做什么:

req.add_header(key, value)

您当前正在做的事情是因为您将 header 作为元组获取:

req.add_header((key, value,))    # aka passing a tuple with both arguments to the key parameter

您需要解压元组:

req.add_header(header[0], header[1])

或者更好,使用 splat运算符(*):

req.add_header(*header)      # Does the same thing as above

此外,您使用空字符串作为 header 的默认参数,而当它被提供时它是一个元组。您可能应该将默认值更改为元组或 None

关于python - add_header 期望 3 个参数而不只是键/值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21832659/

相关文章:

python - 什么时候检查非局部变量的存在?

java - 在同一配置 Spring Security 中使用 RequestHeaderRequestMatcher 和 antmactcher basic auth

python - 如何在没有 k 的情况下进行随机采样,直到产生某个整数? (Python)

python - 类型错误 : This COM object can not automate the makepy process - please run makepy manually for this object

python - 使用Python计算字符串中int和float数量的有效方法

python - 以编程方式将文件添加到 Django ImageField

python - urllib2.urlopen() 与 urllib.urlopen() - urllib2 在 urllib 工作时抛出 404!为什么?

python - 为什么 urllib 会出现这个错误?

ios - 如何快速在 iOS 的全局请求中添加 HTTP header