无法找出Python 3.9中的urllib代码语法,它在Python 2中用作urllib2

whhtz7ly  于 2023-08-08  发布在  Python
关注(0)|答案(1)|浏览(112)

我是一个BASH/PERL/Ansible编码器,对Python不是很有经验。我的经验是使用Python 2。
我有一段代码,在Python2中使用urllib2可以很好地工作,但我不知道如何将其转换为Python3.9中的urllib.parse和urllib.request,因为urllib2已经被弃用了。
在Python 2中,代码可以很好地使用“import urllib2”。我将省去在Python 3.9中让它工作的所有尝试,但我已经得到了大量的错误,包括但不限于:"* 类型错误:POST数据应该是字节、字节的可迭代对象或文件对象。它不能是str. "," 类型错误:不是有效的非字符串序列或Map对象 "," TypeError:需要类似字节的对象,而不是'str'"," TypeError:bytes类型的对象不是JSON可序列化的 "等。当我运行代码时,我得到" urllib. error. HTTPError:HTTP错误500:内部服务器错误 *",结果在Python 2(和cURL)中返回正常。下面的原始代码段(在Python 2中使用urllib2):

def linux_inventoryAWS(self):
        servers = []

        data = urllib.urlencode({'header':'yes',
                'query':'select distinct lower(a.name), a.service_level from view_device_v1 a LEFT OUTER JOIN view_device_custom_fields_flat_v1 b ON (a.device_pk=b.device_fk) LEFT JOIN view_objectcategory_v1 cat ON a.objectcategory_fk=cat.objectcategory_pk where a.os_name ~ \'Linux\' and a.in_service=\'t\' and a.type=\'virtual\' and (virtual_subtype=\'Amazon EC2 Instance\' or virtual_subtype=\'Citrix/Xen\' or virtual_subtype=\'Xen\') and (excludefromautmninventory is null or excludefromautmninventory != \'Yes\') order by a.service_level asc'})

        credentials = self.d42_user + ":" + self.d42_pwd
        base64string = base64.b64encode(credentials)
        url = self.d42_url + "/services/data/v1.0/query/"
        request = urllib2.Request(url)
        request.add_header("Authorization", "Basic %s" % base64string)
        request.add_data(data) # "add_data" has also been depreciated and seems to have been replaced by just "data" -- this may be part of the problem with getting 500 errors.
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
        result = urllib2.urlopen(request, context=ctx)
        for line in result:
            servers.append(line.strip('\n'))
        result.close()
        servers.pop(0)
        serversAsString = ",".join(servers)
        return servers

字符串

piztneat

piztneat1#

多亏了Reddit上r/learnbython的好朋友们的建议和大量的试错,我才能够拼凑出一些在Python 2和Python 3中都能工作的代码。它使用“requests”而不是“urllib”或“urllib 2”。“代码片段如下:

def linux_inventory(self):
    servers = []

    data = {'header':'yes',
            'query':'select distinct lower(a.name), a.service_level from view_device_v1 a LEFT OUTER JOIN view_device_custom_fields_flat_v1 b ON (a.device_pk=b.device_fk) LEFT JOIN view_objectcategory_v1 cat ON a.objectcategory_fk=cat.objectcategory_pk where a.os_name ~ \'Windows\' and a.in_service=\'t\' and a.type=\'virtual\' and (virtual_subtype=\'Amazon EC2 Instance\' or virtual_subtype=\'Citrix/Xen\' or virtual_subtype=\'Xen\') and (excludefromautmninventory is null or excludefromautmninventory != \'Yes\') order by a.service_level asc'}

    if sys.version_info.major == 2:
        credentials = self.d42_user + ":" + self.d42_pwd
    else:
        credentials = bytes(self.d42_user + ":" + self.d42_pwd, 'utf-8')
    base64string = base64.b64encode(credentials)
    url = self.d42_url + "/services/data/v1.0/query/"
    headers = {'Authorization': b'Basic ' + base64string}
    result = requests.post(url, headers=headers, data=data)
    for line in result.text.splitlines():
        servers.append(line)
    result.close()
    servers.pop(0)
    serversAsString = ",".join(servers)
    return servers

字符串

相关问题