Urllib 语法翻译从 python 3.5 到 2.7

Urllib syntax translation from python 3.5 to 2.7

我有一段代码是用 Python 3.5 编写的,使用了 urllib 模块。现在,我尝试将其转换为可以与 Python 2.7 一起使用,但我从 urllib() 模块中得到了一些错误。

例如:

Traceback (most recent call last):
  File "alert.py", line 13, in <module>
    import urllib.request as urllib
ImportError: No module named request

现在,我知道 urllib 在 Python 2.7 中已被弃用,所以我来这里寻求有关使用 urllib 的行的帮助。

import urllib.request as urllib
from http.cookiejar import CookieJar
from os.path import isfile
from os.path import join as joinPath
from sys import exc_info
from traceback import print_tb
from urllib.parse import urlencode

# constant
APPLICATION_PATH = '/srv/path/'
ALERT_POINT_PATH = joinPath(APPLICATION_PATH, 'alert_contact')
URL_REQUEST_TIMEOUT = 42

SMS_BOX_URL = 'xx.xxxx.xxx.xxx'


def initWebConnection():  # init web connection
    response = 0
    initUrlLibResponse = initUrlLib()  # init urllib
    if initUrlLibResponse:
        response = 1

    return response


def initUrlLib():  # init urllib
    response = 0
    try:
        cookieJar = CookieJar()  # cookies
        opener = urllib.build_opener(urllib.HTTPCookieProcessor(cookieJar))
        urllib.install_opener(opener)
    except Exception as e:
        response = 1

    # ex_type, ex, tb = exc_info()
    return response


def urlRequest(url, data=None):  # make url request
    contentResponse = None
    try:
        request = None
        if data:
            dataRequest = urlencode(data)
            dataRequest = dataRequest.encode('UTF-8')
            request = urllib.Request(url, dataRequest)
        else:
            request = urllib.Request(url)
        response = urllib.urlopen(url=request, timeout=URL_REQUEST_TIMEOUT)  # make request

        # get response
        contentResponse = response.read()
    except Exception as e:
        contentResponse = None

    # ex_type, ex, tb = exc_info()
    return contentResponse


try:
    evt.data = 'Some name'

    # check production state
    isInProduction = False
    if evt.prodState == 1000:
        isInProduction = True

    if isInProduction:
        initWebConnection()

        # check alert point'
        if isfile(ALERT_POINT_PATH):
            alertContactContent = None
            with open(ALERT_POINT_PATH, 'r') as alertContactFile:
                alertContactContent = alertContactFile.read()
            alertContactContent = alertContactContent.splitlines()

            if alertContactContent:
                evt.summary = '#[ DNS:  ALERT ]#  {}'.format(evt.summary)

                for alertContactContentLine in alertContactContent:
                    webRequestData = dict(
                        ## TO DO: set the url parameters appropriately
                        phone=alertContactContentLine,
                        message='NEW ALERT: {}'.format(evt.ipAddress),
                    )
                    webRequestResponse = urlRequest(SMS_BOX_URL, webRequestData)
        else:
            evt.summary = '#[ ERROR: SMS ALERT NO CONTACT ]#  {}'.format(evt.summary)
except Exception as e:
    ex_type, ex, tb = exc_info()
    print('\n #[ERROR]#exception: {ex}\n'.format(ex=e))
    print('\n #[ERROR]#exception traceback: {trace}\n'.format(trace=print_tb(tb)))

    evt.summary = '#[ DNS:ERROR traceback in event message ]#  {}'.format(evt.summary)
    evt.message = '#[ DNS:ERROR ex_type:\n {} \nex: {} \n traceback:\n {} \n]#  {}'.format(ex_type, ex,
                                                                                                      print_tb(tb),
                                                                                                      evt.message)

您可以从

更改导入行
import urllib.request as urllib
from http.cookiejar import CookieJar
from urllib.parse import urlencode

import urllib2 as urllib
from cookielib import CookieJar
from urllib import urlencode

对于 Python 2.7