pyjsonrpc的使用

2021-06-05 01:02

阅读:532

标签:pytho   oca   res   def   http   详细   ini   att   creat   

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("create 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("p2p start 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("p2p start error, %s", traceback.format_exc())
            ret = {"status": {"code": -1, "msg": traceback.format_exc()}}
        return ret


def main(server_ip, port):
    """main function"""

    # 线程HTTP-Server
    http_server = pyjsonrpc.ThreadingHttpServer(
        server_address=(server_ip, port),
        RequestHandlerClass=RequestHandler
    )
    http_server.serve_forever()


if __name__ == '__main__':
    main('localhost', 8080)

pyjsonrpc的使用

标签:pytho   oca   res   def   http   详细   ini   att   creat   

原文地址:https://www.cnblogs.com/guotianbao/p/12333654.html


评论


亲,登录后才可以留言!