def send_message(): db_pass_code = redis.hget('temp_pass_code', 'pass_code') db_time_left = redis.hget('temp_pass_code', 'time_left') ui_pass_code = request.form.get('ui_pass_code','') dst_num = request.form.get('dstNum','') msg_text = request.form.get('msgText','') dst_num_list = dst_num.split(',') if ui_pass_code and ui_pass_code == db_pass_code and db_time_left != "expired": _dst = "" for num in dst_num_list: print num _dst = _dst + "<" + num _dst = _dst.lstrip('<') cloud.send_message({'src':'<put_your_plivo_num>','dst': _dst,'text': msg_text}) response = make_response(render_template("codeused.html")) else: err_list = [] if not ui_pass_code or ui_pass_code == "": err_list.append("Pass code was not entered") elif ui_pass_code != db_pass_code: err_list.append("Passcode has expired!") else: err_list.append("Some error happened! Please report to sales and try again!") response = make_response(render_template("error.html" , err_list = err_list)) response.headers['Content-type'] = 'text/html' return response
def handle_message(event): user_profile = event.source.user_id if (event.message.text.find('choose:')!= -1): pass elif (event.message.text.find('detail')!= -1): sa_qid = redis.hget(user_profile,"sa_qid") sys_qid = redis.hget(user_profile,"sys_qid") dev_qid = redis.hget(user_profile,"dev_qid") #總答對題數 correct = redis.hget(user_profile,"result") #總回答題數 total = redis.hget(user_profile,"total") reply_list = [ TextSendMessage(text="各類回答紀錄\nsa:%s/100\ndeveloper:%s/100\nsysops:%s/100" % (sa_qid,sys_qid,dev_qid) ), TextSendMessage(text="總共答對 (%s)題\n總共回答 (%s)題" % (correct,total)) ] line_bot_api.reply_message( event.reply_token, reply_list ) else: line_bot_api.reply_message( event.reply_token, TextSendMessage(text="請使用下方功能選單\n或是輸入下方字串\ndetail"))
def prepare_sms_object(): no_of_sms = len(redis.keys('sms_*')) sms_keys = redis.keys('sms_*') sms_text = [] sms_time = [] sms_from = [] sms_to = [] sms_key = [] sms_replied = [] for key in sms_keys: sms_replied.append(redis.hget(key,'Replied')) sms_text.append(redis.hget(key,'Text')) sms_from.append(redis.hget(key,'From')) sms_to.append(redis.hget(key,'Plivo DID')) sms_time.append(redis.hget(key,'Time Received')) sms_key.append(key) sms_object = {'sms_from':sms_from, 'sms_to':sms_to, 'sms_text':sms_text, 'sms_time':sms_time, 'sms_key':sms_key, \ 'sms_replied':sms_replied} response = make_response(render_template("sms_dashboard.html", no_of_sms = no_of_sms-1,\ sms_object = sms_object)) response.headers['Content-type'] = 'text/html' return response
def start(message): id = message.chat.id redis.sadd('startmebot',id) if redis.hget("lang:{}".format(message.chat.id),"farsi"): bot.send_message(message.chat.id, 'زبان فعلی شما فارسی است🇮🇷\nمیتوانید با زدن دکمه ی زیر زبان خود را تغییر دهید🇺🇸', reply_markup=markupavfa) elif redis.hget("lang:{}".format(message.chat.id),"english"): bot.send_message(message.chat.id, 'Your language now is english🇺🇸\nYou can press down button to set persian language🇮🇷', reply_markup=markupaven) else: bot.send_message(message.chat.id, "زبان خود را انتخاب کنید👇\nSelect your language👇", reply_markup=markupstart)
def send(message): text = message.text.replace('/send ','') user = message.from_user.username name = message.from_user.first_name id = message.chat.id bot.send_message(is_sudo, "پیام جدید:\n\nمتن پیام:\n{}\n\nاز طرف:\nیوزرنیم: @{}\nایدی: {}\nاسم: {}".format(text, user, id, name)) if redis.hget("lang:{}".format(message.chat.id),"farsi"): bot.send_message(message.chat.id, "پیام یا انتقاد شما به ما ارسال شد و ما به سروقت به آن رسیدگی میکنیم😊", parse_mode="Markdown") elif redis.hget("lang:{}".format(message.chat.id),"english"): bot.send_message(message.chat.id, "Your message has been sent and we answer your message soon😊", parse_mode="Markdown")
def handle_post_message(event): #抓取user資料 user_profile = event.source.user_id #抓取postback action的data data = event.postback.data #用query string 解析data data=parse_qs(data) #出考題 if (data['type']==['question']): #每要求出題後,redis 的total增加一 redis.hincrby(user_profile,"total") if (data['question_type']==['sysops']): #每次出一題sysops增加一個sys_qid redis.hincrby(user_profile,"sys_qid") #從redis擷取出來 questionid = redis.hget(user_profile,"sys_qid") #回覆一組回覆串 line_bot_api.reply_message( event.reply_token, test('sysops',user_profile,questionid)) elif (data['question_type']==['develop']): redis.hincrby(user_profile,"dev_qid") questionid = redis.hget(user_profile,"dev_qid") line_bot_api.reply_message( event.reply_token, test('devlop',user_profile,questionid)) elif (data['question_type']==['sa']): redis.hincrby(user_profile,"sa_qid") questionid = redis.hget(user_profile,"sa_qid") line_bot_api.reply_message( event.reply_token, test('sa',user_profile,questionid)) #給按了答案的回覆 elif (data['type']==['answer']): if (data['question_type']==['sysops']): #進行回覆 line_bot_api.reply_message( event.reply_token, result('sysops',data,user_profile) ) elif (data['question_type']==['devlop']): #進行回覆 line_bot_api.reply_message( event.reply_token, result('devlop',data,user_profile) ) elif (data['question_type']==['sa']): line_bot_api.reply_message( event.reply_token, result('sa',data,user_profile) ) else: pass
def send_ui_reply(): sms_id = request.form.get('sms_id') sms_reply = request.form.get('action') print "Here I am: SMS Id - %s" % sms_id if ((sms_reply != "") and (not sms_id.startswith("del"))): src = redis.hget(sms_id,'From') plivo_did = redis.hget(sms_id,'Plivo DID') redis.hset(sms_id,"Replied",'y') redis.save() send_auto_response(src, plivo_did, sms_reply, 'True') elif ((sms_reply != "") and (sms_reply == "del")): redis.delete(sms_id[4:]) redis.save() return "OK"
def __getitem__(self, name): try: item = redis.hget(self.root_node[0], name) #strings if not item: item = redis.hget(self.root_node[1], name) #objects return RedisObject(self.type_name, root=item) else: return RedisPrimitive(self.type_name, self.hashcode, name) except Exception, e: try: index = int(name) item = redis.lrange(self.root_node[0], index, index)[0] if item.isdigit(): return int(item) return RedisObject(self.type_name, root=item) except Exception, e2: raise e2
def update(self,redis=None,pipeline=None): record = redis.hget(self.type,self.id) if record != None: record = json.loads(record) if record['title'] == self.title: return else: Index.remove(redis=redis,options={'id':self.id,'type':self.type,'title':record['title']}) self.save(redis=redis)
def get_pass_code(): gen_pass_code() db_time_left = redis.hget('temp_pass_code', 'time_left') if db_time_left == "1200.0": db_time_left = 1200 response = make_response(render_template("sendsms_admin.html", pass_code = gl_pass_code, time_left = db_time_left)) response.headers['Content-type'] = 'text/html' return response
def intermix (template, values): for value in values: for template_string in template: if template_string[0:2] == ':!': s = redis.hget ( value, template_string ) if s[0:2] == '::': yield render (s) else: yield s else: yield template_string
def admin(): global gl_pass_code pass_code = gl_pass_code db_pass_code = redis.hget('temp_pass_code', 'pass_code') db_time_left = redis.hget('temp_pass_code', 'time_left') db_time_set = redis.hget('temp_pass_code', 'time_set') print db_time_set time_left = "Not Yet Set" if db_pass_code and db_pass_code != "": pass_code = db_pass_code time_left = 1200 - int(time.time() - float(db_time_set)) if int(time_left) <= 0: print time_left redis.hset('temp_pass_code','time_left','expired') time_left = "Expired!" response = make_response(render_template("sendsms_admin.html", pass_code = pass_code, time_left = time_left)) response.headers['Content-type'] = 'text/html' return response
def learn_speaker(): check_post_param('id') user_id = request.form['id'] filename = user_id + next(tempfile._get_candidate_names()) + '.wav' request.files['wav_sample'].save(filename) user_training = None if redis.hexists(hm_data(user_id), USER_TRAINING): user_training = pickle.loads(redis.hget(hm_data(user_id), USER_TRAINING)) gmm, mfccs = predict.learn(filename, user_training) redis.hmset(hm_data(user_id), {USER_TRAINING: pickle.dumps(mfccs), USER_MODEL: pickle.dumps(gmm)}) os.remove(filename) return str(len(mfccs))
def clearPagingCache(): key='paging_token' redis=getRedis() pipe = redis.pipeline(transaction=True) now=time.time() tokens=redis.hkeys(key) for token in tokens: expireTime=int(redis.hget(key,token)) if expireTime<now: pipe.hdel(key,token) pipe.delete("tmp_paging_%s"%token) pipe.execute()
def remove(redis=None,options={}): if redis == None or 'type' not in options.keys() or \ 'id' not in options.keys(): return instance_type = options['type'] instance_id = options['id'] instance = redis.hget(instance_type,instance_id) if instance == None: return instance_title = json.loads(instance)['title'] redis.hdel(instance_type,instance_id) words = Index.split_words_for_index(instance_title) pipeline = redis.pipeline() for word in words: pipeline.srem(mk_sets_key(instance_type,word),instance_id) pipeline.delete(mk_score_key(instance_type,instance_id)) pipeline.srem(mk_sets_key(instance_type,instance_title),instance_id) pipeline.execute()
def get_matches_for_champion(players, champ, begin_time=datetime.utcnow() - timedelta(weeks=1), cache_ignore=False): if not cache_ignore: keys = redis.hkeys('player_matches') if keys: champ_keys = [x for x in keys if "_{}".format(champ['id']) in x] if len(champ_keys) > 10: matches = [] for k,v in redis.hscan_iter('player_matches', '*_{}'.format(champ['id'])): if v: matches += json.loads(v) return matches matches = [] last_week = int(time.mktime(begin_time.timetuple())) * 1000 for region in players.keys(): for player in players[region]: if not cache_ignore: this_player = redis.hget('player_matches', "{}_{}".format(player['id'], champ['id'])) if this_player: print u"CACHE HIT - {}'s {} matches".format(player['name'], champ['name']).encode("utf-8") matches += this_player continue print u"NETWORK - {}'s {} matches".format(player['name'], champ['name']).encode("utf-8") this_player = [] page = riot.get_match_list(player['id'], region=region, champion_ids=champ['id'], ranked_queues='TEAM_BUILDER_DRAFT_RANKED_5x5', begin_time=last_week) while 'matches' in page.keys() and page['matches']: for m in page['matches']: if m['champion'] != champ['id'] or m['queue'] == 'CUSTOM': continue this_player.append({'lane': m['lane'], 'matchId': m['matchId'], 'region': m['region'], 'role': m['role']}) if len(this_player) == page['totalGames']: break time.sleep(1) print u"NETWORK INNER - {}'s {} matches".format(player['name'], champ['name']).encode("utf-8") page = riot.get_match_list(player['id'], region=region, champion_ids=champ['id'], ranked_queues='TEAM_BUILDER_DRAFT_RANKED_5x5', begin_time=last_week, begin_index=page['endIndex']) if this_player: redis.hset('player_matches', "{}_{}".format(player['id'], champ['id']), json.dumps(this_player)) matches += this_player time.sleep(2) return matches
def share(twilio, redis, contact_nickname): contact_phone_number = redis.hget('contacts:' + contact_nickname, REDIS_HASH_PARAM_PHONE) response = {'twilio_sid': None, 'imgur_result': None} MAXIMUM_CHARACTERS = 140 body = request.form['from'] + ' sent you "' + request.form['title'] + '" (' + request.form['link'] + ') via Imgur (' + APP_LINK + ')' if contact_phone_number is not None: message = twilio.messages.create( body = body, to = contact_phone_number, from_ = TWILIO_NUMBER, ) response['twilio_sid'] = message.sid return jsonify(response)
############################################################### ### fish字段表更新 ### 新增1个字段 get_rate ### 2018-01-03 ############################################################### update = {'get_rate':''} for key in redis.keys(FISH_ROOM_TABLE%('*')): if 'set' in key or 'desc' in key: continue print 'set fish_table[%s]'%(key) pipe.hmset(key,update) goods_lists = redis.lrange(FISH_REWARD_ON_SHOP_LIST,0,-1) for goods in goods_lists: goods_type = redis.hget(FISH_REWARD_TABLE%(goods),'reward_type') pipe.lpush(FISH_REWARD_ON_SHOP_TYPE_LIST%(goods_type),goods) print 'set goods id index success....[%s]'%(goods_type) pipe.execute() ############################################################### ### exchange_table更新 ### 新增1个字段 exchange_type ### 2018-01-03 ############################################################### #otal = redis.llen(FISH_EXCHANGE_LIST) #xchange_ids = redis.lrange(FISH_EXCHANGE_LIST,0,-1) #xchange_id_keys = [FISH_EXCHANGE_TABLE%(exchange_id) for exchange_id in exchange_ids] #xchange_details = [exchange_detail for exchange_detail in redis.mget(exchange_id_keys)] #xchange_info = []
def is_schedule_status_open(self, msg): name = self.get_name_by_user_id(msg['user']['id']) status = redis.hget('schedule', name) status = True if status != '0' else False return status
def startmatch(message): if redis.hget(message.from_user.username, 'firstname') != '': bot.reply_to(message, "لطفا از موارد زیر انتخاب کنید", reply_markup=markup)
def handle_post_message(event): #抓取user資料 user_profile = event.source.user_id #抓取postback action的data data = event.postback.data #用query string 解析data data = parse_qs(data) #出考題 if (data['type'] == ['question']): #每要求出題後,redis 的total增加一 redis.hincrby(user_profile, "total") if (data['question_type'] == ['sysops']): #每次出一題sysops增加一個sys_qid redis.hincrby(user_profile, "sys_qid") #從redis擷取出來 questionid = redis.hget(user_profile, "sys_qid") #回覆一組回覆串 line_bot_api.reply_message( event.reply_token, test('sysops', user_profile, questionid)) elif (data['question_type'] == ['develop']): redis.hincrby(user_profile, "dev_qid") questionid = redis.hget(user_profile, "dev_qid") line_bot_api.reply_message( event.reply_token, test('devlop', user_profile, questionid)) elif (data['question_type'] == ['sa']): redis.hincrby(user_profile, "sa_qid") questionid = redis.hget(user_profile, "sa_qid") line_bot_api.reply_message(event.reply_token, test('sa', user_profile, questionid)) #給按了答案的回覆 elif (data['type'] == ['answer']): if (data['question_type'] == ['sysops']): #進行回覆 line_bot_api.reply_message( event.reply_token, answer_reply_list('sysops', data, user_profile)) elif (data['question_type'] == ['devlop']): #進行回覆 line_bot_api.reply_message( event.reply_token, answer_reply_list('devlop', data, user_profile)) elif (data['question_type'] == ['sa']): line_bot_api.reply_message( event.reply_token, answer_reply_list('sa', data, user_profile)) #給按下"AWS相關課程","網路工程課程","Linux課程",推播對應的flexBubble elif (data['type'] == ['AWS']): line_bot_api.reply_message(event.reply_token, flexBubbleSendMessage_AWS) elif (data['type'] == ['Internet']): line_bot_api.reply_message(event.reply_token, flexBubbleSendMessage_Internet) elif (data['type'] == ['Linux']): line_bot_api.reply_message(event.reply_token, flexBubbleSendMessage_Linux) #其他的pass else: pass
def save_matches_info(matches, champ): for m in matches: if "{}_{}_{}".format(m['region'], m['matchId'], champ['id']) in redis.hkeys('match_details'): continue match = redis.hget('match_infos', '{}_{}'.format(m['region'], m['matchId'])) if match: match = json.loads(match) else: match = riot.get_match(m['matchId'], region=m['region'].lower(), include_timeline=True) redis.hset('match_infos', '{}_{}'.format(m['region'], m['matchId']), json.dumps(match)) participantId = None participant = None for p in match['participants']: if p['championId'] == champ['id']: participant = p participantId = p['participantId'] break team = None for t in match['teams']: if t['teamId'] == participant['teamId']: team = t break won = team['winner'] stats = participant['stats'] kills, deaths, assists = stats['kills'], stats['deaths'], stats['assists'] first_blood = stats['firstBloodKill'] first_blood_assist = stats['firstBloodAssist'] tanks_friendly_team = 0 tanks_enemy_team = 0 lane_partner = None for p in match['participants']: friendly = p['teamId'] == participant['teamId'] tags = champion_data_by_id[p['championId']] if 'Tank' in tags: if friendly: tanks_friendly_team += 1 else: tanks_enemy_team += 1 if friendly: continue lane, role = None, None for t in p['timeline']: if 'lane' not in t or 'role' not in t: continue lane = t['lane'] role = t['role'] break if not (lane and role): continue raise ValueError('{}, {}'.format(lane, role)) if lane == m['lane'] and role == m['role']: lane_partner = p break if lane_partner: lane_partner_champ = champion_data_by_id[lane_partner['championId']] lane_partner_ad = lane_partner_champ['info']['attack'] > lane_partner['info']['magic'] else: lane_partner_ad = False items = [] for e in match['timeline']['frames']: if 'events' not in e.keys(): continue for ev in e['events']: if ev['eventType'] == 'ITEM_PURCHASED' and ev['participantId'] == participantId: # I don't care about biscuits or health potions or wards or trinkets if ev['itemId'] in (2003, 2010, 2043, 3340, 3341, 3361, 3362, 3363, 3364): continue item_info = item_data[ev['itemId']] # Don't care about base items, only upgrades if 'depth' not in item_info: continue # Don't care about level 3 boot upgrades if 'group' in item_info and 'boots' in item_info['group'].lower(): continue items.append(ev['itemId']) trimmed_items = [] for i, item_id in enumerate(items): item = item_data[item_id] prev_items = trimmed_items[:] if prev_items and 'from' in item: # if the last few items all build into this item, but they're # different parts of the tree (i.e. they don't upgrade into each other) # we shouldn't have the entire build path in the item list from_items = item['from'] last_item = prev_items.pop() while str(last_item) in from_items: if 'from' in item_data[last_item]: from_items += item_data[last_item]['from'] trimmed_items.remove(last_item) if not prev_items: break last_item = prev_items.pop() prev_items = trimmed_items[:] if prev_items and 'from' in item: # if the N-1th or N-2nd item is something that upgrades into this, skip it last_item = prev_items.pop() last_last_item = prev_items.pop() if prev_items else None if str(last_item) in item['from']: trimmed_items.remove(last_item) if str(last_last_item) in item['from']: trimmed_items.remove(last_last_item) trimmed_items.append(item_id) items = trimmed_items details = { 'championId': champ['id'], 'won': won, 'duration': match['matchDuration'], 'kills': kills, 'deaths': deaths, 'assists': assists, 'first_blood_kill': first_blood, 'first_blood_assist': first_blood_assist, 'lane_enemy_ad': lane_partner_ad, 'purchases': items } redis.hset('match_details', "{}_{}_{}".format(m['region'], m['matchId'], champ['id']), json.dumps(details)) print "Parsed and saved match {}\n".format(m['matchId']) pprint(details) print "-" * 30
#!/usr/bin/env python # -*- coding: utf-8 -*- import redis print((redis.__file__)) # 连接,可选不同数据库 redis = redis.Redis(host='localhost', port=6379, db=0) info = redis.info() print(info) keys = redis.keys("*") print(keys) keys = redis.hkeys("keys") print(keys) print((len(keys))) key__value = redis.hget("key", 'hashkey') print(key__value)
def __str__(self): return redis.hget(self.root_node[0], self.key)
def first_chunk(self): return redis.hget(self.redis_key, 'first_chunk')
print "eto_avg",eto_avg except: eto_avg = 0 try: rain_values = rain.values() rain_avg = ( reduce(lambda x, y: x+y, rain_values ))/len(rain_values) print "rain_avg",rain_avg except: rain_avg = 0 return { "eto":eto_avg,"rain":rain_avg }, json.dumps(eto),json.dumps(rain) if __name__ == "__main__": redis = redis.StrictRedis( host = 'localhost', port=6379, db = 0 ) data = redis.hget("FILES:SYS","eto_api_setup.json") json_data = base64.b64decode(data) #print "json_data",json_data access_data = json.loads(json_data ) eto = ETO(2400,access_data) print eto.integrate_eto_data() # imap_username = '******' # imap_password = '******' ## #try: #eto_data = calculate_site_eto( sites, alt, time.time() -24*3600 ) #print("made it here ",eto_data) #redis.set("YESTERDAY_ETO", eto_data["net_et"] )
# rabbitmq server 10.96.142.108 take care link remote host #datamigerate is the vhost credentials = pika.PlainCredentials('libin','abc123') parameters = pika.ConnectionParameters('10.96.142.108',5672,'datamigerate',credentials) mqconn = pika.BlockingConnection(parameters) channel = mqconn.channel() #declare queue channel.queue_declare(queue='cps1') # add message #look for message : rabbitmqctl list_queues -p datamigerate var =1 while var==1: batmsg=input("Enter a batname:") print (" process : %s"% (batmsg,)) if redis.hget('batdo',batmsg) is not None: batfile = redis.hget('batdo',batmsg).decode('utf-8') print(batfile) scope = redis.hget('batscope',batmsg).decode('utf-8') if str(scope)=='seg': AddbatMessage(batmsg,2) else: AddbatMessage(batmsg,1) else: print('%s is not exist'%(batfile,)) #AddbatMessage('exmm_order',2) mqconn.close()
if fileExtension == ".json": f = open(sys_files + i, "r") data = f.read() data = base64.b64encode(data) redis.hset("FILES:SYS", i, data) print "data", "done" #### #### INSURING THAT ETO_MANAGEMENT FLAG IS DEFINED #### temp = redis.get("ETO_MANAGE_FLAG") if temp == None: # not defined redis.set("ETO_MANAGE_FLAG", 1) temp = redis.hget("CONTROL_VARIABLES", "ETO_MANAGE_FLAG") if temp == None: # not defined redis.hset("CONTROL_VARIABLES", "ETO_MANAGE_FLAG", 1) #### #### Construct ETO Data QUEUES #### file_data = redis.hget("FILES:APP", "eto_site_setup.json") temp = base64.b64decode(file_data) eto_site_data = json.loads(temp) redis.delete("ETO_RESOURCE_A") for j in eto_site_data: redis.hset("ETO_RESOURCE_A", j["controller"] + "|" + str(j["pin"]), 0)
def render_hash_template(key): return '\n'.join ( intermix ( redis.lrange ( redis.hget ( key, 'template' ), 0, -1 ) , redis.lrange ( redis.hget ( key, 'values' ), 0, -1 ) ) )
def AddbatMessage(batname,scopetype=1): #get batname and expfilename from redis if redis.hget('batdo',batname) is not None: expFileName = str(redis.hget('batdo',batname).decode('utf-8')) expFilepath = str(redis.hget('batfilepath',batname).decode('utf-8')) if (scopetype==1): #get center db userid pwd dbname = str(redis.hget('dbname','10').decode('utf-8')) dbip = str(redis.hget('dbip','10').decode('utf-8')) dbuser = str(redis.hget('dbuser','10').decode('utf-8')) dbpwd = str(redis.hget('dbpwd','10').decode('utf-8')) messagebody=getMessagebody(batname,dbname,expFilepath+'\\'+expFileName,dbip,dbuser,dbpwd) channel.basic_publish(exchange='',routing_key='cps1',body=messagebody) print (' [x] process %s' %(messagebody,)) else : for key in redis.hkeys('dbip'): if (key.decode('utf-8') !='10'):# exclude 010 db skey =str(key.decode('utf-8')) dbname = str(redis.hget('dbname',skey).decode('utf-8')) dbip = str(redis.hget('dbip',skey).decode('utf-8')) dbuser= str(redis.hget('dbuser',skey).decode('utf-8')) dbpwd = str(redis.hget('dbpwd',skey).decode('utf-8')) messagebody=getMessagebody(batname,dbname,expFilepath+'\\'+expFileName+str(key.decode('utf-8')),dbip,dbuser,dbpwd) print('[x] process %s'%(getMessagebody(batname,dbname,expFileName+str(key.decode('utf-8')),dbip,dbuser,dbpwd),)) channel.basic_publish(exchange='',routing_key='cps1',body=messagebody) else : print(' %s is not exists'%(batname,))
def encryption_key(self): return redis.hget(self.redis_key, 'encryption_key')
def get_owner_username(self): return redis.hget(self.key(), 'owner')
def chunk_frame(self, chunk_id): return redis.hget(self.redis_key, 'chunk_frame_{}'.format(chunk_id))
def get_last_pid(self): pid = redis.hget(self.key(), 'last_player') if pid: return int(pid)
def __len__(self): return len(redis.hget(self.root_node[0], self.key))
import redis import os import sys rootpath='g:/mig/data/' redis = redis.Redis(host='10.96.142.109',port=6380,db=2) #get all batfile filelist = redis.hkeys('batdo') for item in filelist: filename = str(item.decode('utf-8')) if redis.hget('batfilepath',filename) is not None: batpath = rootpath+str(redis.hget('batfilepath',filename).decode('utf-8')) if os.path.exists(batpath)==False: os.makedirs(batpath) scope = redis.hget('batscope',filename) if scope is not None: if str(scope.decode('utf-8'))=='seg': batcmdA='copy ' batcmdB='copy ' expfile = str(redis.hget('batdo',filename).decode('utf-8')) batcmdFile = batpath+'/'+expfile+'.bat' for segitem in redis.smembers('segment'): segcode=str(segitem.decode('utf-8')) iSegcode = int(segcode[0]) if iSegcode>3: batcmdB=batcmdB+expfile+segcode+'.csv+' else: batcmdA=batcmdA+expfile+segcode+'.csv+' newfile=batpath+'/'+expfile+segcode+'.csv' if os.path.exists(newfile)==False: f=open(newfile,'w')
def get_state(self): return redis.hget(self.key(), 'state')
def Update(key,item,val,redis): d,lst = Query() if key in d.keys() and redis.hexists(key,item): old_val = redis.hget(key,item) redis.hset(key,item,val) r.publish(src[0],src[1])
def get_current_pid(self): pid = redis.hget(self.key(), 'current_player') return int(pid)
wall_id = wall_name redis.hset('bot:session:'+str(chat_id), 'wall_id', wall_id) bot.sendMessage(chat_id=chat_id, text="You are now connected to wall "+str(wall_name)) else: if not redis.hexists('bot:session:'+str(chat_id), 'wall_id'): print 'not associated with any wall' bot.sendMessage(chat_id=chat_id, text="You are not connected to any wall! To connect to a wall type: /wall WALL_NAME where WALL_NAME is the name you will find below the wall.") else: wall_id = redis.hget('bot:session:'+str(chat_id), 'wall_id') print 'user connected to wall: ', wall_id if wall_id != None: url = WALLED_SERVER + '/walls/'+str(wall_id)+'/posts' post = {'user': user, 'text': u.message.text } if len(u.message.photo) > 0: post['type'] = 'image' images = u.message['photo'] for im in images: print bot.getFile(im['file_id']) im = images[-1] #get the last image file_url = bot.getFile(im['file_id'])['file_path'] #, im['width'], im['height'] filename = file_url.split('/')[-1] r = requests.get(file_url, stream=True)
def sighup(message): if message.reply_to_message != None: if message.text == 'flow': doc = open('output.xlsx', 'rb') bot.send_document(message.chat.id, doc) elif len(message.text) != 11: msg = bot.reply_to( message, 'لطقا شماره همراه خود را به این صورت وارد کنید: \n ex:09xxxxxxxxx', reply_markup=mksighup) else: bot.send_message(message.chat.id, " لطفا شماره ملی خود را وارد کنید") sighuplist[message.from_user.username] = { 'firstname': '', 'lastname': '', 'meli': '', 'phonenumber': message.text, 'questionnumbers': [0], 'state': 'alive', 'point': 0, 'questionnum': 1, 'timer': time.time(), 'chat_id': message.chat.id } elif message.content_type == 'text': try: if message.text == 'flow': try: doc = open('output.xlsx', 'rb') bot.send_document(message.chat.id, doc) except: print("it is not possible") pass if sighuplist[message.from_user.username]['meli'] == '': sighuplist[message.from_user.username]['meli'] = message.text bot.reply_to(message, ":لطفا اسم کوچک خود را وارد کنید ") elif sighuplist[message.from_user.username]['firstname'] == '': sighuplist[ message.from_user.username]['firstname'] = message.text bot.reply_to( message, " :لطفا نام خانوادگی خود را وارد کنید {}".format( message.text)) elif sighuplist[message.from_user.username]['lastname'] == '': sighuplist[ message.from_user.username]['lastname'] = message.text bot.reply_to( message, " ثبت نام شما تکمیل شد {} {}".format( sighuplist[message.from_user.username]['firstname'], sighuplist[message.from_user.username]['lastname'])) bot.send_message(message.chat.id, "Please choose from this options", reply_markup=markup) redis.hset(message.from_user.username, 'lastname', sighuplist[message.from_user.username]['lastname']) redis.hset(message.from_user.username, 'firstname', sighuplist[message.from_user.username]['firstname']) redis.hset( message.from_user.username, 'phonenumber', sighuplist[message.from_user.username]['phonenumber']) redis.hset(message.from_user.username, 'meli', sighuplist[message.from_user.username]['meli']) redis.hset(message.from_user.username, 'state', sighuplist[message.from_user.username]['state']) redis.hset(message.from_user.username, 'point', sighuplist[message.from_user.username]['point']) redis.hset( message.from_user.username, 'questionnum', sighuplist[message.from_user.username]['questionnum']) redis.hset(message.from_user.username, 'chat_id', sighuplist[message.from_user.username]['chat_id']) redis.hset(message.from_user.username, 'timer', sighuplist[message.from_user.username]['timer']) else: if redis.hget(message.from_user.username, 'state') == 'finish': bot.send_message(message.chat.id, 'شما شانس خود را قبلا استفاده کرده اید') pass elif int(redis.hget(message.from_user.username, 'questionnum')) == 15 or int( redis.hget(message.from_user.username, 'questionnum')) > 15: bot.send_message( message.chat.id, emojize(':coffee:', use_aliases=True) + 'congratulation you have answered to all questions\nand your point is :{} \njust take rest and relax' .format( redis.hget(message.from_user.username, 'point').decode('utf-8')), reply_markup=markup) redis.hset(message.from_user.username, 'state', 'finish') del sighuplist[message.from_user.username] else: data2 = int( redis.hget(message.from_user.username, 'questionnum')) + 1 redis.hset(message.from_user.username, 'questionnum', data2) if message.text == u"\u2160": check(message, 0) getquestion(message) elif message.text == u"\u2161": check(message, 1) getquestion(message) elif message.text == u"\u2162": check(message, 2) getquestion(message) elif message.text == u"\u2163": check(message, 3) getquestion(message) elif message.text == u"\u2164": check(message, 4) getquestion(message) redis.hset(message.from_user.username, 'timer', time.time()) except: pass else: bot.reply_to(message, "wrong input!!!")
#if both articles are within the cutoff if to_ and from_: vrem = 'voted:' + from_article.split(':')[-1] vadd = 'voted:' + to_article.split(':')[-1] #verify user voting status on articles if redis.sismember(vrem, user) and not redis.sismember(vadd, user): #remove vote from from_article redis.srem(vrem, user) redis.zincrby(name='score:', value=from_article, amount=-1 * VOTE_SCORE) redis.hincrby(name=from_article, key='votes', amount=-1) #add vote to to_article redis.sadd(vadd, user) redis.zincrby(name='score:', value=to_article, amount=VOTE_SCORE) redis.hincrby(name=to_article, key='votes', amount=1) redis = redis.StrictRedis(host='localhost', port=6379, db=0) # user:3 up votes article:1 article_vote(redis, "user:3", "article:1") # user:3 up votes article:3 article_vote(redis, "user:3", "article:3") # user:2 switches their vote from article:8 to article:1 article_switch_vote(redis, "user:2", "article:8", "article:1") # Which article's score is between 10 and 20? article = redis.zrangebyscore("score:", 10, 20) article = article[0] print(redis.hget(article, "link"))
to_article_id = to_article.split(':')[-1] from_article_id = from_article.split(':')[-1] if redis.sismember( 'voted:' + from_article_id, user) and redis.sismember('voted:' + to_article_id, user) is False: if redis.smove('voted:' + from_article_id, 'voted:' + to_article_id, user): redis.zincrby(name='score:', value=to_article, amount=VOTE_SCORE) redis.hincrby(name=to_article, key='votes', amount=1) redis.zincrby(name='score:', value=from_article, amount=-VOTE_SCORE) redis.hincrby(name=from_article, key='votes', amount=-1) redis = redis.StrictRedis(host='localhost', port=6379, db=0) # user:3 up votes article:1 article_vote(redis, "user:3", "article:1") # user:3 up votes article:3 article_vote(redis, "user:3", "article:3") # user:2 switches their vote from article:8 to article:1 article_switch_vote(redis, "user:2", "article:8", "article:1") # Which article's score is between 10 and 20? # PRINT THE ARTICLE'S LINK TO STDOUT: article = redis.zrangebyscore('score:', 10, 20)[0] article_id = article.split(':')[-1] print(redis.hget(article, 'link'))
try: if not w in word_freq: filtered_words.append(unicode(w)) word_freq[w] = 1 else: word_freq[w] += 1 except: print 'something is wrong' pass tagged = st.tag(filtered_words) for (v, t) in tagged: if t in ['NN', 'NNS', 'NNP', 'NNPS']: idf = redis.hget('tfidf', stemmer.stem(v)) try: idf = float(idf) tf = int(word_freq[v]) score = tf * idf term_tuple = v, tf, idf, score, t output_file.write('%s, %s, %s,%s,%s' % term_tuple) output_file.write('\n') except: pass print 'total time :' + str(time.time() - start_time) else: print 'file found' + str(file)
def handle_message(event): user_profile = event.source.user_id # 由於在quick_reply的地方,在按鈕給了text針對按鈕的text不予回應 if (event.message.text.find('choose:') != -1): pass # 結合旋轉門選單中的"答題情形",會有文字detail的輸入,當符合detail字串時判斷成立 elif (event.message.text.find('detail') != -1): # sa回答到哪題 sa_qid = redis.hget(user_profile, "sa_qid") # sysops回答到哪題 sys_qid = redis.hget(user_profile, "sys_qid") # develop回答到哪題 dev_qid = redis.hget(user_profile, "dev_qid") # 總答對題數 correct = redis.hget(user_profile, "result") # 總回答題數 total = redis.hget(user_profile, "total") # 將上面的變數包裝起來 reply_list = [ TextSendMessage( text="各類回答紀錄\nsa:%s/100\ndeveloper:%s/100\nsysops:%s/100" % (sa_qid, dev_qid, sys_qid)), TextSendMessage(text="總共答對 (%s)題\n總共回答 (%s)題" % (correct, total)) ] # 回覆訊息 line_bot_api.reply_message(event.reply_token, reply_list) # 當用戶輸入AWS時判斷成立 elif (event.message.text.find('AWS') != -1): # 提供AWS白皮書網址及AWS培訓與認證網址 url1 = 'https://aws.amazon.com/tw/whitepapers/' url2 = 'https://aws.amazon.com/tw/training/' # 將上面的變數包裝起來 reply_list = [ TextSendMessage(text="AWS 白皮書連結:\n%s" % (url1)), TextSendMessage(text="AWS 培訓與認證:\n%s" % (url2)) ] # 回覆訊息 line_bot_api.reply_message(event.reply_token, reply_list) # 結合旋轉門選單中的"AWS相關課程",進到flexbubble選單,按下"李秉鴻老師簡介",會有文字"我想看李秉鴻老師的簡介"的輸入,當符合字串時判斷成立 elif (event.message.text.find('我想看李秉鴻老師的簡介') != -1): # 回覆訊息 line_bot_api.reply_message( event.reply_token, TextSendMessage( text= "李秉鴻老師:\n現為區塊鏈公司之創辦人,曾任北京軟體公司顧問、專案經理、系統架構師、新創企業之雲服務架構工程師、日商大數據暨雲服務後端工程師,擅長雲端應用開發與研究,並有多項雲服務專案開發經驗,獲有AWS Solution Architect - Associate及AWS SysOps Administarator - Associate等國際技術認證。熱愛成就他人,喜悅分享知識,將探索知識的過程轉化成淺白的技術講義做分享,熱愛挑戰問題,將大問題拆解成小問題,逐步帶領學生克服問題,每當看到學生成長,就覺得這個世界總是美好的。" )) # 結合旋轉門選單中的"Linux課程",進到flexbubble選單,按下"陳建村老師簡介",會有文字"我想看陳建村老師的簡介"的輸入,當符合字串時判斷成立 elif (event.message.text.find('我想看陳建村老師的簡介') != -1): # 回覆訊息 line_bot_api.reply_message( event.reply_token, TextSendMessage( text= "陳建村老師:\n自2010年起擔任公私立大學資管及資工系兼任講師、坊間培訓中心講師、線上遊戲公司系統顧問,兼具產業界技術實力及教學熱忱,教學設計生動活潑,授課採用心智圖(圖像記憶法)加速學員學習與記憶,關心學生學習狀況,因此深受學生喜愛,教學成果卓越,尤其SQL語法課程與OpenSource實作課程都是他的教學強項。" )) # 結合旋轉門選單中的"Linux課程",進到flexbubble選單,按下"黃智鑠老師簡介",會有文字"我想看黃智鑠老師的簡介"的輸入,當符合字串時判斷成立 elif (event.message.text.find('我想看黃智鑠老師的簡介') != -1): line_bot_api.reply_message( event.reply_token, TextSendMessage( text= "黃智鑠老師:\n超過10年Linux中小型企業Open Source解決方案的推動的實務經驗、與多年的教學經驗,專長Linux系統建置、管理、SNMP通訊協定、Linux網路管理,重要的專案與經歷如下:中壢資策會兼任講師、教育網路中心 伺服器管理、HP OpenView 網路系統管理系統 建置、中小企業open source solution建置/管理、IBM Tivoli 網路系統管理系統 建置!" )) # 結合旋轉門選單中的"網路工程課程",進到flexbubble選單,按下"戴致禮老師簡介",會有文字"我想看戴致禮老師的簡介"的輸入,當符合字串時判斷成立 elif (event.message.text.find('我想看戴致禮老師的簡介') != -1): line_bot_api.reply_message( event.reply_token, TextSendMessage( text= "戴致禮老師:\n具有20年網路工程經驗與16年Cisco講師教學經驗,重要的專案與經歷如下: ※美商SITA公司網路系統顧問─負責「中國北京首都機場T3航站樓網路工程建置案」與「台灣桃園機場骨幹網路升級擴建案」 ※中華電信訓練所─負責進階網路技術授課兼任講師,已陸續主持IPv6、Multicast、QoS、BGP、MPLS VPN、MPLS TE、IPSec VPN、SSL VPN等研討會 ※聚碩科技/智邦科技專長:Cisco大型跨國企業網路與Internet ISP骨幹網路的規劃與建置、各種領域Cisco網路的解決方案,包含:Data Center、Design、Routing & Switching、Security、Service Provider、Voice、Wireless" )) # 當用戶按下菜單的最右邊按鈕,會輸入more,符合字串more時判斷成立 elif (event.message.text.find('more') != -1): # 回覆訊息旋轉門選單 line_bot_api.reply_message( event.reply_token, TemplateSendMessage(alt_text="Tibame AWS 功能選單,為您服務", template=button_template_message)) #彩蛋,均在Line官方console做訊息設定,如要相同訊息,亦可寫在程式碼中 elif (event.message.text.find('乃元') != -1): pass elif (event.message.text.find('秉鴻') != -1): pass elif (event.message.text.find('Travis') != -1): pass elif (event.message.text.find('南風') != -1): pass elif (event.message.text.find('南風哥') != -1): pass elif (event.message.text.find('小天使') != -1): pass elif (event.message.text.find('輕鬆一下') != -1): pass elif (event.message.text.find('可惡') != -1): pass elif (event.message.text.find('我問號') != -1): pass elif (event.message.text.find('CC103') != -1): pass elif (event.message.text.find('CC104') != -1): pass # 收到不認識的訊息時,回覆原本的旋轉門菜單 else: line_bot_api.reply_message( event.reply_token, TemplateSendMessage(alt_text="Tibame AWS 功能選單,為您服務", template=button_template_message))
def get_color(self): return redis.hget(self.key(), 'color')
S3BUCKET = "fapomatic" client = boto3.client("s3") redis = redis.Redis(host="localhost", port=6379, db=0) res = client.list_objects_v2(Bucket=S3BUCKET) if res["IsTruncated"]: print("There's more") stored_files = set() for file in res["Contents"]: stored_files.add(file["Key"]) metadata_files = set() for key in redis.keys("*:data"): fname = redis.hget(key, "filename") metadata_files.add(fname.decode("utf8")) redis.close() # TODO: delete metadata in this case print("Has metadata, no stored file:") print(metadata_files - stored_files) # TODO: ask for metadata or delete stored file print("Is stored, no metadata") print(stored_files - metadata_files) sys.exit(0)
def exists(self): return redis.hget(self.key(), 'password_hash') is not None
def version(self): return redis.hget(self.redis_key, 'version')
def check_password(self, password): pw_hash = redis.hget(self.key(), 'password_hash') if not pw_hash: return False return check_password_hash(pw_hash, password)
def meta_data(self): return redis.hget(self.redis_key, 'meta_data')
def get_score(self): return int(redis.hget(self.key(), 'score'))
def key_frame(self, frame_id): return redis.hget(self.redis_key, 'key_frame_{}'.format(frame_id))
def get_name(self): return redis.hget(self.key(), 'name')
def last_chunk(self): return redis.hget(self.redis_key, 'last_chunk')
def cell_phone_number_exist(self, cell_phone_number): member_id = redis.hget(Constant.MEMBER_CELL_PHONE, cell_phone_number) return member_id
def submit_resource_usage(): try: response = {} t = datetime.utcnow() current_date_start = datetime(t.year, t.month, t.day, tzinfo=None) last_block_time = datetime.utcfromtimestamp( int(redis.get('last_block_time_seconds'))) previous_date_start = current_date_start - timedelta(days=1) previous_date_string = previous_date_start.strftime("%Y-%m-%d") previous_date_accounts = [ key[:-12] for key in redis.hkeys(previous_date_string) if key[-12:] == '-cpu-current' ] if last_block_time >= current_date_start: current_date_string = current_date_start.strftime("%Y-%m-%d") current_date_accounts = [ key[:-12] for key in redis.hkeys(current_date_string) if key[-12:] == '-cpu-current' ] logger.info( f'Collating todays records... {len(current_date_accounts)} accounts so far.' ) if len(previous_date_accounts) > 0: # if totals for previous date haven't been sent, calculate and send them now if redis.get('last_usage_total_sent') != previous_date_string: total_cpu_usage_us = 0 total_net_usage_words = 0 for account in previous_date_accounts: total_cpu_usage_us += int( redis.hget(previous_date_string, f'{account}-cpu-current')) total_net_usage_words += int( redis.hget(previous_date_string, f'{account}-net-current')) action = { "account": CONTRACT_ACCOUNT, "name": "settotal", "authorization": [{ "actor": SUBMISSION_ACCOUNT, "permission": SUBMISSION_PERMISSION, }], "data": { "source": SUBMISSION_ACCOUNT, "total_cpu_quantity": total_cpu_usage_us, "total_net_quantity": total_net_usage_words, "time": int(previous_date_start.timestamp()) } } logger.info( f'Submitting resource usage totals for {previous_date_string}...' ) tx = {'actions': [action]} logger.info(tx) # response = requests.post('http://eosjsserver:3000/push_transaction', json=tx, timeout=10).json() # logger.info(f'Transaction {response["transaction_id"]} successfully submitted!') logger.info( f'Transaction {response["transaction_id"]} successfully submitted!' ) redis.set('last_usage_total_sent', previous_date_string) time.sleep(5) # send ubsubmitted data actions = [] for account in previous_date_accounts[: MAX_ACCOUNTS_PER_SUBMISSION]: cpu_usage_us = redis.hget(previous_date_string, f'{account}-cpu-current') net_usage_words = redis.hget(previous_date_string, f'{account}-net-current') action = { "account": CONTRACT_ACCOUNT, "name": "adddistrib", "authorization": [{ "actor": SUBMISSION_ACCOUNT, "permission": SUBMISSION_PERMISSION, }], "data": { "source": SUBMISSION_ACCOUNT, "account": account, "cpu_quantity": cpu_usage_us, "net_quantity": net_usage_words, "time": int(previous_date_start.timestamp()) } } actions.append(action) logger.info( f'Submitting resource usage stats for {previous_date_string}...' ) tx = {'actions': actions} logger.info(tx) # response = requests.post('http://eosjsserver:3000/push_transaction', json=tx, timeout=10).json() # logger.info(f'Transaction {response["transaction_id"]} successfully submitted!') # remove data from -current once successfully sent for account in previous_date_accounts[: MAX_ACCOUNTS_PER_SUBMISSION]: redis.hdel(previous_date_string, f'{account}-cpu-current') redis.hdel(previous_date_string, f'{account}-net-current') # todo - handle if tx doesn't get included in immutable block? # if last block was yesterday, then aggregation is not finished, so don't submit if last_block_time < current_date_start: if len(previous_date_accounts) > 0: logger.info( f'Collating yesterdays records... {len(previous_date_accounts)} accounts so far.' ) except Exception as e: logger.error('Could not submit tx!') logger.error(response.get('error', traceback.format_exc()))
def test_execute(self): browers = self.browers config_dict = self.config_dict redis = self.redis jdbc = self.jdbc browers.implicitly_wait(5) browers.get(config_dict['login.url']) browers.find_element_by_xpath(config_dict['login.page.prompt']).click() browers.find_element_by_id(config_dict['login.username.id']).send_keys( config_dict['login.username']) browers.find_element_by_id(config_dict['login.pwd.id']).send_keys( config_dict['login.pwd']) # 获取cookie中的sid,并获取redis中的图片验证码 yunsid = get_yun_sid(browers) logging.info('>>>>>>>>>>获得yunsid:{}'.format(yunsid)) valied_code = redis.hget((config_dict['session.prefix'] + yunsid), 'VALID_CODE') logging.info('>>>>>>>>>>从redis中获取图片验证码为:{}'.format(valied_code)) browers.find_element_by_id(config_dict['login.valid.id']).send_keys( str(valied_code)) browers.find_element_by_xpath(config_dict['login.button']).click() # 读取用户输入的手机号 verify_phone = browers.find_element_by_id( config_dict['verify.phone.id']).get_attribute('value') logging.info('>>>>>>>>>>当前登录用户手机号码为:{}'.format(verify_phone)) # 发送验证码 browers.find_element_by_id(config_dict['verify.phone.sender']).click() logging.info('>>>>>>>>>>发送验证码中') verify_phone_code = '' i = 1 while i < 6 and verify_phone_code == '': sleep(2) logging.info('>>>>>>>>>>当前手机验证码为空,第{}次查询数据库……'.format(i)) cursor = jdbc.cursor() query_sql = str(config_dict['jdbc.query']).replace( '$equals$', '=').format(verify_phone) cursor.execute(query_sql) logging.info('>>>>>>>>>>查询数据库:{}'.format(query_sql)) jdbc_result = cursor.fetchall() logging.info('>>>>>>>>>>查询结果为:{}'.format(jdbc_result)) if type(jdbc_result) == list: for rows in jdbc_result: if rows[0] is not None: verify_phone_code = rows[0] break i += 1 if verify_phone_code == '': logging.info('>>>>>>>>>>未查询到有效手机验证码,系统自动退出!!!') return logging.info('>>>>>>>>>>短信验证码为:{}'.format(verify_phone_code)) browers.find_element_by_id( config_dict['yzm.input.id']).send_keys(verify_phone_code) browers.find_element_by_xpath(config_dict['yzm.button']).click() title = browers.title count = 1 while count < 4 and title != config_dict['success.title']: sleep(2) logging.info('>>>>>>>>>>还未登录成功,当前页面为:{},等待2秒'.format(title)) title = browers.title count += 1 if title != config_dict['success.title']: logging.info('>>>>>>>>>>登录失败,结束重试') else: logging.info('>>>>>>>>>>登录成功!!!') self.assertEqual(title, config_dict['success.title'])
# print 'hello' # print str(10*24*3600) print '1' redis = getRedisConn() print '2' # redis.delete('试试中文') # redis.set('试试中文','不试') # print redis.get('试试中文') # sessionPool = RedisSessionStore(redis_connection=redis) # session = Session(session_store = sessionPool, sessionid = 'baojianpin',logined=True) # session['test'] = 'goodmorning' # session['hello'] = 'word' # # print session['good'] print redis.hget('session:baojianpin', 'data') print redis.ttl("session:baojianpin") pass # ''' # 使用dict实现的简单sessionStore # 使用方式 # ''' # class SessionStore(object): # # def __init__(self): # self.db = getRedisConn2() # self.session_poll = self.db # # self.session_last = {} #'session的最后访问时间 # # t = threading.Thread(target=self.__remove_dead_session) #定时对sessionStore中没用的session进行删除
def get_username(self): return redis.hget(self.key(), 'user')