from __future__ import print_function from grpc.experimental.gevent import init_gevent from app.main.util.utils import dict_group_by, debug_logging from app.main.util.utils import read_ini_config from app.main.util.redis_tools import RedisTools from pypinyin import lazy_pinyin import json import grpc from app.grpc import company_pb2_grpc as company_grpc from app.grpc import company_pb2 as company # read ini config file _ini_config = read_ini_config() init_gevent() class TestGrpc: channel = '' stub = '' def __init__(self): try: self.channel = grpc.insecure_channel(_ini_config['RPC_INSECURE_CHANNEL']) self.stub = company_grpc.CompanyStub(channel=self.channel) except Exception as ex: debug_logging(ex) def get_departments(self): """获取所有部门""" depts = self.stub.GetDepartments(request=company.Empty()) depts_list = [] for d in depts: pinyin = '' if d.name: pinyin = lazy_pinyin(d.name) depts_list.append({ 'id': d.id, 'name': d.name, 'parentid': d.pid, 'pinyin': pinyin }) redisTools = RedisTools() redisTools.set_redis('depts', json.dumps(depts_list, separators=(',', ':'))) redisTools.set_redis('depts_by_id', json.dumps(dict_group_by(depts_list, 'id'), separators=(',', ':'))) redisTools.set_redis('depts_by_parentid', json.dumps( dict_group_by(depts_list, 'parentid'), separators=(',', ':'))) def get_employees(self): """获取所有员工""" debug_logging("get_employees") stub = company_grpc.CompanyStub(channel=self.channel) employees = self.stub.GetEmployees(request=company.Empty()) e_list = [] for e in employees: pinyin = '' if e.name: pinyin = lazy_pinyin(e.name) e_list.append({ 'user_id': e.userid, 'username': e.name, 'department_id': list(e.departments), 'position': e.position, 'avatar': e.avatar, 'pinyin': pinyin }) redisTools = RedisTools() redisTools.set_redis('employee', json.dumps(e_list, separators=(',', ':'))) redisTools.set_redis('employee_by_user_id', json.dumps(dict_group_by(e_list, 'user_id'), separators=(',', ':'))) redisTools.set_redis('employee_by_department_id', json.dumps( dict_group_by(e_list, 'department_id', fieldinolist=False), separators=(',', ':'))) def get_login_user(self, user_id): """获取用户登录""" login_info = self.stub.GetLoginUser(request=company.UID(uid=user_id)) return login_info def get_user_info(self, user_id): """获取用户信息""" employee = self.stub.GetEmployeeByUID(request=company.UID(uid=user_id)) return employee
加入以下代码:
from grpc.experimental.gevent import init_gevent init_gevent()
def init_gevent(): """Patches gRPC's libraries to be compatible with gevent. This must be called AFTER the python standard lib has been patched, but BEFORE creating and gRPC objects. In order for progress to be made, the application must drive the event loop. """ _cygrpc.init_grpc_gevent()