def insert(cls, _dic): """ 插入Something... :param _dic: 新增的字典 :return: """ key_value_lst = [] for key, value in _dic.items(): # 普通字符串 if type(value) == str or type(value) == unicode: value = _mysql.escape_string(value) item = "'%s'" % value else: item = "%s" % value key_value_lst.append(item) sql = "insert into {db}.{tbl}({column_list}) values ({value_list})". \ format(db=cls.db_name, tbl=cls.table_name, column_list=','.join(["`%s`" % v for v in _dic.keys()]), value_list=','.join(key_value_lst)) logger.info("base_insert===> %s" % sql) if cls.db_name == db_name_config.DOCTOR_DB: ret = doctor_conn.execute_with_exception(sql) elif cls.db_name == db_name_config.DOCTOR_USER_DB: ret = doctor_user_conn.execute_with_exception(sql) elif cls.db_name == db_name_config.DOCTOR_QUESTION_DB: ret = doctor_question_conn.execute_with_exception(sql) else: logger.error("error db...") ret = None return ret
def _check_sid(self): """ 校验每一个请求的sid,后台服务,就是通过sid来控制整个app的生命账户的生命周期!! :return: """ # 检查接口是否允许空字符串的sid,如登录、注册、忘记密码等可以允许空字符串 if self.sid_control_level == constant.SID_CAN_BE_NULL: logger.info("sid can be null...") return True # 调试模式,可以不带sid if config.debug_mode == 1: try: logger.info("调试模式开启,不检查sid!") sid = self.common_param["sid"] sid_info = sid_manager.SidManager.sid2info(sid) if sid_info: self.uid = sid_info.userid # 这个是医生、用户的id,可能是游客id self.user_type = sid_info.user_type # 这个是用户类型,0-游客,1-用户,2-医生 else: self.uid = 0 self.user_type = 0 return True except Exception, ex: logger.error(ex, exc_info=1) self.ret_code = errcode.SID_NOT_CORRECT self.ret_msg = "common_param sid not correct..." logger.error("common_param sid not correct...") return False
def is_expired(self): now = getCurrentTimestamp(bit_type=10) expires = config.SID_ExpiresSeconds expires_time = self.timestamp + expires if now > expires_time: logger.info("过期: 当前 = %s, 过期时间 = %s " % (timestamp2datetime(now, bit_type=10)[0], timestamp2datetime(expires_time, bit_type=10)[0])) return True return False
def update(cls, dic, where_col='id', where_col_str=False): """ 更新Something... :param dic: 字典 :return: """ key_value_lst = [] for key, value in dic.items(): logger.info("%s=%s" % (key, value)) if key == where_col: continue # 普通字符串 if type(value) == str or type(value) == unicode: value = _mysql.escape_string(value) item = "%s='%s'" % (key, value) # 需要追加的int,比如 like_num: (1, True),那么是like_num = like_num + 1 elif type(value) == tuple and len(value) == 2: if value[1]: item = "%s=%s+%s" % (key, key, value[0]) else: item = "%s=%s" % (key, value[0]) # 普通int, 比如 del_flag: 1, 直接 def_flag = 1 else: item = "%s=%s" % (key, value) key_value_lst.append(item) sql = "update {db}.{tbl} set ".format(db=cls.db_name, tbl=cls.table_name) sql += ",".join(key_value_lst) # where 列默认是id where_value = dic[where_col] if where_col_str: sql += " where %s = '%s'" % (where_col, where_value) else: sql += ' where %s = %s' % (where_col, where_value) logger.info("base_update: %s" % sql) if cls.db_name == db_name_config.DOCTOR_DB: ret = doctor_conn.execute_with_exception(sql) elif cls.db_name == db_name_config.DOCTOR_USER_DB: ret = doctor_user_conn.execute_with_exception(sql) elif cls.db_name == db_name_config.DOCTOR_QUESTION_DB: ret = doctor_question_conn.execute_with_exception(sql) else: logger.error("error db...") ret = None return ret
def _try_write_cache(self): """ 尝试写返回数据到缓存中... :return: """ # 如果redis挂了,则直接返回False if not redis_conn.writeable(): return False key, expire_seconds = self._construct_cache_key() if key: logger.info("设置redis,key=%s, 过期时间=%ss" % (key, expire_seconds)) redis_conn.set(key, pickle.dumps(self.ret_data)) redis_conn.expire(key, expire_seconds) return True
def _get_pool(self, redis_cfg): conn_key = "%s:%s#%s" % (redis_cfg.get('host'), redis_cfg.get('port'), redis_cfg.get('db', 0)) print ">>>>> redis get pool, conn_key", conn_key cur_pool = self.__class__.rcfg_2_pool.get(conn_key, None) if cur_pool: logger.info("got redis connection_pool by %s!", conn_key) return cur_pool cur_pool = redis.ConnectionPool(host=redis_cfg.get('host'), port=redis_cfg.get('port'), db=redis_cfg.get('db', 0)) self.__class__.rcfg_2_pool[conn_key] = cur_pool logger.info("create redis connection_pool for %s.", conn_key) print ">>>>> create redis connection_pool for", conn_key return cur_pool
def _check_sid(self): """ 校验每一个请求的sid,后台服务,就是通过sid来控制整个app的生命账户的生命周期!! :return: """ # 检查是否携带sid,即使不需要也要传个空字符串 if config.debug_mode == 1: logger.info("调试模式开启,不检查sid!") return True try: sid = self.common_param["sid"] except KeyError, _: self.ret_code = errcode.SID_NOT_CARRY self.ret_msg = "common_param without sid..." logger.error("common_param without sid...") return False
def post_action_transaction(self): if not self.check_input_arguments(["address", "private_key", "amount" ]): return self._response(error_msg.PARAMS_ERROR) try: key = Key(self._input.get("private_key")) transaction_id = key.send( [(str(self._input.get("address")), self._input.get("amount"), "satoshi")], fee=80, ) logger.info("create transaction {}".format(transaction_id)) return self._response(data=transaction_id) except Exception as e: logger.error("create transaction error {}".format(e)) self._msg = str(e) self._ret = 1 return self._response()
def _response(self, ret_msg=None, data=None): if not ret_msg is None: self._ret, self._msg = ret_msg if not data is None: self._data = data self._resp_json = json.dumps({ "ret": self._ret, "msg": self._msg, "data": self._data }) logger.info("finish %s, ip: %s, url: %s, " "method: %s, headers: %s, body: %s, cookie: %s " "resp: %s. handle time: %s ms" % (self.__class__.__name__, self._request.remote_addr, self._request.url, self._request.method, self._request.headers, self._request.body.decode("utf-8"), self._request.cookies, self._resp_json, (time.time() - self.__start_time) * 1000)) return response.text(self._resp_json, content_type="application/json")
def is_available(self, t): '''传入:Terminal t, 判断SID是否有效''' if not self.version or not self.cuid or not self.device_type or not self.timestamp or self.userid < 1: return False if "android" == self.device_type: if t.IMEI != self.cuid: logger.info("[安卓]: t.IMEI = %s 不等于 cuid = %s" % (t.IMEI, self.cuid)) return False elif "apple" == self.device_type: if t.ADID != self.cuid: logger.info("[苹果]: t.ADID = %s, 不等于 = %s" % (t.ADID, self.cuid)) return False if self.is_expired(): return False return True
def _try_read_cache(self): """ 尝试从缓存获取数据 :return: """ # 如果redis挂了,则直接返回False if not redis_conn.readable(): return False cache_key, expire_seconds = self._construct_cache_key() if cache_key: cache_str = redis_conn.get(cache_key) if cache_str: logger.info("走缓存, key=%s" % cache_key) self.ret_code = errcode.NO_ERROR self.ret_msg = "ok." self.ret_data = pickle.loads(cache_str) return True return False
def sid2info(cls, sid): """ SID ==> INFO对象 "%s|%s|%s|%s|%s|%s" % ( self.user_type, self.userid, self.version, self.timestamp, self.device_type, self.cuid) :param sid: :return: """ try: if not sid: logger.info("sid -> info: sid is null.") return None if config.SID_ENCRYPT_KEY: # 加密 sid = base64.b64decode(sid) sid = MyDESCryptUtil.decrypt(sid) values = sid.split('|') if len(values) < 6: logger.info("sid -> info: sid trans error...") return None sid_info = SidInfo(*values) if sid_info.is_expired(): logger.info("SID=%s 过期" % sid_info.to_string()) return None return sid_info except Exception, ex: logger.error("sid -> info失败:%s" % str(ex), exc_info=1) logger.error(sid) return None
# 检查是否携带sid,即使不需要也要传个空字符串 if config.debug_mode == 1: logger.info("调试模式开启,不检查sid!") return True try: sid = self.common_param["sid"] except KeyError, _: self.ret_code = errcode.SID_NOT_CARRY self.ret_msg = "common_param without sid..." logger.error("common_param without sid...") return False # 检查接口是否允许空字符串的sid,如登录、注册、忘记密码等可以允许空字符串 if self.sid_control_level == constant.SID_CAN_BE_NULL: logger.info("sid can be null...") return True return True def _parse_and_check_parameters(self): """ 1、解析参数 -> self.para_map中。 2、检验参数是否正确?是否必传的参数没有传? :return: True, False """ body = json.loads(request.data) for key, default_value in self.expected_para.iteritems(): value = body.get(key, default_value)
return self.is_w_working def validate_conn(self): try: r_connecting = self.r.ping() self.is_r_working = r_connecting except Exception, ex: self.is_r_working = False logger.error("redis r connect error:%s", str(ex)) try: w_connecting = self.w.ping() self.is_w_working = w_connecting except Exception, ex: self.is_w_working = False logger.error("redis w connect error:%s", str(ex)) logger.info("redis read conn:%s, redis write conn:%s", self.is_r_working, self.is_w_working) def check_r_conn(self): try: r_connecting = self.r.ping() self.is_r_working = r_connecting except Exception, ex: self.is_r_working = False logger.error("redis r connect error:%s", str(ex)) def expire(self, name, t): try: return self.w.expire(name, t) except Exception, ex: self.is_w_working = False logger.error("redis w connect error:%s", str(ex))