新建http_lib.py
import urllib.request
from flask import current_app
class HttpLib(object):
@classmethod
def _http_get(cls, url, headers={}):
from urllib import error
req = urllib.request.Request(url=url, headers=headers)
try:
res_data = urllib.request.urlopen(req)
res = res_data.read()
except error.HTTPError as e:
res = e.read().decode()
current_app.logger.error(res)
raise Exception(e)
return res.decode()
@classmethod
def _http_post(cls, url, data, headers={}, method='POST'):
from urllib import error
req = urllib.request.Request(
url=url, data=data if isinstance(data, bytes) else data.encode(),
headers=headers,
method=method
)
try:
res_data = urllib.request.urlopen(req)
res = res_data.read().decode()
except error.HTTPError as e:
res = e.read().decode()
current_app.logger.error(res)
raise Exception(e)
return res
@classmethod
def _http_post_dict(cls, url, data={}, headers={}):
return cls._http_post(url, json.dumps(data, ensure_ascii=False), headers=headers)
@classmethod
def _http_put_dict(cls, url, data={}, headers={}):
return cls._http_post(url, json.dumps(data, ensure_ascii=False), headers=headers, method='PUT')
@classmethod
def _http_delete_dict(cls, url, data={}, headers={}):
return cls._http_post(url, json.dumps(data, ensure_ascii=False), headers=headers, method='DELETE')