将 "data = urllib.parse.urlencode(values) " 更改为 python 2.7

change "data = urllib.parse.urlencode(values) " to python 2.7

每个人,我必须将一些代码从 python 3.* 更改为 2.7,但是,我只是不知道 python 中的代码 data = urllib.parse.urlencode(values) 是什么=] 2.7

python3.*

import urllib.parse
import urllib.request


def sendsms(phonenumber,textcontent):
    url = 'http://urls?'
    values = {'username' : 'hello',
              'password' : 'world',
              'dstaddr' : phonenumber ,
              'smbody': textcontent
               }

    data = urllib.parse.urlencode(values)
    data = data.encode('Big5') 
    req = urllib.request.Request(url, data)
    with urllib.request.urlopen(req) as response:
       the_page = response.read()

python 2.7

from urlparse import urlparse
from urllib2 import urlopen
from urllib import urlencode

def sendsms(phonenumber,textcontent):
    url = 'http://urls?'
    values = {'username' : 'hello',
              'password' : 'world',
              'dstaddr' : phonenumber ,
              'smbody': textcontent
               }

    data = urllib.parse.urlencode(values)  #python 3.* code, what about python 2.7 ?

    data = data.encode('Big5') 
    req = urllib.request.Request(url, data)
    with urllib.request.urlopen(req) as response:
       the_page = response.read()

这是 python 2.7 中 urllib 函数调用的等价物,它应该可以工作。

import urllib
import urllib2
from contextlib import closing

def sendsms(phonenumber,textcontent):
    url = 'http://urls?'
    values = {'username' : 'hello',
              'password' : 'world',
              'dstaddr' : phonenumber ,
              'smbody': textcontent
               }

    data = urllib.urlencode(values)
    data = data.encode('Big5')
    req = urllib2.Request(url, data)
    with closing(urllib2.urlopen(req)) as response:
       the_page = response.read()

编辑:感谢@Cc L 指出由于未实现上下文管理器而将 with ... asurlopen 结合使用时出现的错误。这是另一种方法,其中返回 closing 的上下文管理器在块完成时关闭 the_page

首先,感谢上面wolfsgang的回答,然后我修改了我的代码,它可以工作

import urllib
import urllib2


def sendsms(phonenumber,textcontent):
    url = 'http://urls?'
    values = {'username' : 'hello',
              'password' : 'world',
              'dstaddr' : phonenumber ,
              'smbody': textcontent
               }


    data = urllib.urlencode(values)
    data = data.encode('Big5')
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req)