Problems with urllib in different versions of python!

import base64
import urllib2

class SGovToken():
    TIME_OUT = 3600
    LAST_UPDATE_TIME = ""
    TOKEN = ""

    def __init__(self, *args, **kwargs):
        pass

    def get_token_from_sgovernace(self,appid,appkey,url):
        if not appid or not appkey:
            return "ERROE"
        
        soap_env = """
                    <applicationID>{0}</applicationID>
                    <credential>{1}</credential>
                    """
        appkey = base64.standard_b64decode(appkey)
        soap_content = soap_env.format(appid,appkey)
        resquest = urllib2.Request(url,soap_content)
        resquest.add_header("SOPAACTION","getTokenByAPPCREdential")

        try:
            response = urllib2.urlopen(resquest)
        except HTTPERROR as e:
            pass
        if response is not none:
            resp_content = response.read()
            return resp_content

now the code can get resp_content normally in python2. But in python3, changing urllib2 to urllib.request is an error. The data parameter of urllib2.Request has also been changed to bytes type! I don"t know what"s wrong with it?

Sep.16,2021

it is recommended that you use a version of IDE, such as PyCharm CE, which is open source and free of charge. Don't waste your precious time on this low-level problem.
you put this code in IDE, at a glance of all the errors.

or use a code upgrade tool, such as pythonconverter.com/" rel=" nofollow noreferrer "> http://pythonconverter.com/
or python.org/2/library/2to3.html" rel= "nofollow noreferrer" > https://docs.python.org/2/lib.

use

import base64
import urllib.request, urllib.error, urllib.parse


class SGovToken():
    TIME_OUT = 3600
    LAST_UPDATE_TIME = ""
    TOKEN = ''

    def __init__(self, *args, **kwargs):
        pass

    def get_token_from_sgovernace(self, appid, appkey, url):
        if not appid or not appkey:
            return 'ERROE'

        soap_env = '''
                    <applicationID>{0}</applicationID>
                    <credential>{1}</credential>
                    '''
        appkey = base64.standard_b64decode(appkey)
        soap_content = soap_env.format(appid, appkey)
        resquest = urllib.request.Request(url, soap_content)
        resquest.add_header('SOPAACTION', 'getTokenByAPPCREdential')

        try:
            response = urllib.request.urlopen(resquest)
        except urllib.error.HTTPERROR as e:
            pass
        if response is not None:
            resp_content = response.read()
            return resp_content

is it easy?

Menu