def game() -> None: """ Método correspondente ao funcionamento do jogo. Ele gerá os participantes e sorteia as cartelas (80) para o jogo. A cada sorteio, a cartela será listada. Quando algum participante atingir 15 pontos, o método listará o parcipante e será finalizado. Se não houver vencedores, será listado. """ generate_cards(CARDS) generate_participants() print('Start of the game!!') numbers = redis.spop(CARDS, 80) for index, number in enumerate(numbers): number = int(number) print(f'Round {index+1}: {number}') round_winners = '' for i in range(1, 51): i = str(i) if redis.sismember(CARD + i, number): redis.zincrby(SCORES, 1, SCORE + i) round_winners += f'player {i} - score {redis.zscore("scores", SCORE + i)} | ' print('Round winners: ' + round_winners) winners = redis.zrangebyscore(SCORES, 15, 15) if winners: winners = [re.sub(r'\D', '', str(s)) for s in winners] print('Winning participant(s): ' + str(winners)) print('End of the game') return print('No winner...')
def run(): # Check if there's anything to do unix_now = time.mktime(datetime.datetime.now().timetuple()) todos = redis.zrangebyscore('gmail_bump_jobs', float('-inf'), unix_now) for serialized_todo in todos: # Run all tasks that are due todo = json.loads(serialized_todo) gmail.login_and_mail(todo.subject, todo.message_id)
def loop(): values = redis.zrangebyscore("delay-queue", 0, time.time(), start=0, num=1) if not values: time.sleep(1) # continue value = values[0] success = redis.zrem("delay-queue", value) if success: msg = json.loads(value) handle_msg(msg)
def loop9): while true: values = redis.zrangebyscore('delay-queue', 0, time.time(), start=1, num=1) if not values: time.sleep(1) continue value = values[0] success = redis.zrem('delay-queue', value) if success: msg = json.loads(value) handle_msg(msg)
def get_domains(): try: start = request.args.get("from", "-inf") end = request.args.get("to", "+inf") if start != "-inf" and end != "+inf": assert start.isdigit() and end.isdigit(), "start/end is non-digit" assert int(start) < int(end), ( "'from' is greater(equal) than 'to'") except Exception as e: return {"status": str(e)}, 400 try: assert is_db_connected, "no connection to redis db" assert redis.exists("visited_links"), ( "there is no such key in redis db") assert redis.zrangebyscore("visited_links", '-inf', '+inf'), ("sorted set is empty") res = redis.zrangebyscore("visited_links", start, end) res = [str(x, "utf-8").split(":")[-1] for x in res] res = list(set(res)) except Exception as e: return {"status": str(e)}, 500 return {"domains": res, "status": "ok"}
def loop(self): while True: # 返回score位于0到time.time()之间的value(默认从小到大排序), 返回索引位于start和num之间的集合,左闭右开 values = redis.zrangebyscore("delay-queue", 0, time.time(), start=0, num=1) if not values: time.sleep(1) continue value = values[0] success = redis.zrem("delay-queue", value) if success: msg = json.loads(value) handle_msg(msg)
def loop(): while True: # 最多取一条 values = redis.zrangebyscore("delay-queue", 0, time.time(), start=0, num=1) if not values: time.sleep(1) # 延迟队列空的,休息1s continue value = values[0] # 获取第一条,也只有一条 # Redis 的zrem是多线程多进程任务的关键,zrem的返回值决定当前实例有没有抢到任务,因为loop方法可能会被多个线程、多个进程调度,同一个任务可能会被多个进程线程抢到,通过zrem来决定唯一成功的线程. success = redis.zrem("delay-queue", value) # 从消息队列中移除该消息 if success: # 因为有多线程并发问题,最终只会有一个进程可以抢到消息 msg = json.loads(value) handle_msg(msg) # 需要对handle_msg进行异常捕获,避免因为个别任务处理问题导致循环异常退出
def test_abnormal_insert_order(): flush_memory() insert_order = [0, 2, 1] expected_results = [1.0, 2.0, 2.0] iteration_number = 0 for index in insert_order: email = EmailMessage(email_messages[index]) email.score = contrived_scores[index] email.score_calculated = True email.save() thread_recommendation = redis.zrangebyscore(recommendation_key, '-inf', '+inf', withscores=True) yield sure_convert, thread_recommendation.should.be.equal([ (email.thread.storage_key, expected_results[iteration_number]) ]) iteration_number += 1
def sorted_sets_redis(): import redis redis = redis.Redis(host='127.0.0.1', port=6379, db=0, charset="utf-8", decode_responses=True) print("-------------") print("SORTED_SETS") print("-------------") #zadd(name,mapping) zrangebyscore(name, min, max) redis.zadd("country.user", {392832938: 0, 34340923233: 1}) print(redis.zrangebyscore("country.user", 0, 1)) #delete all keys for key in redis.scan_iter("prefix:*"): redis.delete(key) #clean data redis.flushdb
#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"))
def article_switch_vote(redis, user, from_article, to_article): 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'))
def partitions(): redis = get_redis() start = request.args.get('start') end = request.args.get('end') key = current_app.config['KEY_PREFIX'] + 'PT' + str( current_app.config['PARTITION']) + 'M' first = redis.zrange(key, 0, 0) last = redis.zrevrange(key, 0, 0) prefix_len = len(current_app.config['KEY_PREFIX']) if len(first) == 0: return jsonify({}) first = first[0].decode('utf-8') first_datetime = first[prefix_len:first.rfind('PT')] last = last[0].decode('utf-8') last_datetime = last[prefix_len:last.rfind('PT')] partition_info = { 'duration': 'PT' + str(current_app.config['PARTITION']) + 'M', 'first': { 'at': first_datetime, 'partition': first }, 'last': { 'at': last_datetime, 'partition': last } } if start is None and end is None: return jsonify(partition_info) if start is None: start = first_datetime if start.find('T') < 0: start += 'T00:00:00' if end is not None and end.find('T') < 0: end += 'T23:59:59' start = datetime.fromisoformat(start) if end is None: timestamp = datetime.utcnow() partition_no = timestamp.minute // current_app.config['PARTITION'] end = datetime(timestamp.year, timestamp.month, timestamp.day, timestamp.hour, partition_no * current_app.config['PARTITION'], tzinfo=timestamp.tzinfo) else: end = datetime.fromisoformat(end) start_score = datetime_score(start) end_score = datetime_score(end) partitions = list( map(lambda v: v.decode('utf-8')[prefix_len:], redis.zrangebyscore(key, start_score, end_score))) partition_info['partitions'] = partitions return jsonify(partition_info)
def get_recommendations(recommendation_key): return redis.zrangebyscore(recommendation_key, '-inf', '+inf', withscores=True)
def cleanup(cls, redis): clients = redis.zrangebyscore(self.key("clients"), 0, cls.timestamp() - cls.TIMEOUT) for client in clients: cls(redis, id=client).disconnect()
# allows user to switch vote from one article to the next by modifying appropriate data structures article_id1 = from_article.split(':')[-1] article_id2 = to_article.split(':')[-1] if (redis.smove('voted:' + article_id1, 'voted:' + article_id2, user) == 1): redis.zincrby(name='score:', value=from_article, amount=-VOTE_SCORE) redis.hincrby(name=from_article, key='votes', amount=-1) redis.zincrby(name='score:', value=to_article, amount=VOTE_SCORE) redis.hincrby(name=to_article, key='votes', amount=1) pass 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: # HOMEWORK 2 Part II #finds article with required score and prints it out article = redis.zrangebyscore('score:', min=10, max=20, withscores=True) lima = str(article) article_id3 = lima[12] link = redis.hget(name='article:' + article_id3, key='link') print(link)