• Title


    pyjsonrpc的使用

    客户端 JsonRpcClient.py

    #!usr/bin/env python2.7
    # -*- coding: utf-8 -*-
    
    import ssl
    import socket
    import inspect
    import logging
    import pyjsonrpc
    
    try:
        ssl._create_default_https_context = ssl._create_unverified_context
    except Exception:
        pass
    
    logger = logging.getLogger('blog')
    
    
    def func():
        # 获取当前函数名, 如果是类直接调用,则是类名
        return inspect.stack()[1][3]
    
    
    class JsonRpcIF(object):
        """封装的基类"""
        def __init__(self, server, port, ssl=True):
            if ssl:
                self.url = "https://%s:%s/jsonrpc" % (server, port)
            else:
                self.url = "http://%s:%s/jsonrpc" % (server, port)
    
        def request(self, method, params, timeout=None):
            # params是参数: {"key1": "value1", "key2": "value2"}
            try:
                self.client = pyjsonrpc.HttpClient(
                    url=self.url,
                    timeout=timeout,
                )
                # 获取服务端执行相应method后的结果
                response = getattr(self.client, method)(params)
            except socket.timeout:
                logger.error("JsonRpc request '%s' timeout", method)
                response = {"status": {"code": -1, "msg": "timeout"}}
            except Exception as err:
                logger.error("JsonRpc request '%s' exception: %s", method, err)
                response = {"status": {"code": -2, "msg": err}}
            return response
    
    
    class LocalRpc(JsonRpcIF):
        """连接本服务器rpc"""
    
        def __init__(self, server="127.0.0.1", port=8080):
            super(LocalRpc, self).__init__(server, port, ssl=False)
    
        def get_mac(self, request=None):
            # func() 返回的是"get_mac"字符串 request是参数: {"key1": "value1", "key2": "value2"}
            return self.request(func(), request, timeout=5)
    
        def get_server_ip(self, request=None):
            # func() 返回的是"get_server_ip"字符串
            return self.request(func(), request, timeout=10)
    
        def get_file_name(self, request=None):
            # func() 返回的是"get_file_name"字符串
            return self.request(func(), request, timeout=None)
    
    
    locRpc = LocalRpc(server="127.0.0.1", port=8080)
    
    

    服务端 JsonRpcServer.py

    #!usr/bin/env python2.7
    # -*- coding: utf-8 -*-
    
    import logging
    import traceback
    import pyjsonrpc
    
    
    logger = logging.getLogger('blog')
    
    
    class RequestHandler(pyjsonrpc.HttpRequestHandler):
    
        @pyjsonrpc.rpcmethod
        def get_mac(self, params):
            ret = {"status": {"code": 0, "msg": "success"}, "mac": ""}
            try:
                # params为 {"key1": "value1", "key2": "value2"}
                key1 = params.get("key1", "")
            except Exception as err:
                logger.error("get mac failed: %s", err)
                ret = {"status": {"code": -1, "msg": err}}
            return ret
    
        @pyjsonrpc.rpcmethod
        def get_server_ip(self, params):
            ret = {"status": {"code": 0, "msg": "success"}, "server_ip": ""}
            try:
                # params为 {"key1": "value1", "key2": "value2"}
                key1 = params.get("key1", "")
            except Exception:
                # traceback.format_exc()能获取到详细的错误打印栈
                logger.error("get server ip error, %s", traceback.format_exc())
                ret = {"status": {"code": -1, "msg": traceback.format_exc()}}
            return ret
    
        @pyjsonrpc.rpcmethod
        def get_file_name(self, params):
            ret = {"status": {"code": 0, "msg": "success"}, "get_file_name": ""}
            try:
                key1 = params.get("key1", "")
            except Exception:
                # traceback.format_exc()能获取到详细的错误打印栈
                logger.error("get file name error, %s", traceback.format_exc())
                ret = {"status": {"code": -1, "msg": traceback.format_exc()}}
            return ret
    
    
    def main(server_ip, port):
    
        # 线程HTTP-Server
        http_server = pyjsonrpc.ThreadingHttpServer(
            server_address=(server_ip, port),
            RequestHandlerClass=RequestHandler
        )
        http_server.serve_forever()
    
    
    if __name__ == '__main__':
        main('localhost', 8080)
    
  • 相关阅读:
    S5pv210 android VGA 1440*900 视频播放/3D 演示效果实拍视频
    毕业3年,工资从5k到20k的经历——真的还是假的啊?
    转载.WinCE6.0 Camera驱动整体结构
    半夜来认识一下S5PV210 的VBPDE和VFPDE
    微软的windows 8授权真的要这么贵?谁要?!
    基于S5PC100的FIMC的部分解释——一篇让我理解透彻2440和S5PV210 摄像头camera控制器的文章
    转.Buffer Management by the Camera Driver (Windows Embedded CE 6.0)
    微软?想干掉苹果,自己做平板,还想做手机,有优秀的合作伙伴诺基亚?简直是笑话,难怪鲍ceo 被评为最应该下台的CEO了
    魅族经过M8——》M9——》MX 已经走向国际?
    wince6.0 S5pv210 之Sate210 VGA 镜像1440*900@60HZ/1280*1024@70HZ分辨率测试镜像(南嵌电子科技作品)
  • 原文地址:https://www.cnblogs.com/guotianbao/p/12333654.html
Copyright © 2020-2023  润新知