python 网站源码_怎么编译源代码

python 网站源码_怎么编译源代码源码目录结构ApiResponse这个类没啥好说的classApiResponse(Response):"""继承了requests模块中的Response类

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

源码目录结构

python 网站源码_怎么编译源代码
 

ApiResponse

这个类没啥好说的

class ApiResponse(Response):
    """
    继承了requests模块中的Response类,重写了里面的raise_for_status方法
    """
    def raise_for_status(self):
        if hasattr(self, "error") and self.error:
            raise self.error
        Response.raise_for_status(self)

 

get_req_resp_record

这个函数的功能是获取请求记录和响应记录,源码分为4段来看
 

第1段

def get_req_resp_record(resp_obj: Response) -> ReqRespData:
    """
    :param resp_obj: Response响应
    :return: 返回自定义的ReqResData模型类
    """

    def log_print(req_or_resp, r_type):
        """
        日志打印,格式为标准的json
        """
        msg = f"\n================== {r_type} details ==================\n"
        for key, value in req_or_resp.dict().items():
            # 如果value中还包含着dict或者list,就把value转成json格式
            if isinstance(value, dict) or isinstance(value, list):
                value = json.dumps(value, indent=4, ensure_ascii=False)

            msg += "{:<8} : {}\n".format(key, value)
        logger.debug(msg)

第1段代码就是定义了一个打印日志的函数,打印的日志解析为标准的json格式
 

第2段

# 记录实际请求信息(请求头、cookie信息、请求体)
    request_headers = dict(resp_obj.request.headers)
    request_cookies = resp_obj.request._cookies.get_dict()

    request_body = resp_obj.request.body
    if request_body is not None:
        try:
            request_body = json.loads(request_body)
        except json.JSONDecodeError:
            # str: a=1&b=2
            pass
        except UnicodeDecodeError:
            # bytes/bytearray: request body in protobuf
            pass
        except TypeError:
            # neither str nor bytes/bytearray, e.g. <MultipartEncoder>
            pass

        # lower_dict_keys的作用是将字典中的key大写转小写
        request_content_type = lower_dict_keys(request_headers).get("content-type")
        if request_content_type and "multipart/form-data" in request_content_type:
            # upload file type
            request_body = "upload file stream (OMITTED)"

    request_data = RequestData(
        method=resp_obj.request.method,
        url=resp_obj.request.url,
        headers=request_headers,
        cookies=request_cookies,
        body=request_body,
    )
    # 在debug模式下打印请求日志
    log_print(request_data, "request")

第2段代码是先获取request_headersrequest_cookiesrequest_body,然后将获取到的信息放入RequestData模型中,最后打印请求的信息
 

第3段

# 记录响应信息
    resp_headers = dict(resp_obj.headers)
    lower_resp_headers = lower_dict_keys(resp_headers)
    content_type = lower_resp_headers.get("content-type", "")

    if "image" in content_type:
        # response is image type, record bytes content only
        response_body = resp_obj.content
    else:
        try:
            # try to record json data
            response_body = resp_obj.json()
        except ValueError:
            # only record at most 512 text charactors
            resp_text = resp_obj.text
            response_body = omit_long_data(resp_text)

    response_data = ResponseData(
        status_code=resp_obj.status_code,
        cookies=resp_obj.cookies or {},
        encoding=resp_obj.encoding,
        headers=resp_headers,
        content_type=content_type,
        body=response_body,
    )

    # 在debug模式下打印响应日志
    log_print(response_data, "response")

第3段代码是获取resp_headerscontent_typeresponse_body,最后将这些数据都放入ResponseData模型类中,最后打印响应日志
 

第4段

req_resp_data = ReqRespData(request=request_data, response=response_data)
    return req_resp_data

最后这段就是将刚才的请求信息和响应信息全部放入ReqRespData模型中,最后get_req_resp_record函数返回的内容就是ReqRespData模型
 

HttpSession

requests.Session上进行了二次封装,该类包含4个方法,下面依次介绍
 

init

    def __init__(self):
        super(HttpSession, self).__init__()
        self.data = SessionData()

初始化方法,定义了data属性的默认值为SessionData模型,该模型包含了req_resps: List[ReqRespData] = []请求响应内容
 

update_last_req_resp_record

    def update_last_req_resp_record(self, resp_obj):
        """
        update request and response info from Response() object.
        """
        # TODO: fix
        self.data.req_resps.pop()
        self.data.req_resps.append(get_req_resp_record(resp_obj))

更新最新的请求响应记录,放入req_resps列表中
 

request

发送requests.Request请求,返回requests.Response响应,还做了以下事情

  • 1.设置了超时时间120s
  • 2.计算整个请求花费了多少时间
  • 3.定义了客户端ip地址和端口号、服务端ip地址和端口号
  • 4.计算了响应体的内容大小
  • 5.记录了消耗时间
  • 6.记录了request和response记录,包括重定向记录
     

_send_request_safe_mode

发送一个http请求,并捕获由于连接问题可能发生的任何异常

    def _send_request_safe_mode(self, method, url, **kwargs):
        """
        Send a HTTP request, and catch any exception that might occur due to connection problems.
        Safe mode has been removed from requests 1.x.
        """
        try:
            return requests.Session.request(self, method, url, **kwargs)
        except (MissingSchema, InvalidSchema, InvalidURL):
            raise
        except RequestException as ex:
            resp = ApiResponse()
            resp.error = ex
            resp.status_code = 0  # with this status_code, content returns None
            resp.request = Request(method, url).prepare()
            return resp
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/166061.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Endnote 域代码已更改

    Endnote 域代码已更改word中参考文献位置出现“域代码已更改”的批注,并且还没有办法删除,现提供如下两个可能可以的解决方法:1.Alt+F9,确实会显示域代码,但是无法解决我的问题;2.直接换一个endnote格式,这个倒是解决了我的问题;上面两种方法都是网上找到的,仅做参考,希望在读者苦苦找寻而不得解的时候,能给予一点点及时的帮助,也希望以后我用得上的时候,我自己也能看到goodluck…

    2022年6月7日
    128
  • 使用FastJson对JSON字符串、JSON对象及JavaBean之间的相互转换

    使用FastJson对JSON字符串、JSON对象及JavaBean之间的相互转换maven依赖包:<!–https://mvnrepository.com/artifact/com.alibaba/fastjson–><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId>…

    2022年10月18日
    0
  • asp.net(c#)网页跳转 方法小结[通俗易懂]

    asp.net(c#)网页跳转 方法小结[通俗易懂]返回 打印asp.net(c#)网页跳转七种方法小结_实用技巧_脚本之家在asp.net下,经常需要页面的跳转,下面是具体的几种方法。跳转页面是大部编辑语言中都会有的,正面我们来分别介绍一下关于.net中response.redirectsever.executeserver.transfer三种页面跳转的方法①respo…

    2022年7月20日
    14
  • c语言基础—-字符串数组

    c语言基础—-字符串数组字符串在C语言中,字符串实际上是使用 null 字符'\0'终止的一维字符数组。因此,一个以null结尾的字符串,包含了组成字符串的字符。字符定义输

    2022年7月1日
    19
  • pycharm2021.12.12永久激活【2021免费激活】

    (pycharm2021.12.12永久激活)最近有小伙伴私信我,问我这边有没有免费的intellijIdea的激活码,然后我将全栈君台教程分享给他了。激活成功之后他一直表示感谢,哈哈~IntelliJ2021最新激活注册码,破解教程可免费永久激活,亲测有效,下面是详细链接哦~https://javaforall.net/100143.html23…

    2022年3月30日
    40
  • 方舟手游怎么用GG修改器_方舟生存进化gg脚本

    方舟手游怎么用GG修改器_方舟生存进化gg脚本首先,确定你的手机是否可以root,如果不能,需要下载平行空间。在平行空间内添加游戏,和gg修改器。其次,最好是下载正版修改。然后,打开平行空间和gg修改器的所有权限。gg修改器几个常用功能搜索介绍(这里指方舟),搜索数据主要分为两个种类,f类(属性类)和d类(物品类)。新手几个简单的操作,长按修改器图标,开启加速功能。长按搜索出的数据,会弹出选项界面。下面正式开始。一,琥珀修改。首先f搜索480…

    2022年9月3日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号