第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定

實例講解urllib在python2和python3的使用差異

標簽:
Python

Urllib是python提供的一个用于操作url的模块, 在python2和python3间是不兼容的,所以实际开发众我们需要为这两个版本分别写一套代码。

在python2中,有urllib库和urllib2库。在python3中,urllib2合并到urllib库中。

以下是python2与python3中常用的关于urllib库的变化:

   1.在python2中使用import urllib2————对应的,在python3中会使用import urllib.request,urllib.error

   2.在python2中使用import urllib————对应的,在python3中会使用import urllib.request,urllib.error,urllib.parse

   3.在python2中使用import urlparse————对应的,在python3中会使用import urllib.parse

   4.在python2中使用urllib2.urlopen————对应的,在python3中会使用urllib.request.urlopen

   5.在python2中使用urllib.urlencode————对应的,在python3中会使用urllib.parse.urlencode

   6.在python2中使用urllib.quote————对应的,在python3中会使用urllib.request.quote

   7.在python2中使用cookielib.CookieJar————对应的,在python3中会使用http.CookieJar

   8.在python2中使用urllib2.Request————对应的,在python3中会使用urllib.request.Request


下面我们通过具体实例来说明一下, 榛子云短信(短信验证码平台)的一个发送api:

python2源码:

import urllib
import urllib2

class ZhenziSmsClient(object):
	url = "http://sms.zhenzikj.com";
	def __init__(self, appId, appSecret):
		self.appId = appId
		self.appSecret = appSecret
	def send(self, number, message):
		data = {
    	    'appId': self.appId,
		    'appSecret': self.appSecret,
		    'message': message,
		    'number': number
		}
		data = urllib.urlencode(data);
		req = urllib2.Request(self.url+'/sms/send.do', data);
		res_data = urllib2.urlopen(req);
		res = res_data.read();
		return res;

send是发送短信方法,参数number是接收手机号码,message是短信内容

python3源码:

import urllib.request
import urllib.parse

class ZhenziSmsClient(object):
	url = "http://sms.zhenzikj.com";
	def __init__(self, appId, appSecret):
		self.appId = appId
		self.appSecret = appSecret

	def send(self, number, message):
		data = {
    	    'appId': self.appId,
		    'appSecret': self.appSecret,
		    'message': message,
		    'number': number
		}
		data = urllib.parse.urlencode(data).encode('utf-8');
		req = urllib.request.Request(self.url+'/sms/send.do', data=data);
		res_data = urllib.request.urlopen(req);
		res = res_data.read();
		res = res.decode('utf-8');
		return res;



来源: http://smsow.zhenzikj.com/bbs/question/detail/48.html

點擊查看更多內(nèi)容
1人點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優(yōu)質(zhì)文章

正在加載中
感謝您的支持,我會繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優(yōu)惠券免費領(lǐng)

立即參與 放棄機會
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號

舉報

0/150
提交
取消