def cache(self): api_url = HOST + '/api/Cache/List' header = { 'content-type': CONTENT_TYPE, 'Authorization': TOKEN, 'userinfo': USERINFO } from login.proto_pb.UserRequestPb_pb2 import UserRequestPb ur_body = UserRequestPb() ur_body.organizationID = '93a6f377-717d-4dc3-a2ae-ab6600b6b2ab' ur_body.observationDeptID = 'aa688ecb-9f0c-439c-bcd1-ab6600b6edd9' ur_body.currentPage = 1 ur_body.pageSize = 10 ur_body = ur_body.SerializeToString() res = self.client.request(method='POST', path=api_url, data=ur_body, headers=header, name='缓存接口') from login.proto_pb.PageResponsePb_pb2 import PageResponsePb rp_data = PageResponsePb() rp_data.ParseFromString(res.content) from google.protobuf.json_format import MessageToJson from login.proto_pb.CacheListResponsePb_pb2 import CacheListResponsePb rp_json = MessageToJson(rp_data) print(res.status_code, rp_json.encode('utf-8').decode("unicode_escape"))
def wait_shoot_list(): api_url = HOST + "/api/Technician/UnFinishList" body = OrderSearchRequestPb() body.observationDate = today_horizon2str() body.observationLocationIDArray = 'E3773228-3C86-4CAE-AF22-AB6600E618D6' body = body.SerializeToString() res = requests.request(method='POST', url=api_url, data=body, headers=header) # 解析结果 data = PageResponsePb() data.ParseFromString(res.content) # 结果转为json res_json = MessageToJson(data) res_dict = json.loads(res_json.encode('utf-8').decode("unicode_escape")) if 'isSuccess' in res_dict.keys() and 'data' in res_dict.keys(): if 'unFinishList' in res_dict['data'][0]: print(res.status_code, res_dict['data'][0]['unFinishList']) else: print(res.status_code, 'unFinishList:[]') else: print(res.status_code)
def _get_checkin_request_as_state(self) -> State: request = self._checkin_manager.get_latest_checkin_request() value = MessageToJson(request) state = State(type="checkin_request", deviceID=snowflake.snowflake(), value=value.encode('utf-8')) return state
def call_shoot(): api_url = HOST + "/api/Exam/Load" r_body = SimpleOrderRequestPb() r_body.orderID = OrderID # 从wait_shoot_list,获取 if r_body.orderID: mr_body = SimpleOrderMessageRequestPb() mr_body.order.CopyFrom(r_body) mr_body = mr_body.SerializeToString() res = requests.request(method='POST', url=api_url, data=mr_body, headers=header) print('RT: %ss' % res.elapsed.total_seconds()) # 解析结果 data = PageResponsePb() data.ParseFromString(res.content) # 结果转为json res_json = MessageToJson(data) res_dict = json.loads( res_json.encode('utf-8').decode("unicode_escape")) if 'isSuccess' in res_dict.keys() and 'data' in res_dict.keys(): if 'orderInfo' in res_dict['data'][0]: print(res.status_code, res_dict['data'][0]['orderInfo']) else: print(res.status_code, 'orderInfo:[]') else: print(res.status_code, res_dict) else: pass
def get_orderID(self): api_url = HOST + "/api/Technician/UnFinishList" from techin.proto_pb.OrderSearchRequestPb_pb2 import OrderSearchRequestPb body = OrderSearchRequestPb() body.observationDate = today_horizon2str() body.observationLocationIDArray = 'E3773228-3C86-4CAE-AF22-AB6600E618D6' body = body.SerializeToString() res = requests.request(method='POST', url=api_url, data=body, headers=header) # 解析结果 from techin.proto_pb.PageResponsePb_pb2 import PageResponsePb data = PageResponsePb() data.ParseFromString(res.content) # 结果转为json from techin.proto_pb.ObservationListResponsePb_pb2 import ObservationListResponsePb res_json = MessageToJson(data) res_dict = json.loads( res_json.encode('utf-8').decode("unicode_escape")) if 'isSuccess' in res_dict.keys() and 'data' in res_dict.keys(): if 'unFinishList' in res_dict['data'][0]: order_list = res_dict['data'][0]['unFinishList'] order_choice = random.choice(order_list) # 随机选择一个检查 return order_choice['orderID'] else: return '' else: return ''
def exam_end(self): api_url = HOST + "/api/Exam/Finish" from techin.proto_pb.OrderSearchRequestPb_pb2 import OrderSearchRequestPb body = OrderSearchRequestPb() body.orderID = self.orderID # 从呼叫列表获取 body = body.SerializeToString() res = self.client.request(method='POST', path=api_url, data=body, headers=header, name='检查完成') # 解析结果 from techin.proto_pb.PageResponsePb_pb2 import PageResponsePb data = PageResponsePb() data.ParseFromString(res.content) # 结果转为json from techin.proto_pb.FinishExamResponsePb_pb2 import FinishExamResponsePb res_json = MessageToJson(data) res_dict = json.loads( res_json.encode('utf-8').decode("unicode_escape")) if 'isSuccess' in res_dict.keys(): if res_dict['isSuccess']: print(res.status_code, '完成检查', res_dict['isSuccess']) else: print(res.status_code, '检查完成失败')
def call_shoot(self): api_url = HOST + "/api/Exam/Load" from techin.proto_pb.SimpleOrderRequestPb_pb2 import SimpleOrderRequestPb r_body = SimpleOrderRequestPb() r_body.orderID = self.orderID if r_body.orderID: from techin.proto_pb.SimpleOrderMessageRequestPb_pb2 import SimpleOrderMessageRequestPb mr_body = SimpleOrderMessageRequestPb() mr_body.order.CopyFrom(r_body) mr_body = mr_body.SerializeToString() res = self.client.request(method='POST', path=api_url, data=mr_body, headers=header, name='呼叫检查') # 解析结果 from techin.proto_pb.PageResponsePb_pb2 import PageResponsePb data = PageResponsePb() data.ParseFromString(res.content) from techin.proto_pb.ExamLoadResponsePb_pb2 import ExamLoadResponsePb res_json = MessageToJson(data) res_dict = json.loads( res_json.encode('utf-8').decode("unicode_escape")) if 'isSuccess' in res_dict.keys() and 'data' in res_dict.keys( ): if 'orderInfo' in res_dict['data'][0]: print(res.status_code, '呼叫成功', res_dict['data'][0]['orderInfo']) else: print(res.status_code, '呼叫失败') else: print(res.status_code, res_dict) else: print('当前没有检查可呼叫')
def hang_list(self): api_url = HOST + "/api/Technician/UnFinishList" from techin.proto_pb.OrderSearchRequestPb_pb2 import OrderSearchRequestPb body = OrderSearchRequestPb() body.observationDate = today_horizon2str() body.observationLocationIDArray = 'E3773228-3C86-4CAE-AF22-AB6600E618D6' body = body.SerializeToString() res = self.client.request(method='POST', path=api_url, data=body, headers=header, name='查询挂起列表') # 解析结果 from techin.proto_pb.PageResponsePb_pb2 import PageResponsePb data = PageResponsePb() data.ParseFromString(res.content) # 结果转为json from techin.proto_pb.ObservationListResponsePb_pb2 import ObservationListResponsePb res_json = MessageToJson(data) res_dict = json.loads( res_json.encode('utf-8').decode("unicode_escape")) if 'isSuccess' in res_dict.keys() and 'data' in res_dict.keys(): if 'hangUpList' in res_dict['data'][0]: print(res.status_code, res_dict['data'][0]['hangUpList']) else: print(res.status_code, '无查询数据') else: print(res.status_code, res_dict)
def cache(): api_url = HOST + '/api/Cache/List' header = { 'content-type': CONTENT_TYPE, 'Authorization': TOKEN, 'userInfo': REGINFO } from login.proto_pb.UserRequestPb_pb2 import UserRequestPb body = UserRequestPb() body.organizationID = REG['organizationID'] body.observationDeptID = REG['observationDeptID'] body.currentPage = 1 body.pageSize = 10 body = body.SerializeToString() res = requests.request(method='POST', url=api_url, data=body, headers=header) from login.proto_pb.PageResponsePb_pb2 import PageResponsePb data = PageResponsePb() data.ParseFromString(res.content) from google.protobuf.json_format import MessageToJson from login.proto_pb.CacheListResponsePb_pb2 import CacheListResponsePb rp_json = MessageToJson(data) print(res.status_code, rp_json.encode('utf-8').decode("unicode_escape"))
def finish_shoot_list(self): api_url = HOST + "/api/Technician/FinishList" from techin.proto_pb.OrderSearchRequestPb_pb2 import OrderSearchRequestPb body = OrderSearchRequestPb() # body.observationEndDate = '2020-03-04 00:00:00|2020-03-04 23:59:59' # 检查结束时间 body.observationEndDate = today_horizon2str() # 检查结束时间 body.observationLocationIDArray = 'E3773228-3C86-4CAE-AF22-AB6600E618D6' body = body.SerializeToString() res = self.client.request(method='POST', path=api_url, data=body, headers=header, name='查询完成列表') # 解析结果 from techin.proto_pb.PageResponsePb_pb2 import PageResponsePb data = PageResponsePb() data.ParseFromString(res.content) # 结果转为json from techin.proto_pb.ViOrderReportResponsePb_pb2 import ViOrderReportResponsePb res_json = MessageToJson(data) res_dict = json.loads( res_json.encode('utf-8').decode("unicode_escape")) if 'isSuccess' in res_dict.keys() and 'data' in res_dict.keys(): print(res.status_code, res_dict['data']) else: print(res.status_code, res_dict)
def refresh_wait_list(self): api_url = HOST + "/api/Technician/UnFinishList" from techin.proto_pb.OrderSearchRequestPb_pb2 import OrderSearchRequestPb body = OrderSearchRequestPb() body.observationDate = today_horizon2str() body.observationLocationIDArray = PROCINFO['observationLocationID'] body = body.SerializeToString() res = self.client.request(method='POST', path=api_url, data=body, headers=header, name='sr刷新摄片列表') from techin.proto_pb.PageResponsePb_pb2 import PageResponsePb data = PageResponsePb() data.ParseFromString(res.content) from techin.proto_pb.ObservationListResponsePb_pb2 import ObservationListResponsePb res_json = MessageToJson(data) res_dict = json.loads( res_json.encode('utf-8').decode("unicode_escape")) print('refresh_wait_list返回---------') if 'isSuccess' in res_dict.keys() and 'data' in res_dict.keys(): if 'unFinishList' in res_dict['data'][0]: print(res.status_code, res_dict['data'][0]['unFinishList']) else: print(res.status_code, '无查询数据') else: print(res.status_code, res_dict)
def report(self): # 报告查询 api_url = HOST + "/api/SimpleSearch/ReportPageList" header = { 'content-type': CONTENT_TYPE, 'Authorization': TOKEN, 'userInfo': USERINFO } from search.proto_pb.OrderSearchRequestPb_pb2 import OrderSearchRequestPb body = OrderSearchRequestPb() """对象入参赋值""" body.preliminaryEndDate = "2019-02-26|2020-02-25" # 报告书写时间 # body.auditEndDate = "2019-02-26|2020-02-25" # 审核时间 body.currentPage = 1 body.pageSize = 20 body = body.SerializeToString() # 将对象转化成字符串 """模拟客户端发出请求""" res = self.client.request(method='POST', path=api_url, data=body, headers=header, name='查询报告') """解析返回结果""" print(res.status_code) from search.proto_pb.PageResponsePb_pb2 import PageResponsePb data = PageResponsePb() # 创建返回参数pb对象 res_str = res.content # 获取返回的正文 data.ParseFromString(res_str) # 从返回正文解析(第一层解析) from google.protobuf.json_format import MessageToJson # 用于第二层解析特殊的类型 from search.proto_pb.ViOrderReportResponsePb_pb2 import ViOrderReportResponsePb # 导入返回参数中的相关pb res_json = MessageToJson(data) print(res_json.encode('utf-8').decode("unicode_escape")) # 宝
def PageList(self): api_url = HOST + "/api/ReportList/PageList" header = { 'content-type': 'application/octet-stream', # 头信息 'Authorization': TOKEN, 'userinfo': USERINFO2 } from report.proto_pb.ViOrderReportRequestPb_pb2 import ViOrderReportRequestPb ar_body = ViOrderReportRequestPb() """对象入参赋值""" ar_body.observationEndDate = '2020-02-20 00:00:00|2020-02-24 23:59:59' ar_body.currentPage = 1 ar_body.pageSize = 20 ar_body = ar_body.SerializeToString() # 将对象转化成字符串 """模拟客户端发出请求""" with self.client.request( method='POST', path=api_url, data=ar_body, headers=header, name='获取报告工作列表接口', timeout=5, catch_response=True ) as ar_res: # 通过使用catch_response参数和with语句,即使响应代码正确,也可以将请求标记为失败 """解析返回结果""" # print(ar_res) # print(ar_res.status_code) from report.proto_pb.PageResponsePb_pb2 import PageResponsePb ar_data = PageResponsePb() # 创建返回参数pb对象 res_str = ar_res.content # 获取返回的正文 # print(res_str) # print(ar_data) ar_data.ParseFromString(res_str) # 从返回正文解析(第一层解析) from google.protobuf.json_format import MessageToJson # 用于第二层解析特殊的类型 from report.proto_pb.ReportListResponsePb_pb2 import ReportListResponsePb # 导入返回参数中的相关pb ar_json = MessageToJson(ar_data) ar_dict = json.loads( ar_json.encode('utf-8').decode("unicode_escape"), strict=False) # 先处理unicode成中文,然后转化成字典 # print(ar_json) # print(ar_data) """校验结果是否正确""" if 'isSuccess' not in ar_dict.keys( ): # 判断返回结果中是否有'isSuccess',无,则一般是登录失败: ar_res.failure(ar_dict['resultDesc']) # 将接口测试结果置为失败 print(ar_dict['resultDesc']) elif ar_dict['isSuccess'] is False or ar_dict[ 'data'] is None: # 判断接口返回是否正确 ar_res.failure("Got wrong response") # 将接口测试结果置为失败 print("Got wrong response") else: print(ar_dict)
def produce_trip_updates(self): feed = gtfs_realtime_pb2.FeedMessage() response = requests.get(self.mta_api_url) feed.ParseFromString(response.content) for entity in feed.entity: if entity.HasField('trip_update'): update_json = MessageToJson(entity.trip_update) self.kafka_producer.produce(self.kafka_topic, update_json.encode('utf-8')) self.kafka_producer.flush()
def pack_pb_req(pb_req, proto_id, conn_id, serial_no=0): proto_fmt = SysConfig.get_proto_fmt() if proto_fmt == ProtoFMT.Json: req_json = MessageToJson(pb_req) ret, msg, req = _joint_head(proto_id, proto_fmt, len(req_json), req_json.encode(), conn_id, serial_no) return ret, msg, req elif proto_fmt == ProtoFMT.Protobuf: ret, msg, req = _joint_head(proto_id, proto_fmt, pb_req.ByteSize(), pb_req, conn_id, serial_no) return ret, msg, req else: error_str = ERROR_STR_PREFIX + 'unknown protocol format, %d' % proto_fmt return RET_ERROR, error_str, None
def login(self): api_url = HOST + "/api/Authorize/Validata" header = { 'content-type': CONTENT_TYPE, 'Authorization': TOKEN, 'userInfo': USERINFO } print(header) from login.proto_pb.AuthorizeRequestPb_pb2 import AuthorizeRequestPb ar_body = AuthorizeRequestPb() """对象入参赋值""" ar_body.accountName = 'zyp' # ar_body.userPassWord = '******' ar_body.userPassWord = md5('123456') ar_body.organizationID = '93a6f377-717d-4dc3-a2ae-ab6600b6b2ab' ar_body.observationDeptID = 'aa688ecb-9f0c-439c-bcd1-ab6600b6edd9' ar_body = ar_body.SerializeToString() # 将对象转化成字符串 """模拟客户端发出请求""" with self.client.request( method='POST', path=api_url, data=ar_body, headers=header, name='验证登录接口', catch_response=True ) as ar_res: # 通过使用catch_response参数和with语句,即使响应代码正确,也可以将请求标记为失败 """解析返回结果""" from login.proto_pb.PageResponsePb_pb2 import PageResponsePb ar_data = PageResponsePb() # 创建返回参数pb对象 res_str = ar_res.content # 获取返回的正文 ar_data.ParseFromString(res_str) # 从返回正文解析(第一层解析) from google.protobuf.json_format import MessageToJson # 用于第二层解析特殊的类型 from login.proto_pb.LoginUserInfoResponsePb_pb2 import LoginUserResponsePb # 导入返回参数中的相关pb ar_json = MessageToJson(ar_data) ar_dict = json.loads( ar_json.encode('utf-8').decode( "unicode_escape")) # 先处理unicode成中文,然后转化成字典 # print(ar_dict) """校验结果是否正确""" if 'isSuccess' not in ar_dict.keys( ): # 判断返回结果中是否有'isSuccess',无,则一般是登录失败: ar_res.failure(ar_dict['resultDesc']) # 将接口测试结果置为失败 print(ar_dict['resultDesc']) elif ar_dict['isSuccess'] is False or ar_dict[ 'data'] is None: # 判断接口返回是否正确 ar_res.failure("Got wrong response") # 将接口测试结果置为失败 print("Got wrong response") else: print(ar_res.status_code) print(ar_dict)
def PageList(): api_url = HOST + "/api/ReportList/PageList" #RIS接口地址 header = {'content-type': 'application/octet-stream', # 头信息 'Authorization': config.get_token(), 'userinfo': USERINFO} #导入protobuf入参文件 from ProtobufPy.ViOrderReportRequestPb_pb2 import ViOrderReportRequestPb ar_body = ViOrderReportRequestPb() """对象入参赋值""" ar_body.observationEndDate = '2021-05-08 00:00:00|2021-05-08 23:59:59' ar_body.resultStatus = '2090' ar_body.currentPage = 1 ar_body.pageSize = 20 ar_body = ar_body.SerializeToString() # 将对象转化成字符串 """模拟客户端发出请求""" with request(method='POST', url=api_url, data=ar_body, headers=header,timeout=5, ) as ar_res: """解析返回结果""" # print(ar_res.content) # print(ar_res.status_code) from ProtobufPy.PageResponsePb_pb2 import PageResponsePb ar_data = PageResponsePb() # 创建返回参数pb对象 res_str = ar_res.content # 获取返回的正文 ar_data.ParseFromString(res_str) # 从返回正文解析(第一层解析) # print(ar_data) # print("---------------------") from google.protobuf.json_format import MessageToJson # 用于第二层解析特殊的类型 from ProtobufPy.ReportListResponsePb_pb2 import ReportListResponsePb # 导入返回参数中的相关pb ar_json = MessageToJson(ar_data) # print(ar_data) ar_dict = json.loads(ar_json.encode('utf-8').decode("unicode_escape"), strict=False) # 先处理unicode成中文,然后转化成字典 # print(ar_dict) # 获取检查列表信息 orderlist = ar_dict['data'][0]['orderReport'] print(orderlist,type(orderlist)) for a in orderlist: print(a,type(a)) orderid = a['orderID'] reportid = Loading(orderid) Signature(orderid,reportid) print('orderid为{0},reportid为{1}的检查签名成功'.format(orderid,reportid))
def encode(cls, message: bytes, including_default_value_fields=False, preserving_proto_field_name=False, indent=None, sort_keys=False, use_integers_for_enums=False, descriptor_pool=None, float_precision=None) -> bytes: """PB转化为json字符串 .""" # preserveing_proto_field_name: 设置为 True 可以保留 protobuf # 的原有字段名,不然会自动转驼峰,如 request_id 会被自动转化为 requestId json_str = MessageToJson( message, including_default_value_fields=including_default_value_fields, preserving_proto_field_name=preserving_proto_field_name, indent=indent, sort_keys=sort_keys, use_integers_for_enums=use_integers_for_enums, descriptor_pool=descriptor_pool, float_precision=float_precision) return json_str.encode("utf8")
def TimeoutReport(self): api_url = HOST + "/api/TimeoutReport/PageList" header = { 'content-type': 'application/octet-stream', # 头信息 'Authorization': TOKEN, 'userinfo': USERINFO2 } from report.proto_pb.ReportConditionRequestPb_pb2 import ReportConditionRequestPb rcr_body = ReportConditionRequestPb() """对象入参赋值""" rcr_body.initiative = 1 rcr_body.pageSize = 20 rcr_body.pageIndex = 1 rcr_body.gapTime = 30 rcr_body.regDate = '2020-02-19 00:00:00|2020-02-25 23:59:59' rcr_body = rcr_body.SerializeToString() # 将对象转化成字符串 """模拟客户端发出请求""" with self.client.request( method='POST', path=api_url, data=rcr_body, headers=header, name='超时报告手动结果接口', catch_response=True ) as ar_res: # 通过使用catch_response参数和with语句,即使响应代码正确,也可以将请求标记为失败 """解析返回结果""" print(ar_res) from report.proto_pb.ViOrderReportResponsePb_pb2 import ViOrderReportResponsePb ar_data = ViOrderReportResponsePb() # 创建返回参数pb对象 res_str = ar_res.content # 获取返回的正文 print(res_str) print(ar_data) ar_data.ParseFromString(res_str) # 从返回正文解析(第一层解析) from google.protobuf.json_format import MessageToJson # 用于第二层解析特殊的类型 ar_json = MessageToJson(ar_data) ar_dict = json.loads( ar_json.encode('utf-8').decode("unicode_escape"), strict=False) # 先处理unicode成中文,然后转化成字典 print(ar_json) print(ar_data)
def finish_shoot_list(): api_url = HOST + "/api/Technician/FinishList" body = OrderSearchRequestPb() body.observationEndDate = '2020-03-04 00:00:00|2020-03-04 23:59:59' # 检查结束时间 body.observationLocationIDArray = 'E3773228-3C86-4CAE-AF22-AB6600E618D6' body = body.SerializeToString() res = requests.request(method='POST', url=api_url, data=body, headers=header) # 解析结果 data = PageResponsePb() data.ParseFromString(res.content) # 结果转为json res_json = MessageToJson(data) res_dict = json.loads(res_json.encode('utf-8').decode("unicode_escape")) if 'isSuccess' in res_dict.keys() and 'data' in res_dict.keys(): print(res.status_code, res_dict['data']) else: print(res.status_code, 'data:[]')
def shoot_finish(): api_url = HOST + "/api/Exam/Finish" body = OrderSearchRequestPb() body.orderID = OrderID # 从呼叫列表获取 body = body.SerializeToString() res = requests.request(method='POST', url=api_url, data=body, headers=header) print('RT: %ss' % res.elapsed.total_seconds()) # 解析结果 data = PageResponsePb() data.ParseFromString(res.content) # 结果转为json res_json = MessageToJson(data) res_dict = json.loads(res_json.encode('utf-8').decode("unicode_escape")) if 'isSuccess' in res_dict.keys(): if res_dict['isSuccess']: print(res.status_code, res_dict['isSuccess']) else: print(res.status_code, res_dict)
def validate(): api_url = HOST + "/api/Authorize/Validata" header = { 'content-type': CONTENT_TYPE, 'Authorization': TOKEN, 'userInfo': USERINFO } print(header) from login.proto_pb.AuthorizeRequestPb_pb2 import AuthorizeRequestPb body = AuthorizeRequestPb() # 声明入参对象 """对象入参赋值""" # print(REG) body.accountName = REG['accountName'] body.userPassWord = REG['userPassWord'] body.organizationID = '47D09C44-BCF7-40BB-AC88-AB7A009CB4B6' body.observationDeptID = '668F4A1C-537C-4C56-859E-AB7A009CCDE3' body = body.SerializeToString() # 将对象转化成字符串 res = requests.request(method='POST', url=api_url, data=body, headers=header) """解析返回结果""" from login.proto_pb.PageResponsePb_pb2 import PageResponsePb data = PageResponsePb() # 创建返回参数pb对象 res_str = res.content # 获取返回的正文 data.ParseFromString(res_str) # 从返回正文解析(第一层解析) from google.protobuf.json_format import MessageToJson # 用于第二层解析特殊的类型 from login.proto_pb.LoginUserInfoResponsePb_pb2 import LoginUserResponsePb # 导入返回参数中的相关pb res_json = MessageToJson(data) res_dict = json.loads(res_json.encode('utf-8').decode( "unicode_escape")) # 先处理unicode成中文,然后转化成字典 if 'isSuccess' in res_dict.keys() and 'data' in res_dict.keys(): print(res.status_code, res_dict['data'], '登录验证成功') return res_dict['data'][0] else: print(res.status_code, res_dict) return {}
def validate(self): api_url = HOST + "/api/Authorize/Validata" header = { 'content-type': CONTENT_TYPE, 'Authorization': TOKEN, 'userInfo': USERINFO } # print(USERINFO) from login.proto_pb.AuthorizeRequestPb_pb2 import AuthorizeRequestPb body = AuthorizeRequestPb() # 声明入参对象 """对象入参赋值""" body.accountName = REG['accountName'] body.userPassWord = REG['userPassWord'] body.organizationID = REG['organizationID'] body.observationDeptID = REG['observationDeptID'] body = body.SerializeToString() # 将对象转化成字符串 """发出请求""" res = self.client.request(method='POST', path=api_url, data=body, headers=header, name='验证登录接口') """解析返回结果""" from login.proto_pb.PageResponsePb_pb2 import PageResponsePb data = PageResponsePb() # 创建返回参数pb对象 res_str = res.content # 获取返回的正文 data.ParseFromString(res_str) # 从返回正文解析(第一层解析) from google.protobuf.json_format import MessageToJson # 用于第二层解析特殊的类型 from login.proto_pb.LoginUserInfoResponsePb_pb2 import LoginUserResponsePb # 导入返回参数中的相关pb res_json = MessageToJson(data) res_dict = json.loads( res_json.encode('utf-8').decode( "unicode_escape")) # 先处理unicode成中文,然后转化成字典 if 'isSuccess' in res_dict.keys() and 'data' in res_dict.keys(): print(res.status_code, res_dict['data'], '登录验证成功') # return res_dict['data'][0] else: print(res.status_code, res_dict)
def Loading(orderid): api_url = HOST + "/api/Report/Loading" header = {'content-type': 'application/octet-stream', # 头信息 'Authorization': config.get_token(), 'userinfo': USERINFO} from ProtobufPy.ReportRequestPb_pb2 import ReportRequestPb rr_body = ReportRequestPb() """对象入参赋值""" rr_body.orderID = orderid from ProtobufPy.OrderReportRequestPb_pb2 import OrderReportRequestPb orr_body = OrderReportRequestPb() orr_body.report.CopyFrom(rr_body) orr_body = orr_body.SerializeToString() # 将对象转化成字符串 """模拟客户端发出请求""" with request(method='POST', url=api_url, data=orr_body, headers=header,timeout=5, ) as ar_res: """解析返回结果""" from ProtobufPy.PageResponsePb_pb2 import PageResponsePb ar_data = PageResponsePb() # 创建返回参数pb对象 res_str = ar_res.content # 获取返回的正文 ar_data.ParseFromString(res_str) # print(ar_data) from google.protobuf.json_format import MessageToJson # 用于第二层解析特殊的类型 from ProtobufPy.ReportWriteListResponsePb_pb2 import ReportWriteListResponsePb ar_json = MessageToJson(ar_data) # print(ar_data) ar_dict = json.loads(ar_json.encode('utf-8').decode("unicode_escape"), strict=False) # 先处理unicode成中文,然后转化成字典 # print(ar_dict) report = ar_dict['data'][0]['report'] # print(report,type(report)) # print(report['reportID']) return report['reportID']
def start_shoot(self): api_url = HOST + "/api/Exam/Start" from techin.proto_pb.OrderSearchRequestPb_pb2 import OrderSearchRequestPb body = OrderSearchRequestPb() body.orderID = self.orderID body = body.SerializeToString() res = self.client.request(method='POST', path=api_url, data=body, headers=header, name='to开始摄片') from techin.proto_pb.PageResponsePb_pb2 import PageResponsePb data = PageResponsePb() data.ParseFromString(res.content) from techin.proto_pb.FinishExamResponsePb_pb2 import FinishExamResponsePb res_json = MessageToJson(data) res_dict = json.loads( res_json.encode('utf-8').decode("unicode_escape")) print('start_shoot返回---------') if 'isSuccess' in res_dict.keys(): if res_dict['isSuccess']: print(res.status_code, '检查开始成功', res_dict['isSuccess']) else: print(res.status_code, '检查开始失败')
def test_update(self, config_mock): """ Test that mconfig updates are handled correctly """ # Set up fixture data # Update will simulate gateway moving from # test_mconfig -> updated_mconfig test_mconfig = GatewayConfigs() updated_mconfig = GatewayConfigs() some_any = Any() magmad = MagmaD(log_level=1) some_any.Pack(magmad) test_mconfig.configs_by_key['magmad'].CopyFrom(some_any) updated_mconfig.configs_by_key['magmad'].CopyFrom(some_any) metricsd = MetricsD(log_level=2) some_any.Pack(metricsd) test_mconfig.configs_by_key['metricsd'].CopyFrom(some_any) metricsd = MetricsD(log_level=3) some_any.Pack(metricsd) updated_mconfig.configs_by_key['metricsd'].CopyFrom(some_any) # Set up mock dependencies config_mock.return_value = { 'magma_services': ['magmad', 'metricsd'], } @asyncio.coroutine def _mock_restart_services(): return "blah" @asyncio.coroutine def _mock_update_dynamic_services(): return "mockResponse" service_manager_mock = MagicMock() magmad_service_mock = MagicMock() mconfig_manager_mock = MconfigManagerImpl() load_mock = patch.object( mconfig_manager_mock, 'load_mconfig', MagicMock(return_value=test_mconfig), ) update_mock = patch.object( mconfig_manager_mock, 'update_stored_mconfig', Mock(), ) restart_service_mock = patch.object( service_manager_mock, 'restart_services', MagicMock(wraps=_mock_restart_services), ) update_dynamic_services_mock = patch.object( service_manager_mock, 'update_dynamic_services', MagicMock(wraps=_mock_update_dynamic_services), ) processed_updates_mock = patch('magma.magmad.events.processed_updates') class ServiceMconfigMock: def __init__(self, service, mconfig_struct): pass dynamic_services = [] mock_mcfg = patch('magma.magmad.config_manager.load_service_mconfig', MagicMock(wraps=ServiceMconfigMock)) with load_mock as loader,\ update_mock as updater, \ restart_service_mock as restarter,\ update_dynamic_services_mock as dynamic_services,\ mock_mcfg as mock_c,\ processed_updates_mock as processed_updates: loop = asyncio.new_event_loop() config_manager = ConfigManager( ['magmad', 'metricsd'], service_manager_mock, magmad_service_mock, mconfig_manager_mock, allow_unknown_fields=False, loop=loop, ) # Process an empty set of updates updates = [] config_manager.process_update(CONFIG_STREAM_NAME, updates, False) # No services should be updated or restarted due to empty updates restarter.assert_not_called() updater.assert_not_called() # Verify that config update restarts all services update_str = MessageToJson(updated_mconfig) updates = [ DataUpdate(value=''.encode('utf-8'), key='some key'), DataUpdate( value=update_str.encode('utf-8'), key='last key', ), ] config_manager.process_update(CONFIG_STREAM_NAME, updates, False) # Only metricsd config was updated, hence should be restarted self.assertEqual(loader.call_count, 1) restarter.assert_called_once_with(['metricsd']) updater.assert_called_once_with(update_str) configs_by_service = { 'magmad': updated_mconfig.configs_by_key['magmad'], 'metricsd': updated_mconfig.configs_by_key['metricsd'], } processed_updates.assert_called_once_with(configs_by_service) restarter.reset_mock() updater.reset_mock() processed_updates.reset_mock() updated_mconfig.configs_by_key['shared_mconfig'].CopyFrom(some_any) update_str = MessageToJson(updated_mconfig) updates = [ DataUpdate( value=update_str.encode('utf-8'), key='last key', ), ] config_manager.process_update(CONFIG_STREAM_NAME, updates, False) # shared config update should restart all services restarter.assert_called_once_with(['magmad', 'metricsd']) updater.assert_called_once_with(update_str) dynamic_services.assert_called_once_with([]) processed_updates.assert_called_once_with(configs_by_service) self.assertEqual(mock_c.call_count, 1) restarter.reset_mock() updater.reset_mock() processed_updates.reset_mock() dynamic_services.reset_mock()
def test_process_update(self, config_mock): """ Test an update with the following characteristics: - There is an unrecognized Any type - There is an unrecognized service - The magmad mconfig is updated and flips the new feature flag on - Another service has its config updated - Another service does not have its config updated """ # Set up fixtures old_mconfig, new_mconfig = self._get_old_and_new_mconfig_fixtures() new_mconfig_ser = MessageToJson(new_mconfig) # Add a config with a bad type to the new mconfig (MessageToJson errors # out if we include it in the proto message) new_mconfig_json_deser = json.loads(new_mconfig_ser) new_mconfig_json_deser['configs']['configsByKey']['oops'] = { '@type': 'type.googleapis.com/not.a.real.type', 'value': 'value', } new_mconfig_ser = json.dumps(new_mconfig_json_deser) updates = [ DataUpdate( value=new_mconfig_ser.encode(), key='mock', ), ] # Set up mock dependencies config_mock.return_value = ['metricsd'] @asyncio.coroutine def _mock_restart_services(): return 'mock' service_manager_mock = mock.Mock() service_manager_mock.restart_services = mock.MagicMock( wraps=_mock_restart_services, ) mconfig_manager_mock = mock.Mock() mconfig_manager_mock.load_mconfig.return_value = old_mconfig mconfig_manager_mock.update_stored_mconfig = mock.MagicMock() # use original impl of deserialize mconfig_manager_mock.deserialize_mconfig = mock.MagicMock( wraps=functools.partial( StreamedMconfigManager.deserialize_mconfig, mconfig_manager_mock, ), ) magma_service_mock = mock.Mock() magma_service_mock.reload_mconfig = mock.MagicMock() loop_mock = mock.MagicMock() # Run function, assert calls callback = StreamingMconfigCallback( ['metricsd'], service_manager_mock, magma_service_mock, mconfig_manager_mock, allow_unknown_fields=False, loop=loop_mock, ) callback.process_update(MCONFIG_VIEW_STREAM_NAME, updates, True) # magmad and metricsd configs changed but only metricsd should be # restarted (magmad won't restart for config change) service_manager_mock.restart_services.assert_called_once_with( ['metricsd'], ) # We should have written the whole serialized mconfig, bad keys and all mconfig_manager_mock.update_stored_mconfig.assert_called_once_with( new_mconfig_ser, ) # Should have reloaded magmad mconfigs to pick up change magma_service_mock.reload_mconfig.assert_called_once_with()
def test_update(self, config_mock): """ Test that mconfig updates are handled correctly """ # Set up fixture data # Update will simulate gateway moving from # test_mconfig -> updated_mconfig TestUpdate = namedtuple('TestUpdate', ['value', 'key']) test_mconfig = GatewayConfigs() updated_mconfig = GatewayConfigs() some_any = Any() magmad = MagmaD(log_level=1) some_any.Pack(magmad) test_mconfig.configs_by_key['magmad'].CopyFrom(some_any) updated_mconfig.configs_by_key['magmad'].CopyFrom(some_any) metricsd = MetricsD(log_level=2) some_any.Pack(metricsd) test_mconfig.configs_by_key['metricsd'].CopyFrom(some_any) metricsd = MetricsD(log_level=3) some_any.Pack(metricsd) updated_mconfig.configs_by_key['metricsd'].CopyFrom(some_any) # Set up mock dependencies config_mock.return_value = { 'magma_services': ['magmad', 'metricsd'], } @asyncio.coroutine def _mock_restart_services(): return "blah" service_manager_mock = MagicMock() magmad_service_mock = MagicMock() mconfig_manager_mock = MconfigManagerImpl() load_mock = patch.object( mconfig_manager_mock, 'load_mconfig', MagicMock(return_value=test_mconfig), ) update_mock = patch.object( mconfig_manager_mock, 'update_stored_mconfig', Mock(), ) restart_service_mock = patch.object( service_manager_mock, 'restart_services', MagicMock(wraps=_mock_restart_services), ) with load_mock as loader, update_mock as updater, \ restart_service_mock as restarter: loop = asyncio.new_event_loop() config_manager = ConfigManager( ['magmad', 'metricsd'], service_manager_mock, magmad_service_mock, mconfig_manager_mock, allow_unknown_fields=False, loop=loop, ) # Verify that config update restarts all services update_str = MessageToJson(updated_mconfig) updates = [ TestUpdate(value='', key='some key'), TestUpdate( value=update_str.encode('utf-8'), key='last key', ), ] config_manager.process_update(CONFIG_STREAM_NAME, updates, False) # Only metricsd config was updated, hence should be restarted loader.assert_called_once_with() restarter.assert_called_once_with(['metricsd']) updater.assert_called_once_with(update_str)
if srx != 0: pb_qso.contest.serial_received = str(srx) pb_qso.contest.serial_sent = safe_bytes(qso, 'stx_string') if pb_qso.contest.serial_sent == '': stx = safe_int(qso, 'stx') if stx != 0: pb_qso.contest.serial_sent = str(stx) pb_qso.contest.arrl_section = safe_bytes(qso, 'arrl_sect') pb_qso.contest.station_class = safe_bytes(qso, 'class') json = MessageToJson(pb_adi) print(json) num_fmt = "{:,}" json_size = len(json) gzip_json_size = len(gzip.compress(json.encode('utf-8'))) pb_size = len(pb_adi.SerializeToString()) gzip_pb_size = len(gzip.compress(pb_adi.SerializeToString())) print(tabulate([[ 'Input ADIF', num_fmt.format(adif_size), num_fmt.format(gzip_adif_size) ], [ 'JSON', num_fmt.format(json_size), num_fmt.format(gzip_json_size) ], ['Binary protobuf', num_fmt.format(pb_size), num_fmt.format(gzip_pb_size)]], headers=['Encoding', 'bytes', 'gzip']), file=sys.stderr)