Esempio n. 1
0
    def create(self):
        """
        Create a new session
        """
        # Generate a unique id
        self._data['id'] = str(uuid4())

        # Set created_at to now
        self._data['created_at'] = datetime.now().timestamp()

        # Save session settings
        redis.hset(f"session::{self.id}",
                   mapping={
                       "title": self.title,
                       "description": self.description,
                       "created_at": self.created_at,
                       "duration": self.duration
                   })

        # Set ttl of session settings (expire this redis key 500 seconds after the session ends)
        redis.expire(f'session::{self.id}', self.timeToEnd().seconds + (500))

        # enqueue a job to close the session at the session end time
        scheduler.enqueue_in(timedelta(seconds=self.duration), closeSession,
                             self.id)

        print(f"Session created: {self.id}")
Esempio n. 2
0
def get_lock(key, timeout=10, user_wait_timeout=15):
    import time
    _lock, lock_key = 0, "%s_dynamic_lock" % key

    wait_timestamp = int(time.time()) + user_wait_timeout
    while _lock != 1:
        timestamp = int(time.time() + timeout)

        # 延时11秒
        _lock = redis.setnx(lock_key, timestamp)
        # 如果持有锁,当前时间大于过期时间,说明已经超时了
        if _lock == 1:
            redis.expire(lock_key, int(time.time()) + timeout)

            return 'success', lock_key

        lock_key_time = redis.get(lock_key)

        if lock_key_time:
            if int(time.time()) > int(lock_key_time):
                new_time = redis.getset(lock_key, int(time.time()) + timeout)
                if not new_time or lock_key_time == new_time:
                    redis.expire(lock_key, int(time.time()) + timeout)
                    return 'success', lock_key
            else:
                if int(time.time()) > wait_timestamp:
                    return 'timeout', lock_key
                time.sleep(0.1)

        else:
            if int(time.time()) > wait_timestamp:
                return 'timeout', lock_key

            time.sleep(0.3)
Esempio n. 3
0
def update_session(user_id, next_filter=None, **kwargs):
    if next_filter is not None:
        redis.hset(user_id, 'next_filter', next_filter)
    params = {k: v for k, v in kwargs.items() if k in FILTERS}
    if params:
        redis.hmset(user_id, params)
    redis.expire(user_id, app.config['EXPIRE'])
Esempio n. 4
0
def _check_code(uuid, code):
    if rd.hget(uuid, 'code').decode('utf8') != code:
        raise Forbidden('wrong captcha')
    rd.hmset(uuid, {
        'success': 1,
    })
    rd.expire(uuid, 60)
Esempio n. 5
0
def start_session(sender_id, message_text):
    # if 'hi' in message_text.lower():
    #     redis.set(sender_id, {'started_at': int(time.time())})
    #     send_text_message(sender_id, 'Hi! Nice to meet you!')
    # else:
    #     send_text_message(sender_id, 'Say hi!')
    redis.hmset(sender_id, {'started_at': int(time.time())})
    redis.expire(sender_id, 300)
    return process_city(sender_id, message_text)
Esempio n. 6
0
def count_online():
    when = int(time.time()) / PERIOD * PERIOD
    key = KEY.format(when)
    redis.expire(key, PERIOD * SAMPLES)
    total = 0
    for i in xrange(SAMPLES):
        key = 'online:{}'.format(when - (PERIOD * i))
        total += len(redis.smembers(key))
    total /= SAMPLES
    return total or 1
Esempio n. 7
0
def gen_id():  # 根据redis+snowflake生成自增分布式ID
    ms = int(datetime.now().timestamp() * 1000)
    seq_id = redis.incr(ms)
    redis.expire(ms, 2)
    seq_id = seq_id % 4096
    ms = ms << 17
    work_id = current_app.config["WORK_ID"]  # 只有容纳0-31台服务
    work_id = work_id << 12
    # 合并成long字长的整数
    ms += ms + work_id + seq_id
    return ms
Esempio n. 8
0
def get_mail_captcha_api():
    form = MailForm().validate_for_api()
    uuid = 'M-' + _generate_uuid()
    code = _generate_code()
    rd.hmset(uuid, {
        'code': code,
        'success': 0,
    })
    rd.expire(uuid, 3600)
    send_verification_mail(form.mail.data, code)
    return jsonify({'code': 0, 'data': {'uuid': uuid}})
Esempio n. 9
0
def get_image_captcha_api():
    uuid = 'I-' + _generate_uuid()
    code = _generate_code()
    rd.hmset(uuid, {
        'code': code,
        'success': 0,
    })
    rd.expire(uuid, 300)
    img = ImageCaptcha()
    image = img.generate_image(code)
    base64_str = _image_to_base64(image)
    return jsonify({'code': 0, 'data': {'image': base64_str, 'uuid': uuid}})
Esempio n. 10
0
def make_cache_rate(rates, providers):
    ts_now = datetime.datetime.now().timestamp()

    payload = {
        'time_stamp': str(ts_now),
        'rates': json.dumps(rates),
        'providers': json.dumps([provider.url for provider in providers])
    }
    redis.hmset('rate_ten_mins', payload)
    redis.expire('rate_ten_mins', 10 * 60)
    redis.hmset('daily_ ' + str(ts_now), payload)
    redis.expire('daily_ ' + str(ts_now), 60 * 60 * 24)
Esempio n. 11
0
 def addIPAddress(self, ip_address):
     """
     Add an IP address to the IP address list
     """
     self._data['ip_addresses'].add(ip_address)
     keyExists = True
     if redis.exists(f'session::{self.id}::ip_addresses') == 0:
         keyExists = False
     redis.sadd(f'session::{self.id}::ip_addresses', ip_address)
     if not keyExists:
         redis.expire(f'session::{self.id}::ip_addresses',
                      self.timeToEnd().seconds + (500))
Esempio n. 12
0
 def get(self):
     """ 获取/生成token """
     token = redis.get(self.token_id)
     if token:
         return jsonify({'token': token.decode('utf-8'), 'expiration': redis.ttl(self.token_id)})
     else:
         token = g.current_user.generate_auth_token(
             expiration=current_app.config['TOKEN_EXPIRATION'])
         redis.set(self.token_id, token)
         redis.expire(self.token_id, current_app.config['TOKEN_EXPIRATION'])
         return jsonify({
             'token': token,
             'expiration': current_app.config['TOKEN_EXPIRATION']
         })
Esempio n. 13
0
 def addPost(self, post):
     """
     Add a post to the post list
     """
     if self.isEnded():
         raise Exception('This session has ended.')
     self._data['posts'].append(post)
     keyExists = True
     if redis.exists(f'session::{self.id}::posts') == 0:
         keyExists = False
     redis.lpush(f'session::{self.id}::posts', post)
     if not keyExists:
         redis.expire(f'session::{self.id}::posts',
                      self.timeToEnd().seconds + (500))
Esempio n. 14
0
    def on_finish(self):
        if self.result:
            base_log = f"IP:{self.request.remote_ip},用户:{self.data['account']}"
            if self.result['status_code'] == 200:
                key = f"token:{self.result['data']['token']}"
                redis.hmset(key, {"url": self.data['url'], "account": self.data["account"]})
                redis.expire(key, 3600)

                # 获取用户信息
                user_client = self.school.get_auth_user(self.data['account'])['data']
                user_info = user_client.get_info()
                logger.info("%s,绑定成功:%s", base_log, user_info['real_name'])
                # TODO 保存用户信息
            else:
                logger.warning("%s,错误信息:%s", base_log, self.result['data'])
Esempio n. 15
0
def process_prompt(next_prompt, user_id, message_text):
    if next_prompt < len(PROMPTS):
        prompt = PROMPTS[next_prompt]
        value = prompt['formatter'](message_text)
        redis.hset(user_id, prompt['name'], value)
        redis.hset(user_id, 'next_prompt', next_prompt+1)
        redis.expire(user_id, app.config['EXPIRE'])
        if next_prompt < len(PROMPTS):
            send_text_message(user_id, PROMPT_GREETINGS[next_prompt+1])
        return

    res = book_a_table(redis.hget(user_id, 'id_rest'),
                 redis.hget(user_id, 'time'),
                 redis.hget(user_id, 'persons'),
                 redis.hget(user_id, 'firstName'),
                 redis.hget(user_id, 'phone'))
    send_text_message(user_id, str(res))
Esempio n. 16
0
    def post(self):
        json_data = data_json()

        email = json_data["email"]
        password = json_data["password"]
        user = User.query.filter_by(email=email).first()
        if (user.verify_password(password)):
            if (redis.hexists(email, "field1")):
                token = redis.hget(email, "field1")
                return jsonify({"token": token})
            min_expire_token = 25
            number_bytes = 256
            token = token_urlsafe(number_bytes)
            redis.hset(email, "field1", token)
            redis.expire(email, 60 * min_expire_token)
            return jsonify({"token": token})
        else:
            return jsonify({"error": "password dont check"}), 400
Esempio n. 17
0
        def wrapper(*args, **kwargs):
            key = "{0}: {1}".format(request.remote_addr, request.path)

            try:
                remaining = limit - int(redis.get(key))
            except (ValueError, TypeError):
                remaining = limit
                redis.set(key, 0)

            expires_in = redis.ttl(key)
            if not expires_in:
                redis.expire(key, window)
                expires_in = window

            g.rate_limits = (limit, remaining-1, time()+expires_in)

            if remaining > 0:
                redis.incr(key, 1)
                return func(*args, **kwargs)
            return TOO_MANY_REQUESTS
        def wrapper(*args, **kwargs):
            key = "{0}: {1}".format(request.remote_addr, request.path)

            try:
                remaining = limit - int(redis.get(key))
            except (ValueError, TypeError):
                remaining = limit
                redis.set(key, 0)

            expires_in = redis.ttl(key)
            if not expires_in:
                redis.expire(key, window)
                expires_in = window

            g.rate_limits = (limit, remaining-1, time()+expires_in)

            if remaining > 0:
                redis.incr(key, 1)
                return func(*args, **kwargs)
            return TOO_MANY_REQUESTS
Esempio n. 19
0
    def addEmail(self, email):
        """
        Add email to email list, emails on this list will be sent a message with the final results
        """
        # Don't allow modifications to data after the session has ended
        if self.isEnded():
            raise Exception('This session has ended.')

        # Force emails to lowercase
        email = email.lower()

        # Add email address to this session's email set
        self._data['emails'].add(email)

        # Save to redis
        keyExists = True
        if redis.exists(f'session::{self.id}::emails') == 0:
            keyExists = False
        redis.sadd(f'session::{self.id}::emails', email)
        ## set ttl on the key if it was just created
        if not keyExists:
            redis.expire(f'session::{self.id}::emails',
                         self.timeToEnd().seconds + (500))
Esempio n. 20
0
def product(id):
    product = Product.query.get_or_404(id)
    product_key = "product-%s" % product.id
    redis.set(product_key, product.name)
    redis.expire(product_key, 180)
    return render_template("catalog/product.html", product=product)
Esempio n. 21
0
def start_prompt_user(sender_id, id_rest):
    redis.hset(sender_id, 'next_prompt', 0)
    redis.hset(sender_id, 'ready', 1)
    redis.hset(sender_id, 'id_rest', id_rest)
    redis.expire(sender_id, app.config['EXPIRE'])
    send_text_message(sender_id, PROMPT_GREETINGS[0])
Esempio n. 22
0
def do_payment(pending_id):
    # Create locked celery job (using redis) to send payment
    k = "do_payment:%s" % pending_id
    if redis.setnx(k, 1):
        redis.expire(k, LOCK_EXPIRE)
        pending = PendingTransaction.query.get(pending_id)
        # Only do the task if signed is not completed already
        if pending.tx_signed is False:
            r = tx_sign(pending.destination, pending.amount, pending.sequence)
            if r['result']['status'] == 'success' and 'tx_blob' in r['result']:
                # Signing was successful
                pending.tx_blob = r['result']['tx_blob']
                pending.tx_hash = r['result']['tx_json']['hash']
                pending.tx_signed = True
                db.session.add(pending)
                db.session.commit()
                # Also save info to Payable
                payable = Payable.query.get(pending.payable)
                payable.tx_blob = pending.tx_blob
                payable.tx_hash = pending.tx_hash
                payable.tx_signed = pending.tx_signed
                db.session.add(payable)
                db.session.commit()
        if pending.tx_signed is True and pending.tx_submitted is False:
            # Check if tx has already been submitted successfully
            verify = verify_tx(pending.tx_hash)
            if verify['result']['status'] == 'success' and 'validated' in r['result']:
                if verify['result']['validated'] is True:
                    pending.tx_submitted = True
                    db.session.add(pending)
                    db.session.commit()
            else:
                r = submit_tx_blob(pending.tx_blob)
                if r['result']['status'] == 'success':
                    if r['result']['engine_result_code'] == 0:
                        # payment was successful
                        tx = r['result']['tx_json']
                        pending.tx_submitted = True
                        db.session.add(pending)
                        db.session.commit()
                        payable = Payable.query.get(pending.payable)
                        payable.tx_submitted = True
                        db.session.add(payable)
                        db.session.commit()
        if pending.tx_signed is True and pending.tx_submitted is True and pending.tx_validated is False:
            # Verify tx was confirmed and validated
            r = verify_tx(pending.tx_hash)
            if r['result']['status'] == 'success' and 'validated' in r['result']:
                if r['result']['validated'] is True:
                    # tx has been confirmed
                    tx = r['result']
                    payable = Payable.query.get(pending.payable)
                    payable.tx_validated = True
                    payable.account_fulfilled = tx['Account']
                    payable.amount_fulfilled = tx['Amount']
                    payable.destination_fulfilled = tx['Destination']
                    payable.fee_fulfilled = tx['Fee']
                    payable.flags_fulfilled = tx['Flags']
                    payable.sequence_fulfilled = tx['Sequence']
                    payable.signing_pub_key_fulfilled = tx['SigningPubKey']
                    payable.transaction_type_fulfilled = tx['TransactionType']
                    payable.tx_signature_fulfilled = tx['TxnSignature']
                    payable.tx_hash_fulfilled = tx['hash']
                    payable.ledger_index_fulfilled = tx['ledger_index']
                    db.session.add(payable)
                    db.session.commit()
                    db.session.delete(pending)
                    db.session.commit()
            else:
                # Validation typically takes 5 seconds to confirm
                # celery retry is bugging out the redis lock release
                pass

        if pending.tx_signed is True and pending.tx_submitted is True and pending.tx_validated is True:
            # If all 3 conditions are true, the pending entry should be deleted
            db.session.delete(pending)
            db.session.commit()

        # Release the redis lock after we're done working on it
        redis.delete(k)
    else:
        # The payment is redis locked
        print "Aborting: the payment is currently locked."