def __delitem__(self, key): deletable_object = self.__getitem__(key) if isinstance(deletable_object, RedisPrimitive): redis.hdel(self.root_node[0], key) else: clear_sub_nodes(self.type_name, deletable_object.hashcode) redis.hdel(self.root_node[1], key)
def edit(request, room): was_private = room.is_private if request.method == 'POST': form = RoomForm(request.POST, instance=room) if form.is_valid(): form.save(commit=False) room.save() if room.is_private and not was_private: redis = create_redis_connection() redis.publish('web_channel', 'room_private:' + str(room.id)) try: redis.hdel(redis_room_key(room.id), *redis.hkeys(redis_room_key(room.id))) except: pass return HttpResponseRedirect(request.get_full_path()) else: form = RoomForm(instance=room) response_data = { 'form' : form } if room.is_private: response_data['invited_users'] = room.invited.order_by('username').all() response_data['users'] = User.objects.exclude(pk=room.owner.id).exclude(rooms__pk=room.id).order_by('username').all() return response_data
def callback_inline(call): if call.message: if call.data == "farsi": redis.hset("lang:{}".format(call.message.chat.id),"farsi",True) redis.hdel("lang:{}".format(call.message.chat.id),"english") bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="زبان شما با موفقیت به فارسی انتخاب شد\n\nلطفا یکدام از دکمه های زیر را انتخاب کنید👇", reply_markup=markupstartfa) bot.answer_callback_query(callback_query_id=call.id,text="خوش آمدید😊") if call.message: if call.data == "english": redis.hset("lang:{}".format(call.message.chat.id),"english",True) redis.hdel("lang:{}".format(call.message.chat.id),"farsi") bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="Your language selected to english🇺🇸\nPlease select one of the button👇", reply_markup=markupstarten) bot.answer_callback_query(callback_query_id=call.id,text="Wellcome😊") if call.message: if call.data == "joke": f = open("joke.db") text = f.read() text1 = text.split(",") last = random.choice(text1) bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="{}\n\n[😂ربات جک😂](https://telegram.me/FunJokeBot)".format(last), reply_markup=markupjoke, parse_mode="Markdown") if call.message: if call.data == "chuk": url = "http://tambal.azurewebsites.net/joke/random" res = urllib.urlopen(url) parsed_json = json.loads(res.read()) joke = parsed_json['joke'] bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="{}\n\n[😂Joke bot😂](https://telegram.me/FunJokeBot)".format(joke), reply_markup=markupchuk, parse_mode="Markdown") if call.message: if call.data == "avazfa": bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="زبان خود را انتخاب کنید 👇\nSelect your language👇", reply_markup=markupstart) if call.message: if call.data == "avazen": bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="Select your language👇\nزبان خود را انتخاب کنید 👇", reply_markup=markupstart) if call.message: if call.data == "getjoke": f = open("joke.db") text = f.read() text1 = text.split(",") last = random.choice(text1) bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="{}\n\n\n[😂ربات جک😂](https://telegram.me/FunJokeBot)".format(last), reply_markup=markupjoke, parse_mode="Markdown") if call.message: if call.data == "sendjoke": bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="برای ارسال جک یا انتقاد یا پیشنهاد به ما طبق دستورالعمل زیر عمل کنید👇\n/send متن", reply_markup=markupback) if call.message: if call.data == "getjokeen": url = "http://tambal.azurewebsites.net/joke/random" res = urllib.urlopen(url) parsed_json = json.loads(res.read()) joke = parsed_json['joke'] bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="{}\n\n\n[😂Joke bot😂](https://telegram.me/FunJokeBot)".format(joke), reply_markup=markupchuk, parse_mode="Markdown") if call.message: if call.data == "sendjokeen": bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="For send us rate or joke please send👇\n/Send Text", reply_markup=markupbacken) if call.message: if call.data == "back": bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="به عقب برگشتید🔙\n\nلطفا یکدام از دکمه های زیر را انتخاب کنید👇", reply_markup=markupstartfa) if call.message: if call.data == "backen": bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="Come backed🔙\nPlease select one of the button👇", reply_markup=markupstarten)
def add_version_to_number(number): need_update = redis.hget('boardVersion', number + '_needIncr') if need_update is None: return number else: redis.hincrby('boardVersion', number) redis.hdel('boardVersion', number + '_needIncr') return number + '_' + redis.hget('boardVersion', number)
def requeue(task_description, channel, redis): queue_name = task_description["queue"] del task_description["queue"] count = task_description.get("requeue_count", 0) task_description["requeue_count"] = count + 1 task_queue = Queue(queue_name, channel) task_queue.send(task_description) redis.hdel("failed_tasks", task_description["id"])
def add(msg): if msg.left_chat_member: redis.hdel(msg.chat.id, msg.left_chat_member.id) elif msg.new_chat_members: for user in msg.new_chat_members: if 'username' in user and user['username'].lower().endswith("bot"): return else: redis.hincrby(msg.chat.id, msg.from_user.id, 1)
def remove_member(number, sourceId): if redis.scard(number) == 1: redis.srem(number, sourceId) redis.delete(number + '_member') else: redis.srem(number, sourceId) redis.hset(sourceId, 'current', '-') redis.hset(sourceId, 'voted', 'N') redis.hdel(sourceId, 'status')
def _requeue_failed_task(failed, channel, redis): description = failed['description'] queue_name = failed['queue'] count = description.get('requeue_count', 0) description['requeue_count'] = count + 1 body = json.dumps(description) msg = amqp.Message(body=body) channel.queue_declare(queue_name, durable=True, auto_delete=False) channel.basic_publish(msg, exchange="", routing_key=queue_name) redis.hdel(REDIS_KEY, description['id'])
def delete_rss(): del_rss = request.form['del_rss'] user = request.form['user'] redis.hdel(user, del_rss) print(user) print(del_rss) return jsonify(res='ok')
def clean_counter(redis): """ 清理计数器,保留最新的120个样本 :param redis: :return: """ # 为了平等地处理更新频率各不相同的多个计数器,程序需要记录清理操作执行的次数。 passes = 0 while 1: p = redis.pipeline(True) start = time.time() # 渐进地遍历所有已知的计数器 index = 0 while index < redis.zcard('test:known:'): # 取得被检擦计数器的数据 hash = redis.zrange('test:known:', index, index) index += 1 if not hash: break hash = hash[0] prec = int(hash.partition(":")[0]) # 因为清理程序每60秒就会循环一次,所以需要根据计数器的更新频率来判断是否真的有必要对计数器进行清理。 bprec = int(prec // 60) or 1 # 如果整个计数器在这次循环里不需要进行清理,那么检擦下一个计数器 if passes % bprec: continue hkey = 'test:count:' + hash # print hkey # 更具给定的精度以及需要b保留的样本数量,计算出我们需要保留什么时间之前的样本。 cutoff = time.time() - SAMPLE_COUNT * prec samples = map(int, redis.hkeys(hkey)) samples.sort() remove = bisect.bisect_right(samples, cutoff) if remove: print "===========================================" print hkey, samples[:remove] redis.hdel(hkey, *samples[:remove]) if remove == len(samples): try: # 尝试修改计数器散列之前对其进行监视 p.watch(hkey) if not p.hlen(hkey): p.multi() p.zrem('test:known:', hash) p.execute() # 在删除一个计数器的情况下,下次循环可以使用与本次循环相同的索引 index -= 1 else: p.unwatch() except WatchError: pass passes += 1 duration = min(int(time.time() - start) + 1, 60) print "sleep" time.sleep(max(60 - duration, 1))
def delete(request, room): redis = create_redis_connection() redis.publish('web_channel', 'room_deleted:' + str(room.id)) try: redis.hdel(redis_room_key(room.id), *redis.hkeys(redis_room_key(room.id))) except: pass room.delete() return HttpResponseRedirect(reverse('rooms.views.my_list'))
def delete_invite(request, room, user_id): if room.is_private: user = get_object_or_404(User, pk=user_id) redis = create_redis_connection() redis.publish('web_channel', 'kick_user_from_room:' + str(room.id) + ':' + str(user.id)) session_key = redis.get('session_key:' + str(user.id)) try: redis.hdel(redis_room_key(room.id), session_key) except: pass room.invited.remove(user) return HttpResponseRedirect(reverse('rooms.views.edit', args=[room.id]))
def delete(self, id): """ This function delete the label @param id: user id @return: delete label """ try: instance = self.request.user.id instance.delete() logger.info("Label Deleted successfully") redis.hdel(str(self.request.user.id) + "label", id) return Response("Label Deleted successfully", status=status.HTTP_200_OK) except: logger.error("Label not deleted, Please check again") return Response("Label not deleted, Please check again", status=status.HTTP_400_BAD_REQUEST)
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 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 delete(self, request, note_id): """ This function trash the note or if note is already in trashed then it deleted permanently @param request: userid @param note_id: note id of note @return: Delete the Note """ user = request.user try: note = Notes.objects.get(Q(pk=note_id) & Q(user_id=self.request.user.id)) redis.hdel(str(self.request.user.id) + "label", id) if note.is_trash: note.delete() cache.delete(str(user.id) + "note" + str(id)) return Response("Your note is Deleted permanently", status=status.HTTP_200_OK) else: note.is_trash = True note.save() return Response("Your note is Trashed", status=status.HTTP_200_OK) except Notes.DoesNotExist: logger.error("Note Not Found") return Response("Note Not found", status=status.HTTP_404_NOT_FOUND)
def view_queue(): # print(pickle.loads(redis.get('c_q'))) customer_queue = pickle.loads(redis.get('c_q')) currently_serving = pickle.loads(redis.get('c_s')) if request.method == 'POST': if 'uid' in session: new_customer = Customer(request.form.get('name'), request.form.get('party-num'), uid=session['uid']) head, count = customer_queue.find_by_uid_and_update( session['uid'], new_customer) # redis.hset('session', str(new_customer.uid), strftime("%X", localtime())) redis.hset('session', str(new_customer.uid), app.current_waiting_time[count - 1]) else: new_customer = Customer(request.form.get('name'), request.form.get('party-num')) print(request.form) customer_queue.append(new_customer) session['uid'] = new_customer.uid count = customer_queue.length() # redis.hset('session', str(new_customer.uid), strftime("%X", localtime())) redis.hset('session', str(new_customer.uid), app.current_waiting_time[count - 1]) redis.set('c_q', pickle.dumps(customer_queue)) return redirect('/queue') elif request.method == 'DELETE': if 'uid' in session: customer_queue.delete_by_uid(session['uid']) # redis.hset('session', session['uid'], 'n/a') redis.hdel('session', session['uid']) session.clear() redis.set('c_q', pickle.dumps(customer_queue)) return redirect('/queue') elif request.method == 'PUT': if 'uid' in session: target, count = customer_queue.find( lambda x: x.uid == session['uid']) if target: target.present = not target.present # new_customer = Customer(request.form.get('name'), request.form.get('party-num'), present=True, uid=session['uid']) # app.customer_queue.find_by_uid_and_update(session['uid'], new_customer) redis.set('c_q', pickle.dumps(customer_queue)) return redirect('/queue') else: print(session) if 'uid' in session: print(customer_queue) print(customer_queue.tail.data.uid) data, count = customer_queue.find_by_uid(session['uid']) print(data, count) if data: redis.hset('session', str(session['uid']), app.current_waiting_time[count - 1]) final_time = redis.hget('session', session['uid']) else: # session.clear() final_time = 'n/a' else: final_time = 'n/a' return render_template('index.html', queue=customer_queue, cur=currently_serving, final_time=final_time)
def callback_inline(call): if call.message: if call.data == "farsi": redis.hset("lang:{}".format(call.message.chat.id), "farsi", True) redis.hdel("lang:{}".format(call.message.chat.id), "english") bot.edit_message_text( chat_id=call.message.chat.id, message_id=call.message.message_id, text= "ط²ط¨ط§ظ† ط´ظ…ط§ ط¨ط§ ظ…ظˆظپظ‚غŒطھ ط¨ظ‡ ظپط§ط±ط³غŒ ط§ظ†طھط®ط§ط¨ ط´ط¯\n\nظ„ط·ظپط§ غŒع©ط¯ط§ظ… ط§ط² ط¯ع©ظ…ظ‡ ظ‡ط§غŒ ط²غŒط± ط±ط§ ط§ظ†طھط®ط§ط¨ ع©ظ†غŒط¯ًں‘‡", reply_markup=markupstartfa) bot.answer_callback_query(callback_query_id=call.id, text="ط®ظˆط´ ط¢ظ…ط¯غŒط¯ًںکٹ") if call.message: if call.data == "english": redis.hset("lang:{}".format(call.message.chat.id), "english", True) redis.hdel("lang:{}".format(call.message.chat.id), "farsi") bot.edit_message_text( chat_id=call.message.chat.id, message_id=call.message.message_id, text= "Your language selected to englishًں‡؛ًں‡¸\nPlease select one of the buttonًں‘‡", reply_markup=markupstarten) bot.answer_callback_query(callback_query_id=call.id, text="Wellcomeًںکٹ") if call.message: if call.data == "backfa": bot.edit_message_text( chat_id=call.message.chat.id, message_id=call.message.message_id, text= "ط¨ظ‡ ط¹ظ‚ط¨ ط¨ط±ع¯ط´طھغŒط¯ًں”™\n\nظ„ط·ظپط§ غŒع©ط¯ط§ظ… ط§ط² ط¯ع©ظ…ظ‡ ظ‡ط§غŒ ط²غŒط± ط±ط§ ط§ظ†طھط®ط§ط¨ ع©ظ†غŒط¯ًں‘‡", reply_markup=markupstartfa) bot.answer_callback_query(callback_query_id=call.id, text="ط¨ظ‡ ط¹ظ‚ط¨ ط¨ط±ع¯ط´طھغŒط¯ًں”™") if call.message: if call.data == "backen": bot.edit_message_text( chat_id=call.message.chat.id, message_id=call.message.message_id, text="Come backedًں”™\nPlease select one of the buttonًں‘‡", reply_markup=markupstarten) bot.answer_callback_query(callback_query_id=call.id, text="Come backedًں”™") if call.message: if call.data == "reload": bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="reload: [â–†____________]") bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="reload: [▆▆___________]") bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="reload: [▆▆▆__________]") bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="reload: [▆▆▆▆_________]") bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="reload: [▆▆▆▆▆________]") bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="reload: [▆▆▆▆▆▆_______]") bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="reload: [▆▆▆▆▆▆▆______]") bot.edit_message_text( chat_id=call.message.chat.id, message_id=call.message.message_id, text="reload: [▆▆▆▆▆▆▆▆_____]") bot.edit_message_text( chat_id=call.message.chat.id, message_id=call.message.message_id, text="reload: [▆▆▆▆▆▆▆▆▆____]") bot.edit_message_text( chat_id=call.message.chat.id, message_id=call.message.message_id, text="reload: [▆▆▆▆▆▆▆▆▆▆___]") bot.edit_message_text( chat_id=call.message.chat.id, message_id=call.message.message_id, text="reload: [▆▆▆▆▆▆▆▆▆▆▆__]") bot.edit_message_text( chat_id=call.message.chat.id, message_id=call.message.message_id, text="reload: [▆▆▆▆▆▆▆▆▆▆▆▆_]") bot.edit_message_text( chat_id=call.message.chat.id, message_id=call.message.message_id, text="reload: [▆▆▆▆▆▆▆▆▆▆▆▆▆]") bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="reloaded!", reply_markup=markupreload) if call.message: if call.data == "timefa": reqa = urllib2.Request('http://api.gpmod.ir/time/') openera = urllib2.build_opener() fa = openera.open(reqa) parsed_jsona = json.loads(fa.read()) FAtime = parsed_jsona['FAtime'] FAdate = parsed_jsona['FAdate'] bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="طھط§ط±غŒط®: {} \nط³ط§ط¹طھ: {}".format( FAdate, FAtime), reply_markup=markupredatefa) if call.message: if call.data == "timeen": reqa = urllib2.Request('http://api.gpmod.ir/time/') openera = urllib2.build_opener() fa = openera.open(reqa) parsed_jsona = json.loads(fa.read()) ENtime = parsed_jsona['ENtime'] ENdate = parsed_jsona['ENdate'] bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="date: {} \ntime: {}".format( ENdate, ENtime), reply_markup=markupredateen) if call.message: if call.data == "refa": reqa = urllib2.Request('http://api.gpmod.ir/time/') openera = urllib2.build_opener() fa = openera.open(reqa) parsed_jsona = json.loads(fa.read()) FAtime = parsed_jsona['FAtime'] FAdate = parsed_jsona['FAdate'] bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="طھط§ط±غŒط®: {} \nط³ط§ط¹طھ: {}".format( FAdate, FAtime), reply_markup=markupredatefa) if call.message: if call.data == "reen": reqa = urllib2.Request('http://api.gpmod.ir/time/') openera = urllib2.build_opener() fa = openera.open(reqa) parsed_jsona = json.loads(fa.read()) ENtime = parsed_jsona['ENtime'] ENdate = parsed_jsona['ENdate'] bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="date: {} \ntime: {}".format( ENdate, ENtime), reply_markup=markupredateen)
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 clear_fields(id: int, *args) -> bool: redis.hdel(id, *args) return True
def delete_todo(id: str): print(id) todos_container.delete_item(id, partition_key=id) redis.hdel("todos", id) return {"message": "deleted"}
for key in all_decoded_metablock_metadata: validation_blockchain = redis.hget("blocks:" + key, "flag") if (validation_blockchain.decode('utf-8') == "0"): continue else: already_checked = redis.hexists("blocks:" + key, "audit") if (already_checked == False): print("-- blocks:" + key + " : Not associated with an entry in the blockchain!") redis.delete("blocks:" + key) print("---- blocks:" + key + " deleted.") bad_entries = bad_entries + 1 else: # This metablock was already checked in the first way blockchain ==> redis # Delete audit field redis.hdel("blocks:" + key, "audit") print("-- blocks:" + key + " : already checked (Audit field deleted in Redis)") #Metadoc for key in all_decoded_metadoc_metadata: validation_blockchain = redis.hget("files:" + key, "flag") if (validation_blockchain.decode('utf-8') == "0"): continue else: already_checked = redis.hexists("files:" + key, "audit") if (already_checked == False): print("-- files:" + key + " : Not associated with an entry in the blockchain!") redis.delete("files:" + key) print("---- files:" + key + " deleted.")
compact_data = base64.b4encode(json_data) self.redis.hset(self.key, name, compact_data) def load_file(self, name): compact_data = self.redis.hget(self.key, name) data = json.loads(base64.b64decode(compact_data)) return data def delete_file(self, name): os.remove(self.path + name) if __name__ == "__main__": # delete APP FILES DATA if len(app_list) > 0: redis.hdel("FILES:APP", app_list) # delete SYS FILES DATA if len(sys_list) > 0: redis.hdel("FILES:SYS", sys_list) files = [f for f in listdir(app_files)] # load app files for i in files: fileName, fileExtension = os.path.splitext(i) if fileExtension == ".json": f = open(app_files + i, 'r') data = f.read()
def handle_text_message(event): text = event.message.text sourceId = getSourceId(event.source) matcher = re.match(r'^#(\d+) (.+)', text) if text == 'join': #メンバ集め number = str(redis.get('maxVoteKey')).encode('utf-8') join_mutex = Mutex(redis, JOIN_MUTEX_KEY_PREFIX + number) join_mutex.lock() redis.sadd(number, sourceId) redis.hset(number + '_member', redis.scard(number), sourceId) redis.hset(sourceId, 'current', number) if join_mutex.is_lock(): time.sleep(JOIN_MUTEX_TIMEOUT) push_all( number, TextSendMessage(text='投票No.' + str(number) + ' (参加者' + str(redis.scard(number)) + '人)の投票板です\uD83D\uDE04\n' + '5秒間投票をスタートするなら 投票開始≫ ボタンを押してね\uD83D\uDE03')) push_all(number, generate_planning_poker_message(number)) join_mutex.unlock() redis.incr('maxVoteKey') elif text == 'add': current = redis.hget(sourceId, 'current') if current != '-': remove_member(current, sourceId) line_bot_api.push_message( sourceId, TextSendMessage(text='参加したい投票No.を入力してください\uD83D\uDE03')) redis.hset(sourceId, 'status', 'number_wait') elif matcher is not None: number = matcher.group(1) value = matcher.group(2) current = redis.hget(sourceId, 'current').encode('utf-8') if current != number: line_bot_api.push_message( sourceId, TextSendMessage(text='投票板が古かった?もう一度お願いします!')) line_bot_api.push_message(sourceId, generate_planning_poker_message(current)) return if value == '11': #退出 resign_operation(number, sourceId) return status = redis.hget('status_' + number, 'status') if status is None: vote_mutex = Mutex(redis, VOTE_MUTEX_KEY_PREFIX + number) if value == '0': #開始 vote_mutex.lock() if vote_mutex.is_lock(): push_all( number, TextSendMessage( text='5秒間投票をはじめます\uD83D\uDD52名前をタップして投票どうぞ\u2755')) redis.hset('status_' + number, 'status', 'inprogress') time.sleep(2) push_all(number, TextSendMessage(text='あと3秒!')) time.sleep(3) push_all( number, TextSendMessage(text='-\uD83D\uDD52投票終了\uD83D\uDD52-')) vote_mutex.unlock() redis.delete('status_' + number) member_list = redis.smembers(number) for memberid in member_list: redis.hset(memberid, 'voted', 'N') push_result_message(number) #結果発表後の結果クリア redis.delete('res_' + number) refresh_board(number) return else: line_bot_api.push_message( sourceId, TextSendMessage(text='投票開始ボタンがまだ押されていないようです\uD83D\uDCA6')) else: if redis.hget(sourceId, 'voted') == 'Y': line_bot_api.push_message( sourceId, TextSendMessage(text='すでに投票済です・・結果集計まで待ってね\uD83D\uDE04')) return elif value == '0': line_bot_api.push_message( sourceId, TextSendMessage(text='もうはじまってるよ、誰かに投票して!\uD83D\uDE04')) elif value == '11': resign_operation(number, sourceId) else: #異常値処理省略 redis.hincrby('res_' + number, value) redis.hset(sourceId, 'voted', 'Y') else: current = redis.hget(sourceId, 'current') if current is not None and current != '-': display_name = getUtfName(line_bot_api.get_profile(sourceId)) push_all_except_me(current, sourceId, TextSendMessage(text=display_name + ':' + text)) elif redis.hget(sourceId, 'status') == 'number_wait': if text == '0': redis.hdel(sourceId, 'status') line_bot_api.push_message( sourceId, TextSendMessage( text='始めるときは参加!ボタンをみんなと一緒に押してね\uD83D\uDE04')) line_bot_api.push_message(sourceId, generateJoinButton()) elif redis.exists(text) == 1: redis.hdel(sourceId, 'status') redis.sadd(text, sourceId) redis.hset(sourceId, 'current', text) if redis.hget('status_' + text, 'status') is None: redis.hset(text + '_member', redis.scard(text), sourceId) push_all(text, TextSendMessage(text='メンバーが増えたので再度投票板を表示します')) push_all( text, TextSendMessage( text='投票No.' + str(text) + ' (参加者' + str(redis.scard(text)) + '人)の投票板です\uD83D\uDE04\n' + '5秒間投票をスタートするなら 投票開始≫ ボタンを押してね\uD83D\uDE03')) push_all(text, generate_planning_poker_message(text)) else: line_bot_api.push_message( sourceId, TextSendMessage( text= '見つからないです・・参加したい投票No.を再入力してね\uD83D\uDE22(初期画面に戻るなら 0 )' ))
compact_data = base64.b4encode(json_data) self.redis.hset(self.key, name, compact_data) def load_file(self, name): compact_data = self.redis.hget(self.key, name) data = json.loads(base64.b64decode(compact_data)) return data def delete_file(self, name): os.remove(self.path + name) if __name__ == "__main__": # delete APP FILES DATA if len(app_list) > 0: redis.hdel("FILES:APP", app_list) # delete SYS FILES DATA if len(sys_list) > 0: redis.hdel("FILES:SYS", sys_list) files = [f for f in listdir(app_files)] # load app files for i in files: fileName, fileExtension = os.path.splitext(i) if fileExtension == ".json": f = open(app_files + i, "r") data = f.read()
def hdel(self, name, key): redis = self._get_redis(name) return redis.hdel(name, key)
count += 1 except Exception: print u'更新题目出错,id:%s ' % item['id'] pipe.execute() print(u'更新题目完毕, %s / %s' % (count, len(QUESTION_BANK))) # 更新答题奖品 print u'更新答题奖品' redis.delete(ACTIVICE_QUESTION_REWARD_LIST) pipe = redis.pipeline() count = 0 for idx, item in enumerate(QUESTION_REDPACK_LIST): count += 1 tid = item['id'] curTime = datetime.now().strftime('%Y-%m-%d') redis.hdel(ACTIVICE_QUESTION_REWARD_COUNT % tid, curTime) try: pipe.hset(ACTIVICE_QUESTION_REWARD_LIST, tid, json.dumps(item)) pipe.hincrby(ACTIVICE_QUESTION_REWARD_COUNT % tid, curTime, 0) except Exception: print u'更新答题奖品出错' pipe.execute() print(u'更新答题奖品完毕, %s / %s' % (count, len(QUESTION_REDPACK_LIST))) # 更新问卷题库 print u'更新问卷数据' count = 0 number = SURVER_NUMBER if SURVER_COVER: redis.delete(ACTIVICE_SURVER_NUMBER_LIST % number) pipe = redis.pipeline()
def getInfo(drugId): # get priceMin url = 'https://www.yaofangwang.com/medicine-' + str(drugId) + '.html?sort=sprice&sorttype=asc' soup = getSoup(url) retailerCount = soup.select_one('#priceABtn b') if retailerCount != None: retailerCount = int(retailerCount.string) if retailerCount == 0: return else: return priceList = soup.select('#slist .slist li') priceMin = priceList[0].select_one('p.money').string.strip().lstrip('¥') stockPriceMin = priceList[0].select_one('.info .sreserve').string.strip() if retailerCount > 1: priceMin2 = priceList[1].select_one('p.money').string.strip().lstrip('¥') stockPriceMin2 = priceList[1].select_one('.info .sreserve').string.strip() else: priceMin2 = '' stockPriceMin2 = '' # get priceMax #url = 'https://www.yaofangwang.com/medicine-' + str(drugId) + '.html?sort=sprice&sorttype=desc' #soup = getSoup(url) #priceTag = soup.select_one('#slist .slist li p.money') #if priceTag == None: # priceMax = '' #else: # priceMax = priceTag.string.strip().lstrip('¥') priceMax = '' ourPrice = drugs[drugId].split(':')[0] approvalNum = drugs[drugId].split(':')[1] ourStock = drugs[drugId].split(':')[2] info = soup.select('div.maininfo div.info dd') name = info[0].string if info[2].div == None: spec = info[2].text.strip() else: spec = info[2].div.div.text.strip() form = info[3].string manufacturer = info[4].string #imgURL = 'https:' + soup.select_one('div.maininfo div.info dd img')['src'] imgURL = '' sql = "select drugId from drug" cursor.execute(sql) res = cursor.fetchall() alreadyHave = [] for i in res: alreadyHave.append(i['drugId']) if int(drugId) in alreadyHave: #print('Updating', drugId, '...') sql = f"update drug set approvalNum = '{approvalNum}', name = '{name}', spec = '{spec}', form = '{form}', manufacturer = '{manufacturer}', ourPrice = '{ourPrice}', ourStock = '{ourStock}', priceMax = '{priceMax}', priceMin = '{priceMin}', stockPriceMin = '{stockPriceMin}', priceMin2 = '{priceMin2}', stockPriceMin2 = '{stockPriceMin2}', imgURL = '{imgURL}', updateOn = CURRENT_TIMESTAMP where drugId = '{drugId}'" else: #print('Inserting', drugId, '...') sql = f"insert into drug (drugId, approvalNum, name, spec, form, manufacturer, ourPrice, ourStock, priceMax, priceMin, stockPriceMin, priceMin2, stockPriceMin2, imgURL) values ('{drugId}', '{approvalNum}', '{name}', '{spec}', '{form}', '{manufacturer}', '{ourPrice}', '{ourStock}', '{priceMax}', '{priceMin}', '{stockPriceMin}', '{priceMin2}', '{stockPriceMin2}', '{imgURL}')" try: cursor.execute(sql) redis.hdel(redisHash, drugId) # print(cursor.fetchall()) except: print('error when processing drugId:', drugId) conn.commit()
socket_keepalive=True) def convert_redis_index(result): decoded_list = [] for key in result: decoded_list.append(key.decode('utf-8')) return decoded_list # Get all keys in Redis all_metadata_metablock_entries = redis.zrange("block_index", 0, -1) all_decoded_metablock_metadata = convert_redis_index( all_metadata_metablock_entries) # Get metablock from Redis all_metadata_metadoc_entries = redis.zrange("file_index", 0, -1) all_decoded_metadoc_metadata = convert_redis_index( all_metadata_metadoc_entries) # Delete one field in each metadoc for key in all_decoded_metadoc_metadata: redis.hdel("files:" + key, "entangling_blocks") print("Metadoc: All entangling_blocks field deleted") # Delete one field in each mtablock for key in all_decoded_metablock_metadata: redis.hdel("blocks:" + key, "size") print("Metablock: All size field deleted")