首页 > 其他分享 >fastrpc的使用

fastrpc的使用

时间:2023-08-24 14:48:13浏览次数:30  
标签:function responseJson wsURL request var 使用 fastrpc action

首先为了防止项目更新我把它fork到我的git下面的了,项目地址
[email protected]:cxapython/fastrpc.git。

这是一个python和js的项目,首先使用python3,安装所需要的依赖问题
然后直接,启动sekiro服务

python3 main.py

之际将client.js文件放到油猴脚本。

例如下面的xhs的。x-s获取

// ==UserScript==
// @name         getXS
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://www.xiaohongshu.com/search_result*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=xiaohongshu.com
// @grant        none
// ==/UserScript==


function WSClient(wsURL) {
    this.wsURL = wsURL;
    this.handlers = {};
    this.socket = {};
    // check
    if (!wsURL) {
        throw new Error('wsURL can not be empty!!')
    }
    this.webSocketFactory = this.resolveWebSocketFactory();
    this.connect()
}

WSClient.prototype.resolveWebSocketFactory = function () {
    if (typeof window === 'object') {
        var theWebSocket = window.WebSocket ? window.WebSocket : window.MozWebSocket;
        return function (wsURL) {

            function WindowWebSocketWrapper(wsURL) {
                this.mSocket = new theWebSocket(wsURL);
            }

            WindowWebSocketWrapper.prototype.close = function () {
                this.mSocket.close();
            };

            WindowWebSocketWrapper.prototype.onmessage = function (onMessageFunction) {
                this.mSocket.onmessage = onMessageFunction;
            };

            WindowWebSocketWrapper.prototype.onopen = function (onOpenFunction) {
                this.mSocket.onopen = onOpenFunction;
            };
            WindowWebSocketWrapper.prototype.onclose = function (onCloseFunction) {
                this.mSocket.onclose = onCloseFunction;
            };

            WindowWebSocketWrapper.prototype.send = function (message) {
                this.mSocket.send(message);
            };

            return new WindowWebSocketWrapper(wsURL);
        }
    }
    if (typeof weex === 'object') {
        // this is weex env : https://weex.apache.org/zh/docs/modules/websockets.html
        try {
            console.log("test webSocket for weex");
            var ws = weex.requireModule('webSocket');
            console.log("find webSocket for weex:" + ws);
            return function (wsURL) {
                try {
                    ws.close();
                } catch (e) {
                }
                ws.WebSocket(wsURL, '');
                return ws;
            }
        } catch (e) {
            console.log(e);
            //ignore
        }
    }
    //TODO support ReactNative
    if (typeof WebSocket === 'object') {
        return function (wsURL) {
            return new theWebSocket(wsURL);
        }
    }
    // weex 鍜� PC鐜鐨剋ebsocket API涓嶅畬鍏ㄤ竴鑷达紝鎵€浠ュ仛浜嗘娊璞″吋瀹�
    throw new Error("the js environment do not support websocket");
};

WSClient.prototype.connect = function () {
    console.log('sekiro: begin of connect to wsURL: ' + this.wsURL);
    var _this = this;
    // 涓峜heck close锛岃
    // if (this.socket && this.socket.readyState === 1) {
    //     this.socket.close();
    // }
    try {
        this.socket = this.webSocketFactory(this.wsURL);
    } catch (e) {
        console.log("sekiro: create connection failed,reconnect after 2s");
        setTimeout(function () {
            _this.connect()
        }, 2000)
    }

    this.socket.onmessage(function (event) {
        _this.handleSekiroRequest(event.data)
    });

    this.socket.onopen(function (event) {
        console.log('sekiro: open a sekiro client connection')
    });

    this.socket.onclose(function (event) {
        console.log('sekiro: disconnected ,reconnection after 2s');
        setTimeout(function () {
            _this.connect()
        }, 2000)
    });
};

WSClient.prototype.handleSekiroRequest = function (requestJson) {
    console.log("receive sekiro request: " + requestJson);
    var request = JSON.parse(requestJson);
    var seq = request['__sekiro_seq__'];
    console.log('request', request)
    if (!request['action']) {
        // this.sendFailed(seq, 'need request param {action}');
        return
    }
    var action = request['action'];
    if (!this.handlers[action]) {
        // this.sendFailed(seq, 'no action handler: ' + action + ' defined');
        return
    }

    const theHandler = this.handlers[action];
    var _this = this;
    try {
        theHandler(request, function (response) {
            try {
                _this.sendSuccess(seq, response)
            } catch (e) {
                _this.sendFailed(seq, "e:" + e);
            }
        }, function (errorMessage) {
            _this.sendFailed(seq, errorMessage)
        })
    } catch (e) {
        console.log("error: " + e);
        _this.sendFailed(seq, ":" + e);
    }
};

WSClient.prototype.sendSuccess = function (seq, response) {
    var responseJson;
    if (typeof response == 'string') {
        try {
            responseJson = JSON.parse(response);
        } catch (e) {
            responseJson = {};
            responseJson['data'] = response;
        }
    } else if (typeof response == 'object') {
        responseJson = response;
    } else {
        responseJson = {};
        responseJson['data'] = response;
    }


    if (Array.isArray(responseJson)) {
        responseJson = {
            data: responseJson,
            code: 0
        }
    }

    if (responseJson['code']) {
        responseJson['code'] = 0;
    } else if (responseJson['status']) {
        responseJson['status'] = 0;
    } else {
        responseJson['status'] = 0;
    }
    responseJson['__sekiro_seq__'] = seq;
    var responseText = JSON.stringify(responseJson);
    console.log("response :" + responseText);
    this.socket.send(responseText);
};

WSClient.prototype.sendFailed = function (seq, errorMessage) {
    if (typeof errorMessage != 'string') {
        errorMessage = JSON.stringify(errorMessage);
    }
    var responseJson = {};
    responseJson['message'] = errorMessage;
    responseJson['status'] = -1;
    responseJson['__sekiro_seq__'] = seq;
    var responseText = JSON.stringify(responseJson);
    console.log("sekiro: response :" + responseText);
    this.socket.send(responseText)
};

WSClient.prototype.registerAction = function (action, handler) {
    if (typeof action !== 'string') {
        throw new Error("an action must be string");
    }
    if (typeof handler !== 'function') {
        throw new Error("a handler must be function");
    }
    console.log("sekiro: register action: " + action);
    this.handlers[action] = handler;
    return this;
};
function guid() {
    function S4() {
          return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
        }
        return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}

const client = new WSClient("ws://localhost:8000/ws/" + guid());

client.registerAction("clientTime",function(request, resolve,reject ){
        resolve(""+new Date());
})
client.registerAction("html",function(request, resolve,reject ){
        resolve(document.documentElement.outerHTML);
})
client.registerAction("cookies",function(request, resolve,reject ){
        resolve(document.cookie);
})

client.registerAction("get_headers",function(request, resolve,reject ){
        console.log("request",request)
        var params = request.param
        var url_path = params.url_path
        var param = params.param
        var result = window._webmsxyw(url_path,params)
        resolve(result);
})


然后在python中这样使用
这里以post请求为例,参数action和param是固定的名称。
action就是请求下面方法的内容,这里是get_headers。

    post_data = {"action": "get_headers", "param": {"url_path": url_path, "param": json_data}}
    response = None
    for i in range(10):
        try:
            response = requests.post("http://localhost:8000/invoke", headers=headers2,
                                     data=json.dumps(post_data, ensure_ascii=False, separators=(',', ':')).encode(),
                                     timeout=3)
            break
        except Exception:
            pass

请求的方法就是上面的js的这段代码

client.registerAction("get_headers",function(request, resolve,reject ){
        console.log("request",request)
//这里面写逻辑就好了
        var params = request.param
        var url_path = params.url_path
        var param = params.param
        var result = window._webmsxyw(url_path,params)
        resolve(result); //返回内容
})

标签:function,responseJson,wsURL,request,var,使用,fastrpc,action
From: https://www.cnblogs.com/c-x-a/p/17654061.html

相关文章

  • mysql使用sql开启日志
    --查看日志是否开启和日志文件夹showvariableslike'%general%';SETGLOBALgeneral_log='On';setgloballog_syslog=on;--慢sql日志setglobalslow_query_log=on;setglobalsql_log_off=on;--设置日志生成道的文件夹SETGLOBALgeneral_log_file='/lo......
  • shopify如何添加在线客服-跨境电商在线客服使用
    Shopify在线客服添加的好处有助于提高销量一、售前和售后服务对整个销量的重要作用亚马逊售后只能通过邮件跟客户进行交流Shopify可以通过在线聊天客服添加到在线商店中,提高沟通时效率我们在shopify的模板页面上可以直接添加在线客服的代码,参照下图的步骤找到编辑代码的部......
  • StableVideo:使用Stable Diffusion生成连续无闪烁的视频
    使用StableDiffusion生成视频一直是人们的研究目标,但是我们遇到的最大问题是视频帧和帧之间的闪烁,但是最新的论文则着力解决这个问题。本文总结了Chai等人的论文《StableVideo:Text-drivenconsistency-awareDiffusionVideoEditing》,该论文提出了一种新的方法,使扩散模型能......
  • Python-PyMySQL的一些使用注意事项
    一、关于groupby的使用在部分mysql版本(5.7.xx及以上)中,若select的列中,包含了未被groupby的字段,会报以下错误:[Err]1055-Expression#1ofORDERBYclauseisnotinGROUPBYclauseandcontainsnonaggregatedcolumn'xxxx'whichisnotfunctionallydependentoncolu......
  • pip或者pip3安装软件,使用国内的镜像源?
    使用pip3或者pip安装软件,默认使用的是python官方的镜像,如果遇到速度慢,或者超时的情况,可以考虑使用国内的镜像源。 如下:清华大学镜像源(Tuna):  https://pypi.tuna.tsinghua.edu.cn/simplepipinstall-ihttps://pypi.tuna.tsinghua.edu.cn/simplepackage-name  ......
  • Batfish (Bazel版) Windows使用 IDEA
    1.安装Bazelhttps://docs.bazel.build/versions/4.1.0/install-windows.html#installing-bazel,按照Step一步步完成就可以了需要安装MSY64,装在C:\msys64\下,按照这个改环境变量就可以https://docs.bazel.build/versions/4.1.0/install-windows.html#troubleshooting2.修......
  • 使用 OpenTelemetry 构建可观测性 06 - 生态系统
    过去的五篇文章讨论了如何使用OpenTelemetry来构建可观测性的技术细节。我认为在本博文系列的结尾介绍有关OTel生态系统的信息,为读者提供更全面的了解非常重要。OpenTelemetry的发展非常迅速,对于刚接触它的人来说,可能会感到有些不知所措或困惑,不知道在哪里找到有效的信息或资......
  • K8S集群中使用JD KMS服务对敏感数据安全加密
    基本概念KMS,KeyManagementService,即密钥管理服务,在K8S集群中,以驱动和插件的形式启用对Secret,Configmap进行加密。以保护敏感数据,驱动和插件需要使用者按照需求进行定制和实现自己的KMS插件,插件可以是gRPC服务器或者启用一个云服务商提供的KMS插件。本文中演示使用的KMS服务......
  • Unity UGUI的Toggle(复选框)组件的介绍及使用
    UnityUGUI的Toggle(复选框)组件的介绍及使用1.什么是Toggle组件?Toggle(复选框)是UnityUGUI中的一个常用组件,用于实现复选框的功能。它可以被选中或取消选中,并且可以代码通过其制控状态。2.Toggle组件的工作原理组Toggle件由两个部分组成:背景记标和。景背用于显示复选框的外观......
  • linux服务器docker compose的使用步骤
    之前说了docker的安装,dockercompose的安装,还比较了dockerfile和dockercompose的区别,那么dockercompose的实际应用是怎么样呢?记录下我的实操步骤1、服务器上新建目录,目录情况如下,我的data目录是挂载到数据盘的/data/docker_config/nginx//存放nginx的配置文件/dat......