2.3 requests发送http请求及代码的简化手段
#封装HTTP请求类
#发送http请求的两种方式
#urllib
#requests
#from urllib import request
import requests
class HTTP: #class HTTP(object):有无都无所谓
#def get(self,url,return_json=True):
#或者使用静态方法,与上面一模一样
@staticmethod
def get(url,return_json=True):
r = requests.get(url)
#restful
#json
# if r.status_code == 200:
# if return_json():
# return r.json()
# else:
# return r.text
# else:
# if return_json:
# return {}
# else:
# return ''
#将以上代码优化
if r.status_code != 200:
return {} if return_json else '' #特例情况
return r.json() if return_json else r.text #正常返回
#优化; if else ,for 提取成另一个函数Last updated
Was this helpful?