def test_dict2xml(self): """ 测试Dict转XML @return: None """ dict_data = utils.xml_to_dict(self.xml_string) xml_data = utils.dict_to_xml(dict_data) self.assertEqual(xml_data, self.xml_string.replace('\n', '').replace(' ', ''))
def test_xml2dict(self): """ 测试XML转Dict @return: None """ dict_data = utils.xml_to_dict(self.xml_string) self.assertIsInstance(dict_data, collections.OrderedDict) self.assertIn('ToUserName', dict_data) self.assertIn('FromUserName', dict_data) self.assertIn('CreateTime', dict_data) self.assertIn('MsgType', dict_data) self.assertIn('Content', dict_data) self.assertIn('MsgId', dict_data) self.assertIn('AgentID', dict_data)
def do_reply(self): """ 根据消息类型调用对应的回调函数进行回复 @return: 回复的消息, 按照微信接口加密 """ req_msg_sig = flask.request.args.get('msg_signature', '') timestamp = flask.request.args.get('timestamp', '') nonce = flask.request.args.get('nonce', '') req_data = flask.request.data ret, xml_str = self.wxcpt.DecryptMsg(req_data, req_msg_sig, timestamp, nonce) if ret == 0: param_dict = utils.xml_to_dict(xml_str) msg_type = param_dict.get("MsgType", '') if msg_type in self.callback_funcs: callback_func = self.callback_funcs[msg_type] if callback_func: # call the callback function and get return message (dict) res_dict = callback_func(copy.deepcopy(param_dict)) default_params = { 'MsgType': param_dict['MsgType'], 'CreateTime': int(time.time()) } for key, val in default_params.items(): if not res_dict.get(key, None): res_dict[key] = val res_dict['ToUserName'] = param_dict['FromUserName'] res_dict['FromUserName'] = param_dict['ToUserName'] xml_data = utils.dict_to_xml(res_dict) ret_val, encrypted_data = \ self.wxcpt.EncryptMsg(xml_data, nonce, timestamp) if ret_val == 0: self.logger.info('replied a message to %s' % res_dict.get('ToUserName', 'null')) return flask.Response(encrypted_data, mimetype='text/xml') # 如果没有正确走完这个流程, 就记录日志返回错误 self.logger.error('request failed with request data: %r' % req_data) # if decryption failed or all other reasons, return 400 bad request code flask.abort(400)