繁体   English   中英

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM