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

时间:2016-06-16 11:47:35

标签: python-2.7 python-3.x urllib2 urllib

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

  

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()

2 个答案:

答案 0 :(得分:7)

这是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

答案 1 :(得分:0)

首先,感谢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)