#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2022/8/29 23:14 # @Author : old tom # @File : http_response.py # @Project : Futool # @Desc : 响应解析 from http.client import HTTPResponse from http.cookiejar import CookieJar import json DEFAULT_ENCODING = 'UTF-8' # 响应类型编码 RESPONSE_CONTENT_ENCODING = "Content-Encoding" # 压缩类型 COMPRESS_TYPE = ('gzip', 'deflate', 'br') class ResponseWrapper(object): def __init__(self, response: HTTPResponse, cookie: CookieJar = None): self.resp = response if cookie and len(cookie) > 0: self.cookie = cookie def body(self, encoding=DEFAULT_ENCODING): return self.resp.read().decode(encoding) def json_body(self, encoding=DEFAULT_ENCODING): return json.loads(self.body(encoding)) def status(self): return self.resp.status def is_ok(self): st_code = self.resp.status return 200 <= st_code <= 300 def header(self, name=None): return self.resp.getheader(name) if name else self._parse_header_dict() def _parse_header_dict(self): headers = self.resp.getheaders() header_dict = {} if headers: for h in headers: header_dict[h[0]] = h[1] return header_dict def is_compress(self): """ 是否压缩 :return: """ return self.compress_type() in COMPRESS_TYPE def compress_type(self): """ 压缩格式 :return: """ header = self.header() if RESPONSE_CONTENT_ENCODING in header.keys(): res_content_encoding = header[RESPONSE_CONTENT_ENCODING] return res_content_encoding def cookies(self): """ 获取cookie :return: """ ck = {} if self.cookie: for item in self.cookie: ck[item.name] = item.value return ck