Reqable 中文文档 下载 App

脚本入口函数 onRequest 和 onResponse 怎么写

Reqable 的脚本用 Python3 语法编写(要求本机 Python3 大于 3.6,见 Python 脚本环境),提供两个函数入口。

onRequest:请求发出前

在客户端请求发送给服务器之前调用,可以在此修改请求。函数接收 CaptureContext 和 HttpRequest 两个参数,并返回 HttpRequest:

def onRequest(context, request):
    # 在这里修改 request
    return request

中断请求的写法:让 onRequest 返回 None,该请求即被拦截不再发出。

onResponse:响应回到客户端前

在服务器响应发送给客户端之前调用,可以修改响应。参数与返回值对应 CaptureContext 和 HttpResponse:

def onResponse(context, response):
    # 在这里修改 response
    return response

同样,返回 None 即中断该响应。

两个函数之间共享数据

有一个容易踩的坑:onRequest 和 onResponse 分别运行在不同的进程中,不能直接共享外部变量。需要传递数据时用 CaptureContext 的 shared 变量:

def onRequest(context, request):
    context.shared = 'foobar'
    return request

def onResponse(context, response):
    print(context.shared)  # 输出 foobar
    return response

内置 API 能做什么

脚本 API 提供了对请求/响应各部分的读写能力(URL、头部、体、状态等),具体接口以官方文档的「脚本 API」页面为准。写作时的通用思路:

调试建议

脚本规则的管理方式(文件夹、导入导出)与其他规则一致。到这里四大调试手段已经讲了三个,还有个轻量的 网络环境模拟。