예제 #1
0
def createhotel():
  if not request.json or not 'displayname' in request.json or not 'id' in request.json:
    abort(400)
 
  hotel = {
    'id': request.json['id'],
    'displayname': request.json['displayname'],
    'acname': request.json['acname'],    
    'image': request.json.get('image', ''),
    'latitude': request.json.get('latitude', 0),
    'longitude': request.json.get('longitude', 0),
    'thirdpartyrating': request.json.get('thirdpartyrating', 0)
  }

  hotelname = hotel['acname']
  for l in range(1, len(hotelname)):
    hotelfragment = hotelname[0:l]
    redis.zadd('hotelfragments', 0, hotelfragment)
  
  hotelwithid = hotelname + '%H-' + str(hotel['id']) + '%'
  redis.zadd('hotelfragments', 0, hotelwithid)  
  
  hotelkey = 'H-' + str(hotel['id'])
  redis.execute_command('geoadd', 'hotels', '%f' % hotel['longitude'], '%f' % hotel['latitude'], hotelkey)
  redis.delete(hotelkey)

  redis.rpush(hotelkey, hotel['id'])
  redis.rpush(hotelkey, hotel['displayname'])
  redis.rpush(hotelkey, hotel['acname'])
  redis.rpush(hotelkey, hotel['image'])
  redis.rpush(hotelkey, hotel['latitude'])
  redis.rpush(hotelkey, hotel['longitude'])  
  redis.rpush(hotelkey, hotel['thirdpartyrating']) 
  
  return jsonify({ 'hotel': hotel }), 201 
예제 #2
0
def createlocation():
    if not request.json or not 'displayname' in request.json or not 'id' in request.json:
        abort(400)

    location = {
        'id': request.json['id'],
        'displayname': request.json['displayname'],
        'acname': request.json['acname'],
        'icon': request.json.get('icon', ''),
        'latitude': request.json.get('latitude', 0),
        'longitude': request.json.get('longitude', 0)
    }

    locationname = location['acname']
    for l in range(1, len(locationname)):
        locationfragment = locationname[0:l]
        redis.zadd('locationfragments', 0, locationfragment)

    locationwithid = locationname + '%L-' + str(location['id']) + '%'
    redis.zadd('locationfragments', 0, locationwithid)

    locationkey = 'L-' + str(location['id'])
    redis.delete(locationkey)

    redis.rpush(locationkey, location['id'])
    redis.rpush(locationkey, location['displayname'])
    redis.rpush(locationkey, location['acname'])
    redis.rpush(locationkey, location['icon'])
    redis.rpush(locationkey, location['latitude'])
    redis.rpush(locationkey, location['longitude'])

    return jsonify({'location': location}), 201
 def delay(self, msg):
     msg.id = str(uuid.uuid4())
     value = json.dumps(msg.id)
     retry_ts = time.time() + 5
     # zset: key score1 value1 score2 value2
     # score: 到期处理时间 value: 请求的ID
     redis.zadd("delay-queue", retry_ts, value)
예제 #4
0
def send_message(redis, chat_id, sender, message):
    """ 发送消息
    :param redis:
    :param chat_id:
    :param sender:
    :param message:
    :return:
    """
    key_chat_group = CHAT_GRUOP.format(chat_id=chat_id)
    key_chat_message_ids = CHAT_MESSAGE_GEN_IDS.format(chat_id=chat_id)
    key_chat_message = CHAT_MESSAGE.format(chat_id=chat_id)

    identifier = acquire_lock(redis, key_chat_group)
    if not identifier:
        raise Exception("Couldn't get the lock")
    try:
        # 筹备待发送的消息。
        message_id = redis.incr(key_chat_message_ids)
        ts = time.time()
        paked = json.dumps({
            'id': message_id,
            'ts': ts,
            'sender': sender,
            'message': message,
        })
        # 将消息推送至群组
        redis.zadd(key_chat_message, {paked: message_id})
    except:
        pass
    finally:
        release_lock(redis, key_chat_group, identifier)
    return chat_id
예제 #5
0
def handler(event, context):
    for record in event['Records']:
        if record['eventName'] == "REMOVE":
            continue

        print(record)
        playerName = record['dynamodb']['NewImage']['PlayerName']['S']

        if 'OldImage' in record['dynamodb'].keys():
            oldScore = int(record['dynamodb']['OldImage']['Score']['N'])
            oldWin = int(record['dynamodb']['OldImage']['Win']['N'])
            oldLose = int(record['dynamodb']['OldImage']['Lose']['N'])

            olddata = {
                "PlayerName": str(playerName),
                "Win": int(oldWin),
                "Lose": int(oldLose)
            }
            old_json = json.dumps(olddata)
            redis.zrem('Rating', old_json)

        newScore = int(record['dynamodb']['NewImage']['Score']['N'])
        newWin = int(record['dynamodb']['NewImage']['Win']['N'])
        newLose = int(record['dynamodb']['NewImage']['Lose']['N'])

        newdata = {
            "PlayerName": str(playerName),
            "Win": int(newWin),
            "Lose": int(newLose)
        }
        new_json = json.dumps(newdata)

        redis.zadd('Rating', new_json, newScore)

    return "OK"
예제 #6
0
    def run(self):
        dbJson = list()
        redis = open_connection_redis(self.schema_conv_output_option.host,
                                      self.schema_conv_output_option.username,
                                      self.schema_conv_output_option.password,
                                      self.schema_conv_output_option.dbname)

        mongoConnection = open_connection_mongodb(self.schema_conv_init_option)

        # TODO: Map nhe lai cai nay thanh check schema roi loop tren kia.
        for dataAndSchema in mongoConnection.list_collection_names():
            data = dataAndSchema["data"]
            if dataAndSchema["schema"]["collection"] == "string":
                for item in data:
                    redis.set(item["key"], item["value"])
            elif dataAndSchema["schema"]["collection"] == "list":
                for item in data:
                    redis.rpush(item["key"], *item["value"])
            elif dataAndSchema["schema"]["collection"] == "set":
                for item in data:
                    redis.sadd(item["key"], *item["value"])
            elif dataAndSchema["schema"]["collection"] == "hash":
                for item in data:
                    redis.hset(item["key"], mapping=item["value"])
            elif dataAndSchema["schema"]["collection"] == "sortedSet":
                for item in data:
                    redis.zadd(item["key"], item["value"])
            else:
                for item in data:
                    # TODO: bitmap hyperlog
                    redis.set(
                        dataAndSchema["schema"]["collection"] + "_" +
                        item["key"], item["value"])
예제 #7
0
def handler(event, context):
    for record in event['Records']:
        if record['eventName'] == "REMOVE":
            continue
        
        print(record)
        playerName = record['dynamodb']['NewImage']['PlayerName']['S']
        
        if 'OldImage' in record['dynamodb'].keys():
            oldScore = int(record['dynamodb']['OldImage']['Score']['N'])
            oldWin = int(record['dynamodb']['OldImage']['Win']['N'])
            oldLose = int(record['dynamodb']['OldImage']['Lose']['N'])
            
            olddata = { "PlayerName" : str(playerName), "Win" : int(oldWin), "Lose" : int(oldLose)}
            old_json = json.dumps(olddata)
            redis.zrem('Rating', old_json)
        
        newScore = int(record['dynamodb']['NewImage']['Score']['N'])
        newWin = int(record['dynamodb']['NewImage']['Win']['N'])
        newLose = int(record['dynamodb']['NewImage']['Lose']['N'])
        
        newdata = { "PlayerName" : str(playerName), "Win" : int(newWin), "Lose" : int(newLose)}
        new_json = json.dumps(newdata)
        
        redis.zadd('Rating', new_json, newScore)

    return "OK" 
예제 #8
0
 def save(proxies):
     for proxy in proxies:
         redis.set(Proxy._get_redis_key(str(proxy)),
                   json.dumps(proxy._proxy_info))
         redis.sadd(Proxy._get_set_key(), str(proxy))
         redis.zadd(Proxy._get_sorted_set_key(),
                    {str(proxy): int(datetime.now().timestamp())})
예제 #9
0
    def store_message(self, mailfrom, target, rcpttos, data):
        msg = email.message_from_string(data)
        headers = {
            "From": msg.get("From"),
            "To": msg.get("To"),
            "Subject": msg.get("Subject"),
            "Date": time.ctime(time.time()),
        }
        text_parts = []
        html_parts = []
        for part in msg.walk():
            if part.get_content_type() == "text/plain":
                text_parts.append(part.get_payload())
            elif part.get_content_type() == "text/html":
                html_parts.append(self.clean_html(part.get_payload()))
        simple_msg = {"headers": headers, "text_parts": text_parts, "html_parts": html_parts}
        simple_msg_json = json.dumps(simple_msg)
        timestamp = time.time()

        msgid = redis.get("msgid_counter")
        if msgid:
            msgid = redis.incr("msgid_counter")
        else:
            redis.set("msgid_counter", 1)
            msgid = 1

        msgkey = "message:" + str(msgid)
        redis.set(msgkey, simple_msg_json)  # storing the msg once
        redis.zadd("messages:" + target, msgkey, timestamp)  # all messages to me
        redis.zadd("messages_from:" + target + ":" + mailfrom, msgkey, timestamp)  # all messages from you to me
예제 #10
0
def execute_later(redis, queue, name, args, delay=0):
    identifier = str(uuid.uuid4())
    item = json.dumps([identifier, queue, name, args])
    if delay > 0:
        redis.zadd('delayed:queue:', {item: time.time() + delay})
    else:
        redis.rpush('queue:' + queue, item)
    return identifier
예제 #11
0
def set_score_participant(hash_position: str) -> None:
    """
    Cria o score do participante com um valor inicial de 0.
    
    Parameters:
        hash_position: número do usuário.
    """
    redis.zadd(SCORES, {SCORE + hash_position: 0})
예제 #12
0
 def update_elo(self, p_a, p_b, score_a, score_b):
     Ra = redis.zscore('elo', p_a) or START_ELO
     Rb = redis.zscore('elo', p_b) or START_ELO
     Ea = 1.0 / (1 + 10.0**((Rb - Ra) / 400.0))
     Eb = 1.0 / (1 + 10.0**((Ra - Rb) / 400.0))
     Ra_new = Ra + 10 * (score_a - Ea)
     Rb_new = Rb + 10 * (score_b - Eb)
     redis.zadd('elo', {p_a: Ra_new})
     redis.zadd('elo', {p_b: Rb_new})
     return Ra_new, Rb_new, Ra_new - Ra
예제 #13
0
def load_initial_sites(redis):
    fname = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                         "data/other_sites.json")

    f = open(fname, 'r')
    parsed_json = json.load(f)
    sites = parsed_json['sites']
    scores = [int(time()) for i in range(len(sites))]
    zipped = zip(scores, sites)
    zset_args = [item for sublist in zipped for item in sublist]
    redis.zadd(redis_keys.URLS_TO_PROCESS_SET, *zset_args)
예제 #14
0
 def zadd_test(self, num=1000, pipe=False) :
     key = 'zadd-test-0'
     value = 'f382460a7c7c3597ef34b139ecda7e59'
     redis = self.get_redis()
     if pipe == False:
         for i in range(0, num):
             redis.zadd(key, i, value + str(i))
     else :
         pipe = redis.pipeline()
         for i in range(0, num):
             pipe.zadd(key, i, value + str(i))
         pipe.execute()
def load_initial_sites(redis):
    fname = os.path.join(
        os.path.dirname(os.path.abspath(__file__)),
        "data/other_sites.json")

    f = open(fname, 'r')
    parsed_json = json.load(f)
    sites = parsed_json['sites']
    scores = [int(time()) for i in range(len(sites))]
    zipped = zip(scores, sites)
    zset_args = [item for sublist in zipped for item in sublist]
    redis.zadd(redis_keys.URLS_TO_PROCESS_SET, *zset_args)
예제 #16
0
    def join(self, player):
        if player.table == self:
            return                              # Already part of this table.

        if player.table is not None:
            player.table.leave(player)          # Player has to leave old table

        msg = Message('JOINED')                 # Tell all the other players
        msg.player_name = player.name           # that a new player has joined.
        self.send(msg)

        player.table = self                     # Register the new player with
        self.players.append(player)             # this table.

        # Get a list of all the other players on this table
        others = redis.zrange(self.players_key, 0, -1)

        # Check if the player exists (race condition I guess)
        score = redis.zscore(self.players_key, player.name)
        if score is None:
            # Add new player to the player list
            redis.zadd(self.players_key, player.name, 0)

            # Add player to the turn list if he/she wasn't already there
            redis.zadd(self.turns_key, player.name, time.time())

        # Prepare joined messages for all existing players
        msgs = []
        for other in others:
            if other == player.name:
                continue
            msg = Message('JOINED')
            msg.player_name = other
            msgs.append(msg)

        # Prepare passed message to set correct turn
        current = self._get_artist()
        msg = Message('PASSED', player_name=current)
        if player.name == current:
            msg.word = redis.get(self.word_key)

            end_time = time.time() + 120
            if not redis.setnx(self.end_key, end_time):
                # Clock's already started!
                end_time = redis.get(self.end_key)
        else:
            end_time = redis.get(self.end_key)
            assert(end_time is not None)
        msg.end_time = end_time
        msgs.append(msg)

        # Send all the prepared messages
        gevent.joinall([gevent.spawn(player.send, x) for x in msgs])
예제 #17
0
    def join(self, player):
        if player.table == self:
            return  # Already part of this table.

        if player.table is not None:
            player.table.leave(player)  # Player has to leave old table

        msg = Message('JOINED')  # Tell all the other players
        msg.player_name = player.name  # that a new player has joined.
        self.send(msg)

        player.table = self  # Register the new player with
        self.players.append(player)  # this table.

        # Get a list of all the other players on this table
        others = redis.zrange(self.players_key, 0, -1)

        # Check if the player exists (race condition I guess)
        score = redis.zscore(self.players_key, player.name)
        if score is None:
            # Add new player to the player list
            redis.zadd(self.players_key, player.name, 0)

            # Add player to the turn list if he/she wasn't already there
            redis.zadd(self.turns_key, player.name, time.time())

        # Prepare joined messages for all existing players
        msgs = []
        for other in others:
            if other == player.name:
                continue
            msg = Message('JOINED')
            msg.player_name = other
            msgs.append(msg)

        # Prepare passed message to set correct turn
        current = self._get_artist()
        msg = Message('PASSED', player_name=current)
        if player.name == current:
            msg.word = redis.get(self.word_key)

            end_time = time.time() + 120
            if not redis.setnx(self.end_key, end_time):
                # Clock's already started!
                end_time = redis.get(self.end_key)
        else:
            end_time = redis.get(self.end_key)
            assert (end_time is not None)
        msg.end_time = end_time
        msgs.append(msg)

        # Send all the prepared messages
        gevent.joinall([gevent.spawn(player.send, x) for x in msgs])
예제 #18
0
파일: server.py 프로젝트: yxw2014/ccg
    def __init__(self, stream, address):
        self._stream = stream
        self._address = address
        self._message = []
        self._stream.set_close_callback(self.on_close)

        self.uuid = str(uuid.uuid4())
        #self.uuid= str(451377)

        obj = ConnectionObj()
        obj.stream = self._stream
        obj.time = int(time.time())
        obj.uuid = self.uuid

        Connection.clients[self.uuid] = obj
        redis.zadd('hs:user:session' + ":" + server_id, self.uuid,
                   int(time.time()))
        '''
        all_uuids= []
        for id, client in Connection.clients.items(): 
             all_uuids.append({"uuid":id})
         
         
        for id, client in Connection.clients.items(): 
                if id== self.uuid:  
                    encoded_data = {"uuid":self.uuid, "service": "main", "method": "signUpSucceeded", "params":{"all_user": all_uuids}}                     
                else:
                    continue
                    encoded_data = {"uuid":self.uuid, "service": "main", "method": "joinNewPlayer", "params":{"user": {'uuid':self.uuid}}}
                print encoded_data
                reqt= request(encoded_data)
                res= reqt.dump()
                
                client.stream.write_to_fd(res) 
         '''

        encoded_data = {
            "uuid": self.uuid,
            "service": "main",
            "method": "signUpSucceeded",
            "params": {}
        }
        reqt = request(encoded_data)
        res = reqt.dump()
        self._stream.write_to_fd(res)

        self.read_message()

        print "A new user has entered.", address, self.uuid
예제 #19
0
def company_event_changes():
    rethink_conn = yield r.connect(**rethink_conn.conn())
    feed = yield r.table('company_events').changes().run(rethink_conn)
    while (yield feed.fetch_next()):
        change = yield feed.next()
        # get domain of company 

        qry = {"domain":change["new_val"]["domain"]}
        users = r.table("user_contacts").filter(qry).run(conn)
        max_number_of_elements = 100
        val = change["new_val"]
        for user in users:
            key = "user:#{id}".format(user)
            #redis.zadd(key, score, new_content.id)
            redis.zadd(key, val["timestamp"], val["id"])
            redis.zremrangebyrank(key, max_number_of_elements, -1)
예제 #20
0
def inital():
    """
    inital project data to redis
    :return:
    """
    for path in get_files(settings.PROJECT_DIR, ".md"):
        # 文件创建时间
        # 有序结合保存所有文档,查看所有文章时,可以按照时间顺序查看
        create_time = os.path.getctime(path)
        redis.zadd('admin.blog.list', create_time, utils.encrypt(path))

        # 把文件的上级目录当作标签
        #有序set存放该标签下的文章,相当于文章按标签分类,用有序集合的原因是可以按时间顺序显示
        tag_name = os.path.basename(os.path.dirname(path))
        redis.zadd('blog.tag.%s' % tag_name, create_time, utils.encrypt(path))

        #set集合存放所有标签
        redis.sadd('blog.tag', tag_name)
예제 #21
0
def inital():
    """
    inital project data to redis
    :return:
    """
    for path in get_files(settings.PROJECT_DIR, ".md"):
        # 文件创建时间
        # 有序结合保存所有文档,查看所有文章时,可以按照时间顺序查看
        create_time = os.path.getctime(path)
        redis.zadd('admin.blog.list', create_time, utils.encrypt(path))

        # 把文件的上级目录当作标签
        #有序set存放该标签下的文章,相当于文章按标签分类,用有序集合的原因是可以按时间顺序显示
        tag_name = os.path.basename(os.path.dirname(path))
        redis.zadd('blog.tag.%s' % tag_name, create_time, utils.encrypt(path))

        #set集合存放所有标签
        redis.sadd('blog.tag', tag_name)
예제 #22
0
def article_switch_vote(redis, user, from_article, to_article):
    # HOMEWORK 2 Part I
    from_article_id = from_article.split(':')[-1]
    to_article_id = to_article.split(':')[-1]

    redis.srem('voted:' + from_article_id, user)
    redis.sadd('voted:' + to_article_id, user)
    # or redis.smove('voted:' + from_article_id, 'voted:' + to_article_id, user)

    from_article_score = redis.zscore('score:', 'article:' + from_article_id)
    changed_from_article_score = from_article_score - 432
    to_article_score = redis.zscore('score:', 'article:' + to_article_id)
    changed_to_article_score = to_article_score + 432

    redis.zrem('score:', 'article:' + from_article_id)
    redis.zadd('score:', changed_from_article_score,
               'article:' + from_article_id)
    redis.zrem('score:', 'article:' + to_article_id)
    redis.zadd('score:', changed_to_article_score, 'article:' + to_article_id)
예제 #23
0
def publish_article(redis, user, title, link):
    user_id = user.split(':')[-1]
    article_id = str(int(redis.zrange("nArticles", 0, 0)[0]) + 1)

    redis.hset("article:" + article_id, "title", title)
    redis.hset("article:" + article_id, "upvotes", 1)
    redis.hset("article:" + article_id, "user", user_id)
    redis.hset("article:" + article_id, "link", link)
    redis.hset("article:" + article_id, "time", time.time())
    redis.hset("article:" + article_id, "comments", 0)

    redis.hincrby(name=user, key="submissions", amount=1)
    redis.hincrby(name=user, key="karma", amount=1)

    redis.sadd("uSubmissions:" + user_id, article_id)

    redis.zadd("tArticles", 1, article_id)
    redis.zadd("nArticles", time.time(), article_id)

    return article_id
예제 #24
0
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
예제 #25
0
def add_domains():
    try:
        assert request.data, "there is no data"
        json = request.get_json()
        assert isinstance(json, dict), "Data is not a dict"
        assert "links" in json, "Trere is no field 'links' in data"
        assert isinstance(json["links"], list), "'links' is not a list"
        assert json["links"] != [], "'links' list is empty"
        assert list_isinstance(json["links"],
                               str), ("'links' contain non-string values")
        domains = [check_valid_domain(link) for link in json["links"]]
    except Exception as e:
        return {"status": str(e)}, 400

    try:
        assert is_db_connected, "no connection to redis db"
        timestamp = int(datetime.now(tz=timezone.utc).timestamp())
        domains = dict(zip(domains, [timestamp] * len(domains)))
        redis.zadd("visited_links", domains)
    except Exception as e:
        return {"status": str(e)}, 500
    return {"status": "ok"}
예제 #26
0
    def _pass_turn(self, player_name, guesser=None, score=None):
        # Get the next player
        next_player = redis.zrange(self.turns_key, 1, 1)

        # Are we playing with ourself?
        if next_player:
            next_player = next_player[0]
        else:
            next_player = player_name

        # Set the new word
        word = redis.set(self.word_key, get_next_word().text)

        # Clear the skip key
        redis.delete(self.skip_key)

        # Tell everyone who's turn it is
        msg = Message('PASSED', player_name=next_player)
        msg.end_time = time.time() + 120
        redis.set(self.end_key, msg.end_time)
        if score is not None:
            msg.guesser = guesser
            msg.score = score
        self.send(msg)

        # Ten points to win the game
        if score >= 10:
            # Send the won message
            self.send(Message('WON', player_name=guesser))

            # Clear all scores
            players = redis.zrange(self.players_key, 0, -1)
            scores = dict((x, 0) for x in players)
            redis.zadd(self.players_key, **scores)

        # Move the old player to the end of the turn list
        redis.zadd(self.turns_key, player_name, time.time())
예제 #27
0
def fetch_pending_message(redis, recipient):
    """ 获取消息
    :param redis:
    :param recipient:
    :return:
    """
    key_user_seen = CHAT_USER_SEEN.format(user=recipient)

    # 获取最后接收到的消息ID
    seen = redis.zrange(key_user_seen, 0, -1, withscores=True)
    p = redis.pipeline()
    for chat_id, seen_id in seen:
        key_chat_message = CHAT_MESSAGE.format(chat_id=chat_id)

        p.zrangebyscore(key_chat_message, seen_id + 1, 'inf')
    chat_info = zip(seen, p.execute())
    for i, ((chat_id, seen_id), messages) in enumerate(chat_info):
        if not messages:
            continue
        key_chat_group = CHAT_GRUOP.format(chat_id=chat_id)

        messages[:] = map(json.loads, messages)
        # 使用最新收到的消息来更新群组有序集合。
        seen_id = messages[-1]['id']
        redis.zadd(key_chat_group, {recipient: seen_id})
        # 找出那些所有人都已经阅读过的消息
        min_id = redis.zrange(key_chat_group, 0, 0, withscores=True)
        # 更新已读消息有序集合
        p.zadd(key_user_seen, {chat_id: seen_id})
        if min_id:
            key_chat_message = CHAT_MESSAGE.format(chat_id=chat_id)

            # 清除那些已经被所有人阅读过的消息
            p.zremrangebyscore(key_chat_message, 0, min_id[0][1])
        chat_info[i] = (chat_id, messages)
    p.execute()
    return chat_info
예제 #28
0
    def _pass_turn(self, player_name, guesser=None, score=None):
        # Get the next player
        next_player = redis.zrange(self.turns_key, 1, 1)

        # Are we playing with ourself?
        if next_player:
            next_player = next_player[0]
        else:
            next_player = player_name

        # Set the new word
        word = redis.set(self.word_key, get_next_word().text)

        # Clear the skip key
        redis.delete(self.skip_key)

        # Tell everyone who's turn it is
        msg = Message('PASSED', player_name=next_player)
        msg.end_time = time.time() + 120
        redis.set(self.end_key, msg.end_time)
        if score is not None:
            msg.guesser = guesser
            msg.score = score
        self.send(msg)

        # Ten points to win the game
        if score >= 10:
            # Send the won message
            self.send(Message('WON', player_name=guesser))

            # Clear all scores
            players = redis.zrange(self.players_key, 0, -1)
            scores = dict((x, 0) for x in players)
            redis.zadd(self.players_key, **scores)

        # Move the old player to the end of the turn list
        redis.zadd(self.turns_key, player_name, time.time())
예제 #29
0
    def post(self):
        redis = datastore.get_datastore()

        # get a dict from the response
        activity = request.get_json(force=True)

        position = int(redis.get('activityindex'))
        redis.incr('activityindex', 1)
        activity['id'] = str(position)

        akey = "activity:" + str(activity['id'])
        redis.hset('activitieshash', akey, pickle.dumps(activity))

        redis.zadd('sortet-activities:all', position, akey)
        if (activity['state'] == "FINISHED"):
            redis.zadd('sortet-activities:finished', position, akey)
        else:
            redis.zadd('sortet-activities:notfinished', position, akey)
        return activity, 201
예제 #30
0
            print(arguments.set, "set to", arguments.value, "for",
                  arguments.expire, "seconds")
        else:
            redis.set(arguments.set, arguments.value)
            print(str(arguments.set), ":", str(arguments.value))

    else:
        print("value not given for the key :", arguments.set)

# for adding to a orered set ---------------------------------------------
if arguments.zadd:
    if arguments.key:
        if arguments.score:
            if arguments.member:
                # redis.zadd("key",{"value":score}) syntax of zadd for newer update of redis-----------------
                redis.zadd(arguments.key, {arguments.member: arguments.score})
                print("zadd", arguments.key, arguments.score, arguments.member)
            else:
                print("provide member for zadd")
        else:
            print("provide score for zadd")
    else:
        print("provide the key for zadd")

if arguments.zrange:
    if arguments.key:
        data = redis.zrange(arguments.key, 0, -1)
        print(data[:])
    else:
        print("provide the key for zrange")
예제 #31
0
def addSynonymsToRedis(word, syns):
    for syn in syns:
        redis.zadd(word, syn[1], syn[0])
예제 #32
0
def index_add(id, score):
    redis.zadd('index', id, score)
예제 #33
0
def delay(msg):
    msg.id = str(uuid.uuid4())
    value = json.dumps(msg)
    retry_ts = time.time() + 5
    redis.zadd("delay-queue", msg_id, value)
예제 #34
0
#https://developer.redis.com/develop/python/

import redis

redis = redis.Redis(host='localhost', port='6379')

redis.set('mykey', 'Hello from Python!')
value = redis.get('mykey')
print(value)

redis.zadd('vehicles', {'car': 0})
redis.zadd('vehicles', {'bike': 0})
vehicles = redis.zrange('vehicles', 0, -1)
print(vehicles)
예제 #35
0
    redis.sadd(albums_key, album_key)

    for tune in tunes:

        album, title, artist = tune.id3gw.get_album(), tune.id3gw.get_title(), tune.id3gw.get_artist()
        if not album or not title or not artist:
            continue  # @todo log {{path}}...

        tune_key = RdsTune.get_key(album, title, artist)
        tune_id3_key = RdsTune.get_id3_key(tune_key)
        tune_audio_key = RdsTune.get_audio_key(tune_key)

        for key, value in tune.get_id3().iteritems():
            redis.hset(tune_id3_key, key, value)

        redis.zadd(album_tunes_key, tune_key, tune.id3gw.get_trackn())
        redis.sadd(tunes_key, tune_key)  # track and add all tunes

    for image in images:

        if image.get_type() is image.get_undefined_type():
            continue

        i = {
            "type": image.get_type(),
            "dimx": image.get_dimx(),
            "dimy": image.get_dimx(),
            "filenameid": image.get_filename_id((album_id3["artist"], album_id3["album"]), image.get_type()),
        }

        image_key = RdsImage.get_key(artist, album, image.get_type())
예제 #36
0
def refresh_fair_semaphore(redis, semname, identifier):
    semname = "semaphore:" + semname
    if redis.zadd(semname, {identifier: time.time()}):
        release_fair_semaphore(redis, semname, identifier)
        return False
    return True
예제 #37
0
import redis

redis = redis.Redis()
redis.flushall()

FEM = "female_names_set"

with open("female-names.txt", "r") as f:
    for line in f:
        redis.zadd(FEM, {line.rstrip(): 0})

print("Finished loading the names")
print(redis.zrange(FEM, 4500, 4510))
print("Searching that start with susann")
for tup in redis.zscan_iter(FEM, "susann*"):
    print(tup[0], end=',')
print()

while True:
    name = input("Search for ('Enter' for quit): ")
    if name == "":
        break
    for tup in redis.zscan_iter(FEM, name + "*"):
        print(tup[0])

## b)
redis.flushall()
with open("nomes-registados-2018.csv", "r") as f:
    for line in f:
        name, gender, num = line.rstrip().split(",")
        redis.zadd(FEM, {name: num})
예제 #38
0
redis.sadd("aComments:2", "1", "2")

#USER COMMENTS
redis.sadd("uComments:1", "21")

redis.sadd("uComments:2", "11")

redis.sadd("uComments:3", "12", "22")

#USER SUBMISSIONS
redis.sadd("uSubmissions:1", "1")

redis.sadd("uSubmissions:2", "2")

#TOP ARTICLES
redis.zadd("tArticles", 1234, "1")
redis.zadd("tArticles", 4321, "2")

#NEW ARTICLES
redis.zadd("nArticles", time.time() - 333333, "1")
redis.zadd("nArticles", time.time() - 4444444, "2")

#COUNTER
redis.hset("counter", "user", 3)
redis.hset("counter", "comments", 4)
redis.hset("counter", "articles", 2)

#create new user
new_user(redis, 'niki')

#user publishes article
예제 #39
0
def delay(msg):
    # uuid.uuid4() - Generate a random UUID
    msg.id = str(uuid.uuid4())  # 保证value值唯一
    value = json.dumps(msg)
    retry_ts = time.time() + 5  # 5秒重试
    redis.zadd("delay-queue", retry_ts, value)