关于mock实战作业

在跟着直播敲完代码后,运行报错:

Addon error: Traceback (most recent call last):
  File "E:/PyCharm Community Edition 2020.3.3/homework/demo/mitm_map_local.py", line 40, in request
    flow.response = http.HTTPResponse.make(200,f.read())
AttributeError: module 'http' has no attribute 'HTTPResponse'

他说我http里没有HTTPResponse,怎么解决
这是我Python和mitmproxy的版本号
bannebn

http 这个引用是否为

from mitmproxy import http

又有新问题了,刚刚引用改掉后又报这个错:

Addon error: Traceback (most recent call last):
  File "E:/PyCharm Community Edition 2020.3.3/homework/demo/mitm_map_local.py", line 40, in request
    flow.response = http.HTTPResponse.make(200,f.read())
io.UnsupportedOperation: not readable

贴上你的代码文件吧

"""HTTP-specific events."""
from mitmproxy import http
import json

import mitmproxy.http


class Events:
    def http_connect(self, flow: mitmproxy.http.HTTPFlow):
        """
            An HTTP CONNECT request was received. Setting a non 2xx response on
            the flow will return the response to the client abort the
            connection. CONNECT requests and responses do not generate the usual
            HTTP handler events. CONNECT requests are only valid in regular and
            upstream proxy modes.
        """
        pass

    def requestheaders(self, flow: mitmproxy.http.HTTPFlow):
        """
            HTTP request headers were successfully read. At this point, the body
            is empty.
        """
        pass

    def request(self, flow: mitmproxy.http.HTTPFlow):
        """
            The full HTTP request has been read.
        """
        if "https://stock.xueqiu.com/v5/stock/batch/quote.json" in flow.request.url\
            and "x=" in flow.request.url:
            data = json.load(open("C:/Users/Admin/Desktop/xueqiu.json",encoding="utf-8"))
            data["data"]["items"][1]["quote"]["name"] += data["data"]["items"][1]["quote"]["name"]
            data["data"]["items"][2]["quote"]["name"] = ""

            with open("xueqiu2.json","w",encoding="utf-8") as f:
                json.dump(data,f)

            with open("xueqiu2.json", "w", encoding="utf-8") as f:
                flow.response = http.HTTPResponse.make(200,f.read())


    def responseheaders(self, flow: mitmproxy.http.HTTPFlow):
        """
            HTTP response headers were successfully read. At this point, the body
            is empty.
        """
        pass

    def response(self, flow: mitmproxy.http.HTTPFlow):
        """
            The full HTTP response has been read.
        """
        pass

    def error(self, flow: mitmproxy.http.HTTPFlow):
        """
            An HTTP error has occurred, e.g. invalid server responses, or
            interrupted connections. This is distinct from a valid server HTTP
            error response, which is simply a response with an HTTP error code.
        """
        pass
addons = [Events()]
if __name__ == '__main__':
    from mitmproxy.tools.main import mitmdump
    #使用debug模式启动mitmdump
    mitmdump(['-p', '8080', '-s', __file__])


检查下这段代码吧,没有用就删除掉

我改成这样之后还是报错

    def request(self, flow: mitmproxy.http.HTTPFlow):
        """
            The full HTTP request has been read.
        """
        if "https://stock.xueqiu.com/v5/stock/batch/quote.json" in flow.request.url\
            and "x=" in flow.request.url:
            data = json.load(open("C:/Users/Admin/Desktop/xueqiu.json",encoding="utf-8"))
            data["data"]["items"][1]["quote"]["name"] += data["data"]["items"][1]["quote"]["name"]
            data["data"]["items"][2]["quote"]["name"] = ""


            with open("xueqiu.json", "w", encoding="utf-8") as f:
                flow.response = http.HTTPResponse.make(200,f.read())

这个是报错信息

Addon error: Traceback (most recent call last):
  File "E:/PyCharm Community Edition 2020.3.3/homework/demo/mitm_map_local.py", line 38, in request
    flow.response = http.HTTPResponse.make(200,f.read())
io.UnsupportedOperation: not readable

这个addons的包还需要配置环境变量吗

with open("xueqiu.json", "r", encoding="utf-8") as f:
                flow.response = http.HTTPResponse.make(200,f.read())

在把这个文件以管理员身份运行

是单独打开吗,这是我抓到的包保存下来的json文件,是个文本文档,我不知道怎么以管理员方式运行

E:/PyCharm Community Edition 2020.3.3/homework/demo/mitm_map_local.py 这个文件直接运行

直接运行会报错:

Addon error: Traceback (most recent call last):
  File "E:\PyCharm Community Edition 2020.3.3\homework\demo\mitm_map_local.py", line 38, in request
    flow.response = http.HTTPResponse.make(200,f.read())
io.UnsupportedOperation: not readable

https://docs.mitmproxy.org/stable/addons-scripting/

参照官方文档修改代码

from mitmproxy import http

def request(flow: http.HTTPFlow) -> None:
    if flow.request.pretty_url == "http://example.com/path":
        flow.response = http.HTTPResponse.make(
            200,  # (optional) status code
            b"Hello World",  # (optional) content
            {"Content-Type": "text/html"}  # (optional) headers
        )


这里问题,去掉试试

去掉后报错问题解决了,但是雪球那边没有成功达到效果,雪球那边提示“雪球似乎出了点错误,请稍后再试”

那就是你json文件内容不对了

我重新抓了一次包,还是那样

关闭