python之 网络编程、异常处理、面向对象

1.网络编程

from urllib.request import  urlopen
from urllib.parse import urlencode
url='http://118.24.3.40/api/user/stu_info'
# res=urlopen(url) #发get请求
# print(res.read().decode())
# data={'username':'****','passwd':'*****'}
# print(urlencode(data))
# res=urlopen(url,urlencode(data).encode()) #post请求,不能直接传字典.用urlencode转换为k,v的形式,再转换为二进制的形式
# print(res.read().decode())#
上述方法较为复杂,建议用以下方式

import requests
# res=requests.get(url,params={'stu_name':'小黑'})#发送get请求。params里放请求参数
# print(res.json())#json直接将返回结果转换为字典
# url2='http://118.24.3.40/api/user/login'
# data={'username':'*****','passwd':'******'}
# res=requests.post(url2,data=data) #post请求
# print(res.json())

# res=requests.post(url2,json=data) data数据为json格式时

# url3='http://118.24.3.40/api/user/gold_add'
# data={'stu_id':15,'gold':200}
# cookies={'******':'abd9a0995f4696e1a60133220b32037a'}
# res=requests.post(url3,data=data,cookies=cookies)
# print(res.json())

# url4='http://118.24.3.40/api/user/all_stu'
# header={'Referer':'http://api.nnhp.cn/'}
# res=requests.post(url4,headers=header)
# print(res.json()) #返回的是字典

# url5='http://www.nnzhp.cn'
# res=requests.get(url5)
# print(res.text) #返回的都是字符串

# url6='http://qiniuuwmp3.changba.com/1084511584.mp3' 下载文件
# res=requests.get(url6,verify=False)#verify=False 如果是https的话加上这个
# print(res.content) #返回的就是2进制的
# with open('魔鬼中的天使.MP3','wb') as fw: #wb写二进制,下载文件都是用二进制的模式
# fw.write(res.content)

# print(res.json()) #必须返回的是json才能用
# print(res.text) #下载文件的话text就不行了
# print(res.content) #用来下载文件用的,必须是二进制的
# print(res.headers) #获取返回的所有header
# print(res.cookies)#获取返回的所有cooke

url7='http://118.24.3.40/api.file/file_upload' 上传文件
data={'file':open('魔鬼中的天使.mp3','rb')}
res=requests.post(url7,files=data)
print(res.json())

print(res.status_code)#获取他的状态码

2.异常处理
避免了代码出现异常时出现大量报错,方便调试
money=1000
num=input('please enter a num:')
try: 尝试运行以下代码
num=float(num)
res=money/num
# except ValueError as e: #出现异常了,就走except下面的代码
# print('出现异常了')
# print('你输入的价格不合法')
# print(e)
# except ZeroDivisionError as e:
# print('除数不能为0')
except Exception as e: #可以捕捉到所有的异常,这种方法可以代替所有的异常,即以上两种错误可以用这种方法合并处理
print('出现异常了')
print(e)
else: 当程序没有异常时,运行以下代码
money-=num
print('你的余额是%s'%money)
finally: #无论是否出现错误,都会执行finally的代码
print('我是finally')
 

猜你喜欢

转载自www.cnblogs.com/kuhaha/p/9367359.html