예제 #1
0
    def get_auth_token(cls):
        token = cache.get(cls.CACHE_KEY)
        if not token:
            token = cls.generate_auth_token()
            cache.set(cls.CACHE_KEY, token, expire=cls.CACHE_EXPIRE)

        return token
예제 #2
0
        def wrap(*args, **kwargs):
            data = cache.get(redis_key)
            if data:
                return data

            data = func(*args, **kwargs)
            cache.set(redis_key, data, expire=ttl)
            return data
예제 #3
0
파일: views.py 프로젝트: shaoeric/flask
def email_captcha():
    #      /email_captcha/[email protected]
    email = request.args.get('email')
    if not email:
        return restful.paramserror('请传递邮箱参数')
#     给这个邮箱发送邮件
    source = list(string.ascii_letters)
    source.extend(map(lambda x: str(x), range(0, 10)))
    captcha = "".join(random.sample(source, 6))
    message = Message('python论坛',
                      recipients=[email],
                      body='您的验证码是%s' % captcha)
    try:
        mail.send(message)
    except:
        return restful.servererror()

    cache.set(email, captcha)
    return restful.success()
예제 #4
0
def send_captcha():
    email = request.args.get("email")  #取出ajax提交上来的数据
    source = list(string.ascii_letters)
    #string.ascii_letters是一个字符串类型 : "a-z/A-Z ",然后转换成列表形式:["a"...."Z"]
    source.extend(map(lambda x: str(x), range(0, 10)))
    #map(函数,可迭代对象),它会将可迭代对象执行前面函数,返回值放到一个列表中;此代码最后拿到
    #["0"...."9"],然后extend方法更新到source列表中
    captcha = "".join(random.sample(source, 6))
    #random中sample方法随机在列表中选区几位数;join将列表拼接成字符串,就得到了验证码
    message = Message("之微论坛",
                      recipients=[email],
                      body="你的验证码是:{}".format(captcha))
    try:  #捕获一下异常
        mail.send(message)
    except:
        return restful.servererror()
    cache.set(email, captcha)  #将邮箱与验证码设置到memcache里面,方便在form表单中调用,判断与
    #提交上来的验证码是否一致
    return restful.success("邮件已发送,请注意查收")
예제 #5
0
def email_captcha():
    email = request.args.get("email")
    if not email:
        return restful.param_error(message="请传递参数")

    source = list(string.ascii_letters)
    source.extend([str(i) for i in range(10)])
    captcha = "".join(random.sample(source, 6))

    # 缓存验证码
    cache.set(email, captcha)

    msg = Message("flask测试验证码", recipients=[email])
    msg.body = 'captcha: %s' % captcha
    try:
        th = Thread(target=send_email.send_email_async, args=[msg])
        # mail.send(msg)
        th.start()
        th.join()
    except:
        return restful.server_error("服务器开小差了")
    return restful.success()
예제 #6
0
def passes(norad_id):
    try:
        query = PassesQuery().load(request.args)
    except ValidationError as err:
        return jsonify(err.messages), 400

    limit = query.pop('limit')
    cache_key = get_cache_key(norad_id, query, prefix="passes")
    cache_response = cache.get(cache_key)

    # Return results from cache if hit
    if cache_response:
        passes = json.loads(cache_response)
        next_passes = filter_next_passes(passes)
        return Response(json.dumps(next_passes[:limit]), headers={
            "x-api-cache": "HIT",
            "x-api-cache-ttl": f"{cache.ttl(cache_key)}",
            "content-type": "application/json"
        })

    # Calculate next passes
    try:
        tracker = SatTracker(query["lat"], query["lon"], norad_id=norad_id)
    except TLENotFound:
        return jsonify({"error": "TLE not found"}), 400

    passes = tracker.next_passes(
        days=query["days"],
        visible_only=query["visible_only"]
    )

    # Cache passes for 1 day
    content = json.dumps(passes)
    cache.set(cache_key, content, ex=timedelta(days=1))

    return Response(json.dumps(passes[:limit]), headers={
        "x-api-cache": "MISS",
        "content-type": "application/json"
    })
예제 #7
0
        def wrap(request, *args, **kwargs):
            char_id = getattr(request, char_id_name, None)
            if not char_id:
                return func(request, *args, **kwargs)

            redis_key = 'opt:{0}:{1}'.format(func_name, char_id)
            if keep_result:
                data = cache.get(redis_key)
                if data:
                    extra = {
                        'log_type_id': 1,
                        'error_id': error_code,
                        'char_id': char_id,
                        'func_name': func_name,
                        'error_msg': 'Operate Too Fast, Return from cache',
                        'occurred_at': arrow.utcnow().to(TIME_ZONE).format('YYYY-MM-DD HH:mm:ss')
                    }

                    logger.info("Operate Guard. Char {0} operate {1} too fast. Return result from cache.".format(char_id, func_name),
                                extra=extra
                                )
                    return data

                data = func(request, *args, **kwargs)
                cache.set(redis_key, data, expire=interval)
                return data
            else:
                x = cache.get(redis_key)
                if x:
                    raise SanguoException(
                        error_code,
                        char_id,
                        "Operate Guard",
                        "operate {0} too fast".format(func_name)
                    )

                cache.set(redis_key, 1, expire=interval)
                return func(request, *args, **kwargs)
예제 #8
0
        def wrap(request, *args, **kwargs):
            char_id = getattr(request, char_id_name, None)
            if not char_id:
                return func(request, *args, **kwargs)

            redis_key = 'opt:{0}:{1}'.format(func_name, char_id)
            if keep_result:
                data = cache.get(redis_key)
                if data:
                    extra = {
                        'log_type_id': 1,
                        'error_id': errormsg.OPERATE_TOO_FAST,
                        'char_id': char_id,
                        'func_name': func_name,
                        'error_msg': 'Operate Too Fast, Return from cache',
                        'occurred_at': localnow().strftime('%Y-%m-%d %H:%M:%S'),
                    }

                    logger.info("Operate Guard. Char {0} operate {1} too fast. Return result from cache.".format(char_id, func_name),
                                extra=extra
                                )
                    return data

                data = func(request, *args, **kwargs)
                cache.set(redis_key, data, expire=interval)
                return data
            else:
                x = cache.get(redis_key)
                if x:
                    raise SanguoException(
                        errormsg.OPERATE_TOO_FAST,
                        char_id,
                        "Operate Guard",
                        "operate {0} too fast".format(func_name)
                    )

                cache.set(redis_key, 1, expire=interval)
                return func(request, *args, **kwargs)
예제 #9
0
def get_tle(norad_id):
    """Get latest TLE from API"""
    cache_key = f"tle:{norad_id}"
    tle = cache.get(cache_key)

    if tle:
        logger.info(f"Cache TLE HIT norad={norad_id}")
        return tle.split("\n")

    response = session.get(CELESTRAK_API_TLE, params={
        "CATNR": norad_id,
        "FORMAT": "TLE"
    })

    tle = response.text

    if tle == "No GP data found":
        raise TLENotFound

    logger.info(f"Cache TLE MISS, saving norad={norad_id}")
    cache.set(cache_key, tle, CACHE_TIMEOUT)

    return tle.split("\n")
예제 #10
0
파일: views.py 프로젝트: AlbertMusk/bbs
def email_captcha():
    email = request.args.get('email')
    if not email:
        return restful.params_error(message='请传递邮箱')
    else:
        # string.ascii_letters 可以拿到一个a-zA-Z的字符串
        # list()可以将字符串中的每一个字符作为列表的一项
        source = list(string.ascii_letters)
        # map(func= , 可迭代对象)
        # map方法可以将可迭代对象中的每一项执行func方法
        source.extend(map(lambda x:str(x),range(0,10)))
        # random.sample(列表,个数)方法可以在列表中随机拿多少个
        # ''.join() 可以将列表中的每一项组成一个字符串
        captcha = ''.join(random.sample(source,6))

        message = Message('Python论坛邮箱验证码',recipients=[email],body='您的邮箱验证码是:%s'%captcha)
        try:
            mail.send(message)
        except:
            return restful.params_error()
        cache.set(email,captcha,ex=120)
        print(cache.get(email))
        return restful.success()
예제 #11
0
        def wrap(request, *args, **kwargs):
            char_id = getattr(request, char_id_name, None)
            if not char_id:
                return func(request, *args, **kwargs)

            redis_key = 'opt:{0}:{1}'.format(func_name, char_id)
            if keep_result:
                data = cache.get(redis_key)
                if data:
                    extra = {
                        'log_type_id': 1,
                        'error_id': errormsg.OPERATE_TOO_FAST,
                        'char_id': char_id,
                        'func_name': func_name,
                        'error_msg': 'Operate Too Fast, Return from cache',
                        'occurred_at':
                        localnow().strftime('%Y-%m-%d %H:%M:%S'),
                    }

                    logger.info(
                        "Operate Guard. Char {0} operate {1} too fast. Return result from cache."
                        .format(char_id, func_name),
                        extra=extra)
                    return data

                data = func(request, *args, **kwargs)
                cache.set(redis_key, data, expire=interval)
                return data
            else:
                x = cache.get(redis_key)
                if x:
                    raise SanguoException(
                        errormsg.OPERATE_TOO_FAST, char_id, "Operate Guard",
                        "operate {0} too fast".format(func_name))

                cache.set(redis_key, 1, expire=interval)
                return func(request, *args, **kwargs)
예제 #12
0
파일: backend.py 프로젝트: w1ndseek2/HWRR
def register(_data):
    if not cache.exists(session['username']):
        log.info('设置register_data[session[\'username\']]为空')
        cache.set(session['username'] + '.count', 0, ex=600)
        # expires in 10 minutes
    session['action'] = 'register'
    if verify(_data):
        cache.rpush(session['username'], json.dumps(_data))
        cache.incr(session['username'] + '.count')

        log.info('获取到了一组合法签名数据')
        log.debug(_data)
    if int(cache.get(session['username'] + '.count')) >= 3:
        log.info('获取到了三组信息,成功注册')

        log.debug('所有数据:')
        register_data = cache.lrange(session['username'], 0, -1)
        register_data = [json.loads(i) for i in register_data]
        log.debug(register_data)

        cache.delete(session['username'])
        cache.delete(session['username'] + '.count')

        real = DynamicProcess.prepare_list(register_data)
        real_v = DynamicProcess.prepare_value(real)
        execute_sql(
            "INSERT INTO user (username, password, sign_prepared, sign_val) values (\
                %(username)s, %(password)s, %(sign_prepared)s, %(sign_val)s\
            )",
            username=session['username'],
            password=session['password'],
            sign_prepared=json.dumps(real),
            sign_val=real_v)
        session.pop('username')
        session.pop('password')
        return 'ret'
    return 'continue'
예제 #13
0
    def get_info(self):
        info = cache.get(self.make_cache_key())
        if info:
            return info

        # 需要获取新数据
        db = MongoClubLeaderboard.db(self.server_id)

        my_doc = db.find_one({'_id': self.char_id})
        if not my_doc:
            ClubLeaderBoard.generate(self.server_id)
            my_doc = db.find_one({'_id': self.char_id})

        level = []
        power = []
        my_level_rank = 0
        my_power_rank = 0

        rank = 1
        for doc in db.find({}).sort('level', -1).limit(30):
            level.append((doc['_id'], doc['level'], doc['power']))
            if doc['_id'] == self.char_id:
                my_level_rank = rank

            rank += 1

        rank = 1
        for doc in db.find({}).sort('power', -1).limit(30):
            power.append((doc['_id'], doc['level'], doc['power']))
            if doc['_id'] == self.char_id:
                my_power_rank = rank

            rank += 1

        if not my_level_rank:
            my_level_rank = db.find({'level': {'$gte': my_doc['level']}}).count()

        if not my_power_rank:
            my_power_rank = db.find({'power': {'$gte': my_doc['power']}}).count()

        # 下次更新时间
        # NOTE, 注意 定时任务也要同步修改
        now = arrow.utcnow()
        if now.minute >= 30:
            # 下一个小时30分更新
            next_update_at = now.replace(hours=1)
        else:
            next_update_at = now

        # 虽然定时任务是30分启动的,但是这里设定到35分
        next_update_at = next_update_at.replace(minute=35).timestamp

        info = {
            'level': level,
            'power': power,
            'my_level_rank': my_level_rank,
            'my_power_rank': my_power_rank,
            'next_update_at': next_update_at
        }

        expire = next_update_at - now.timestamp
        cache.set(self.make_cache_key(), info, expire=expire)

        return info
예제 #14
0
 def _set_cache(self, key):
     today = get_start_time_of_today()
     tomorrow = today.replace(days=1)
     expire = tomorrow.timestamp - arrow.utcnow().timestamp
     cache.set(key, 1, expire=expire)
예제 #15
0
 def make_cache(self):
     key = 'unit:{0}:{1}'.format(self.char_id, self.id)
     cache.set(key, self)
예제 #16
0
    def get_info(self):
        info = cache.get(self.make_cache_key())
        if info:
            return info

        # 需要获取新数据
        db = MongoClubLeaderboard.db(self.server_id)

        my_doc = db.find_one({'_id': self.char_id})
        if not my_doc:
            ClubLeaderBoard.generate(self.server_id)
            my_doc = db.find_one({'_id': self.char_id})

        level = []
        power = []
        my_level_rank = 0
        my_power_rank = 0

        rank = 1
        for doc in db.find({}).sort('level', -1).limit(30):
            level.append((doc['_id'], doc['level'], doc['power']))
            if doc['_id'] == self.char_id:
                my_level_rank = rank

            rank += 1

        rank = 1
        for doc in db.find({}).sort('power', -1).limit(30):
            power.append((doc['_id'], doc['level'], doc['power']))
            if doc['_id'] == self.char_id:
                my_power_rank = rank

            rank += 1

        if not my_level_rank:
            my_level_rank = db.find({
                'level': {
                    '$gte': my_doc['level']
                }
            }).count()

        if not my_power_rank:
            my_power_rank = db.find({
                'power': {
                    '$gte': my_doc['power']
                }
            }).count()

        # 下次更新时间
        # NOTE, 注意 定时任务也要同步修改
        now = arrow.utcnow()
        if now.minute >= 30:
            # 下一个小时30分更新
            next_update_at = now.replace(hours=1)
        else:
            next_update_at = now

        # 虽然定时任务是30分启动的,但是这里设定到35分
        next_update_at = next_update_at.replace(minute=35).timestamp

        info = {
            'level': level,
            'power': power,
            'my_level_rank': my_level_rank,
            'my_power_rank': my_power_rank,
            'next_update_at': next_update_at
        }

        expire = next_update_at - now.timestamp
        cache.set(self.make_cache_key(), info, expire=expire)

        return info
예제 #17
0
 def make_cache(self):
     key = 'staff:{0}'.format(self.id)
     cache.set(key, self)
예제 #18
0
파일: hero.py 프로젝트: hx002/sanguo-server
 def save_cache(self):
     cache.set('hero:{0}'.format(self.id), self)
예제 #19
0
파일: models.py 프로젝트: prcek/TSReg
def get_folder_list():
    d = cache.get("folder_list")
    if d is None:
        d = build_folder_list()
        cache.set("folder_list", d)
    return d
예제 #20
0
 def save_cache(self):
     cache.set('hero:{0}'.format(self.id), self)
예제 #21
0
파일: models.py 프로젝트: prcek/TSReg
def get_season_list():
    d = cache.get("season_list")
    if d is None:
        d = build_season_list()
        cache.set("season_list", d)
    return d
예제 #22
0
 def make_cache(self):
     key = 'staff:{0}'.format(self.id)
     cache.set(key, self)
예제 #23
0
파일: hero.py 프로젝트: yaosj/sanguo-server
 def save_cache(self):
     cache.set('hero:{0}'.format(self.id), self, expire=3600*3)
예제 #24
0
 def make_cache(self):
     key = 'unit:{0}:{1}'.format(self.char_id, self.id)
     cache.set(key, self)
예제 #25
0
 def save_cache(self):
     cache.set('hero:{0}'.format(self.id), self, expire=3600 * 3)
예제 #26
0
 def _set_cache(self, key):
     today = get_start_time_of_today()
     tomorrow = today.replace(days=1)
     expire = tomorrow.timestamp - arrow.utcnow().timestamp
     cache.set(key, 1, expire=expire)