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)

pyjsonrpc的使用的更多相关文章

  1. pyjsonrpc模块使用

    pyjsonrpc模块的远程过程调用方法. # -*- coding:utf-8 -*- #!/usr/bin/env python2.7 # @Author : tianbao # @Contact ...

  2. week06 07 创建RPC SERVER 换个镜像安装下载

    RPC server 使用python类库 https://pypi.org/project/python-jsonrpc/ 和NPM 不一样 他没有global选项 他安装的就是全局的安装的类库叫p ...

  3. 从0到1:全面理解RPC远程调用

    上一篇关于 WSGI 的硬核长文,不知道有多少同学,能够从头看到尾的,不管你们有没有看得很过瘾,反正我是写得很爽,总有一种将一样知识吃透了的错觉. 今天我又给自己挖坑了,打算将 rpc 远程调用的知识 ...

随机推荐

  1. spring mvc框架入门

    目录 1.web框架分层 2.什么是springmvc 3.springmvc的优势 4.springmvc和struct的区别 (spring mvc框架入门 1.web框架分层 一般web框架可以 ...

  2. Codeforces 1117C Magic Ship (二分)

    题意: 船在一个坐标,目的地在一个坐标,每天会有一个风向将船刮一个单位,船也可以移动一个单位或不动,问最少几天可以到目的地 思路: 二分天数,对于第k天 可以分解成船先被吹了k天,到达坐标(x1+su ...

  3. 数据库连接池 —— Druid的简单使用

    Druid不仅是一个数据库连接池,还包含一个ProxyDriver.一系列内置的JDBC组件库.一个SQL Parser.支持所有JDBC兼容的数据库,包括Oracle.MySql.Derby.Pos ...

  4. javascript Date对象 js全部的 时间属性 和 方法

    Date() 返回当日的日期和时间. getTime() 返回 1970 年 1 月 1 日至今的毫秒数. getDate() 从 Date 对象返回一个月中的某一天 (1 ~ 31).天 getDa ...

  5. VFP获取 SQL Server 的数据表、触发器、存储过程、视图等脚本

    本文代码转载自红雨先生 *-----------------------------------------------* SqlServer 相关函数*----------------------- ...

  6. Digital Twin 数字孪生

    GE的一个NB视频:http://v.youku.com/v_show/id_XMjk0NTMzODIyNA==.html http://www.gongkong.com/news/201701/35 ...

  7. 2,Hadoop部署

    前期准备 (1)JAVA_HOME:因为Hadoop的配置文件中依赖 $JAVA_HOME.修改/etc/profile文件. (2)hostname:修改主机名,方便管理./etc/sysconfi ...

  8. Redis入门(介绍、搭建)——Windows、Centos环境

    一.介绍 Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cac ...

  9. 给test函数加个装饰器!

    import timedef timer(func): def deco(*args,**kwargs): start_time=time.time() func(*args,**kwargs) st ...

  10. webpack打包进行丑化压缩遇到(TypeError Cannot read property 'compilation' of undefined)问题

    今天再重新配置老项目node打包环境的时候遇到了一个问题. 在打包的时候报: TypeError: Cannot read property 'compilation' of undefined 错误 ...