python常用库 urllib2介绍 URL编码 发送HTTP请求 高精度计算

2015-05-10 21:16:00
admin
原创 2233
摘要:python常用库 urllib2介绍 URL编码 发送HTTP请求 高精度计算

一、python常用库

1、http请求库有urllib、urllib2、requests,其中urllib和urlib2是自带模块,推荐使用requests;

2、加解密库有rsa、pycryptodome、cryptography,都是第三方模块,推荐使用cryptography;

3、高精度计算库gmpy2,pip无法正常安装时可以通过网站直接下载:https://www.lfd.uci.edu/~gohlke/pythonlibs/


二、urllib和urllib2区别

1、urllib提供urlencode方法编码请求字符串,urllib2没有,urllib和urllib2通常配合使用;

2、urllib2可以接受一个Request实例来设置URL请求头,urllib仅可以接受URL;

3、urllib2支持http、https、ftp;


三、URL编码

1、URL中的保留字符有特殊含义,所以URL上的请求内容需要进行编码,否则URL解释时会出错;

2、URL保留字符:/分割路径,?分割请求内容,=分割name和value,@分割URL用户信息;

3、编码格式是%加上字符的ASCII码;

4、quote编码空格为%20,默认安全字符/,quote_plus编码空格为加号,默认无安全字符;

5、urllib.urlencode调用参数是字典,且使用quote_plus进行编码;

6、编码工具:https://www.bejson.com/enc/urlencode


四、urllib2发送GET请求

1、urlopen自动进行重定向处理;

2、geturl返回重定向后的地址;


def testGet():
    obj = urllib2.urlopen('http://www.3scard.com')
    print obj.geturl()
    print obj.getcode()
    print obj.info()
    print obj.read()


五、urllib2发送POST请求

def testPost(url, data):
    data = urllib.urlencode(data)
    obj = urllib2.urlopen(url, data)
    print obj.read()

def main():
    url = "http://127.0.0.1:8080/springmvc/test_post.do"
    data = {'name':'feinen', 'age':'20'}
    testPost(url , data)


六、urllib2使用opener发送POST请求

def testPost(url, data):
    req = urllib2.Request(url)
    data = urllib.urlencode(data)
    #enable cookie
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
    response = opener.open(req, data)
    print response.read()

def main():
    url = "http://127.0.0.1:8080/springmvc/test_post.do"
    data = {'name':'feinen', 'age':'20'}
    testPost(url , data)


七、增加请求头

req.add_header('Content-Type', 'multipart/form-data; boundary=%s; charset=utf-8' % boundary) 
req.add_header('User-Agent','Mozilla/5.0')


八、高精度计算

1、整数类型有int和long,int长度是32比特,long长度无限制;

2、int构造函数int(x, base=10),long构造函数long(x, base=10),其中x可以是字符串;

3、整数常量开头可以是0b、0o、0x,或者直接是十进制常量;


gmpy2常用函数:

1、帮助指引:https://gmpy2.readthedocs.io/en/latest/

2、mpz,gmpy2整数类型;

3、isqrt,计算平方根;

4、iroot,计算任意次方根

5、gcd,计算最大公约数;

6、gcdext,计算最大公约数和方程乘数,g=gcd(a,b),g=ax+by,返回数组(g,x,y);

7、invert,计算乘法逆元;

8、powmod,进行模幂运算;

发表评论
评论通过审核之后才会显示。