示例#1
0
    def __init__(self, key="", ttl=30):
        """
        :param key:
        :param ttl: redis key expire time(锁最大过期时间) / s
        :return:
        Usage::

            with (yield AsyncAntiDDosLock('my_lock').acquire()):
                print "Critical section"
        """
        self.redis_client = Redis()
        self.key = "redis:lock:anti-DDos:" + str(key)
        self.ttl = ttl
        # generate a unique UUID
        self.value = uuid.uuid1().get_hex()
示例#2
0
class AsyncAntiDDosLock(object):
    def __init__(self, key="", ttl=30):
        """
        :param key:
        :param ttl: redis key expire time(锁最大过期时间) / s
        :return:
        Usage::

            with (yield AsyncAntiDDosLock('my_lock').acquire()):
                print "Critical section"
        """
        self.redis_client = Redis()
        self.key = "redis:lock:anti-DDos:" + str(key)
        self.ttl = ttl
        # generate a unique UUID
        self.value = uuid.uuid1().get_hex()

    def acquire(self):
        """Decrement the counter. Returns a Future.

        Block if the counter is zero and wait for a `.release`. The Future
        raises `.TimeoutError` after the deadline.
        """
        waiter = Future()
        if self.redis_client.set(self.key, self.value, ex=self.ttl, nx=True):
            waiter.set_result(locks._ReleasingContextManager(self))
        else:
            waiter.set_exception(DDosError("被暴击了"))
        # def on_timeout():
        #     waiter.set_exception(gen.TimeoutError())
        # io_loop = ioloop.IOLoop.current()
        # timeout_handle = io_loop.add_timeout(timeout, on_timeout)
        # waiter.add_done_callback(
        #     lambda _: io_loop.remove_timeout(timeout_handle))
        return waiter

    def release(self):
        if self.redis_client.get(self.key) == self.value:
            self.redis_client.delete(self.key)

    def __enter__(self):
        raise RuntimeError(
            "Use AsyncLock like 'with (yield AsyncLock().acquire())', not like"
            " 'with AsyncLock()'")

    __exit__ = __enter__
示例#3
0
# -*- coding:utf-8 -*-
if __name__ == '__main__':
    import os
    import sys
    sys.path.insert(0, os.path.join(os.getcwd(), os.pardir))

from tools_lib.common_util.archived.mysql_tools import Conn2Mysql
from tools_lib.gedis.core_redis_key import *
from tools_lib.gedis.gedis import Redis

redis_client = Redis()


def name2code(province='', city='', district=''):
    """
    中文地理位置编码
    :param province:
    :param city:
    :param district:
    :return:
        {
            "province_code": 3921830921830921,
            "city_code": 8309218309218,
            "district_code": 830921830921
        }
    """
    redis_key = key_area_code.format(province_name=province, city_name=city, district_name=district)
    if redis_client.exists(redis_key):
        result = redis_client.hgetall(redis_key)
        for k in result.keys():
            result[k] = int(result[k])
示例#4
0
#coding=utf-8
__author__ = 'kk'

import json
import logging
from tornado import gen

from tools_lib.gedis.gedis import Redis
from tools_lib.gtornado.web2 import ReqHandler
from tools_lib.windchat import conf

from .utils.answerer_utils import pack_leancloud_callback_to_ws
from .utils import channel_utils, message_utils

redisc = Redis()


class LeancloudChannelMessageCallback(ReqHandler):
    """
    给leancloud调用的频道对话回调
    """
    @gen.coroutine
    def post(self):
        # =========> verify token firstly <=========
        try:
            token = self.get_query_argument("token")
        except:
            logging.error("No token connection declined.")
            logging.info("data: %s" % self.request.body)
            self.resp_unauthorized("no token, no way.")
            return