python接口自动化八--网络编程,异常处理,面对对象编程
1.网络编程
#网络请求方法一
from urllib.request import urlopen
from urllib.parse import urlencode
data={'username':'niuhanyang','passwd':'aA123456'}
res=urlopen('http://********/api/user/stu_info') #发送get请求
print(res.read().decode()) #查看请求结果
res=urlopen(url,urlencode(data).encode()) #发送post请求
print(res.read().decode()) #查看请求结果
#网络请求方法二
import requests
#发送带有参数的get请求
url='http://118.24.3.40/api/user/stu_info'
print(res.json()) #返回的结果必须是json格式的才可以用json()直接把返回结果转成字典
#发送参数是json格式的post请求
url2='http://118.24.3.40/api/user/add_stu'
print(res.json())
#发送带有cookie,header的post请求
url3 = 'http://118.24.3.40/api/user/gold_add'
data1 = {'stu_id': 15, 'gold': 200}
data2 = {
"name":"requests_name",
"grade":"天蝎座",
"phone":17712532946,
"sex":"男",
"age":28,
"addr":"河南省济源市北海大道32号"
}
data3 = {'file':open('魔鬼中的天使.mp3','rb')}
cookie = {'niuhanyang':'abd9a0995f4696e1a60133220b32037a'}
header = {'Referer':'http://api.nnzhp.cn/'}
res=requests.get(url,params={'stu_name':'小黑'}) #发送get请求,params类型为字典或者字节
res = requests.post(url3,data=data1,cookies=cookie) #发送带有cookie的post请求
res = requests.post(url3,headers=header) #发送带有headers的post请求
res = requests.post(url2,json=data2) #发送参数是json格式的post请求
res = requests.post(url,files=data3) #发送上传文件的post请求
res = requests.post(url,verify=False) #发送https请求时,带上这个
url1 ="https://qun.qq.com/cgi-bin/qun_mgr/get_group_list"
cookie = { "cookie": "pt2gguin=o0944527839; RK=3PwkP6phQV; ptcz=3a2f696ffba680b8cd3e348bbf57431d2243694416660ea95613175660c0a440; pgv_pvi=7702914048; pgv_pvid=4933765370; ptui_loginuin=944527839; pgv_si=s7643038720; _qpsvr_localtk=0.43753578919271874; uin=o0944527839; skey=@UnhuWAR3t; ptisp=ctc; p_uin=o0944527839; pt4_token=XsVAW80ypbI*umt2B*sJ4oeJY9Iynhq95U8NAAc**do_; p_skey=cN-9paU8c805IEx--UEqzt6xOozxPGDLufithuF6nek_"}
data1 = {"bkn":1187824086}
res = requests.post(url=url1, data=data1, headers=cookie)
print(res.json()) #返回的是字典
print(res.text) #返回的是字符串
print(res.content) #用来下载文件用的,返回的是二进制
print(res.cookies) #获取到返回的所有cookie
print(res.headers) #获取到返回的所有header
print(res.status_code) #获取返回的状态码
1.1 小例子 --下载图片
url6='https://aliimg.changba.com/cache/photo/855e5493-f018-44db-8892-c8660649327b_640_640.jpg'
res = requests.get(url6,verify=False)#verify=False如果是https的话加上这个
print(res.text)
with open('tu.jpg','wb') as fw:
fw.write(res.content)
1.2 小例子--获取qq群成员所有头像
import requests,pymongo,os
url = "https://qun.qq.com/cgi-bin/qun_mgr/search_group_members"
data = {"gc":728755825,"st":0,"end":200,"sort":0,"bkn":729730748}
header = {"Cookie":"pgv_pvi=1977809920; tvfe_boss_uuid=d8ce464d0b7bd6f6; RK=6RFHD8oPOz; ptcz=11c139fb4d425800954a94bcb78d8b04222ef05985e6b9ac493a28744decc178; pgv_pvid=744932512; ptui_loginuin=2851662269; o_cookie=2851662269; pt2gguin=o0469873580; uin=o0469873580; ptisp=ctc; pgv_si=s8086261760; skey=@LfPHQ7sb0; p_uin=o0469873580; pt4_token=sf7OadX0vT5Mv4PiIQ3xkHbiI9quA5GB75z8lMcLgag_; p_skey=PcX00u1AVFRWKu6N1S62ooT13P*JDcCOhq64nknIlGQ_"}
res = requests.post(url=url,data=data,headers=header)
mems = res.json().get("mems")
client = pymongo.MongoClient(host="118.24.3.40",port=27017)
db = client['qq_group']
table = db['dlx']
for i in mems:
mem = {
"qq":i.get("uin"),
"gender":i.get("g"),
"nick":i.get("nick"),
"card":i.get("card"),
"qage":i.get("qage")
}
if mem.get("gender") == 0:
mem['gender'] = "男"
elif mem.get("gender") == 1:
mem['gender'] = "女"
else:
mem['gender'] = "未知"
if mem.get("card") == "":
mem['card'] = "没有群名片"
table.insert_one(mem)
qq=mem.get("qq")
pics = requests.get("http://q4.qlogo.cn/g?b=qq&nk={0}&s=140".format(mem.get("qq")))
abs_path=os.path.join('pics',str(qq)+'.jpg')
with open(abs_path,"wb") as f:
f.write(pics.content)
2.异常处理
money=1000
num=input('please enter a num')
try:
num = float(num)
res = money/num
# except Exception as e:#发生异常时,就运行except下面的代码
except ValueError as e:
print('输入价格不合法',e)
else: #m没有异常时,运行下面代码
money-=num
print(num)
print('你的余额是%s'%money)
finally: #无论是否发生异常,都会运行
print('我是finally')
3.面对对象编程
类:用来描述具有相同的属性和方法的对象的集合,它定义了该集合中每个对象所共有的属性和方法,对象是类的实例。
方法:定义在类中的函数
类变量:类变量在整个实例化的对象中是公用的,类变量定义在类中且在函数体之外。
数据成员:类变量或者实例变量用于处理类及其实例化对象的相关的数据
方法重写:如果从父类继承的方法不能满足子类的需求,可以对其进行改写,这个过程叫方法的覆盖,也叫方法的重写
实例变量:定义在方法中的变量,只作用于当前实例的类
实例化:创建一个类的实例,类的具体对象
对象:通过类定义的数据结构实例。
class people : #定义一个类
name = ' '
age = 0 #定义基本属性
__weight = 0 #定义私有属性,私有属性在类外部无法被直接访问
#定义构造方法
def _init_(self,n,a,w):
self.name = n
self.age = a
self.__weight = w
def speak(self):
print("%s 说:我 %d 岁"%(self.name,self.age)
#实例化类
p = people('runoob',10,30)
p.speak()
3.1 小例子--封装mysql类
import pymysql
class MyDb:
def _init_(self,host,password,user,db,port=3306,charset='utf8',autocommit=True):
try:
self.coon = pymysql.connect(host=host,password=password,user=user,db=db,port=port,charset=charset,autocommit=autocommit)
except Exception as e:
print('数据库连接失败!错误信息是%s'%e)
raise Exception('数据库连接失败!%s'%e) #主动抛出一个异常
else:
self.cur = self.coon.cursor(pymysql.cursors.DictCursor)
def select_all(self,sql):
try:
self.cur.execute(sql)
except Exception as e:
res='sql语句错误,%s\n,错误的sql是【%s】'%(e,sql)
print(res)
else:
res = self.cur.fetchall()
return res
def select_one(self,sql):
try:
self.cur.execute(sql)
except Exception as e:
res = 'sql语句错误,%s\n,错误的sql是【%s】' % (e, sql)
print(res)
else:
res = self.cur.fetchone()
return res
def other_sql(self,sql):
try:
self.cur.execute(sql)
except Exception as e:
res = 'sql语句错误,%s\n,错误的sql是【%s】' % (e, sql)
print(res)
return res
def close(self):
print('Bye')
self.cur.close()
self.coon.close()
my = MyDb('IP','fsdf','sdfsd','sdfsdf')
my.select_one('select * from xx;')
my.select_one('select * from xx;')
my.select_one('select * from xx;')
my.close()
3.2 小例子--封装redis操作
import redis
class MyRedis:
def __init__(self,host,password,port=6379,db=0):
self.r = redis.Redis(host=host,password=password,port=port,db=db)
def op_str(self,k,v=None,ex=-1): #设置永不失效
if v:
self.r.set(k,v,ex)
else:
res = self.r.get(k)
if res:
return res.decode()
def op_hash(self,name,k=None):
if k:
res = self.r.hget(name.k)
if res: #判断是否有返回值
return res.decode()
else:
res = {}
for k,v in self.r.hgetall(name).items():
res[k.decode()] = v.decode()
return res
def my_type(self,k):
return self.r.type(k).decode()