def test_redirect_by_link_success(self): full_link = self.long_link redis.incr('linked_id') counter = int(redis.get('linked_id')) short_link = comp.compress_url(counter) redis.set(short_link, full_link, nx=True) short_link = 'http://0.0.0.0:5000/' + short_link response = self.client.get(short_link) assert response.status_code == 308
def new(): if request.method == 'GET': return render_template('blog/new.html') title = request.form['title'] content = request.form['content'] tags = request.form['tags'] post_id = redis.incr('post:post-id') pipe = redis.pipeline() pipe.hmset( 'post:%s' % post_id, { "id": post_id, "title": title, "content": content, "content_markdown": markdown2.markdown(content, extras=['fenced-code-blocks']), "tags": tags }) for tag in tags.split(','): pipe.sadd('post:post-tags:%s' % tag.strip(), post_id) pipe.lpush('post:post-list', post_id) pipe.execute() return redirect(url_for('.detail', post_id=post_id))
def user_message(message): room_id = message['room_id'] message_time = int(message['message_time']) content = message['content'] nick_name = session[room_id] serial_number = redis.incr(room_id + ':message_num') message = { 'uid': session['uid'], 'nick_name': nick_name, 'message_time': message_time, 'serial_number': serial_number, 'content': content } db.session.add( Message(message_time=message_time, serial_number=serial_number, content=content, uid=session['uid'], nick_name=nick_name, room_id=room_id)) db.session.commit() print '###########' print message emit('user message', message, room=room_id)
def user_message(message): room_id = message['room_id'] message_time = int(message['message_time']) content = message['content'] nick_name = session[room_id] serial_number = redis.incr(room_id + ':message_num') message = { 'uid': session['uid'], 'nick_name': nick_name, 'message_time': message_time, 'serial_number': serial_number, 'content': content } db.session.add( Message( message_time=message_time, serial_number=serial_number, content=content, uid=session['uid'], nick_name=nick_name, room_id=room_id ) ) db.session.commit() print '###########' print message emit('user message', message, room=room_id)
def new(): if request.method == 'GET': return render_template('blog/new.html') title = request.form['title'] content = request.form['content'] tags = request.form['tags'] post_id = redis.incr('post:post-id') pipe = redis.pipeline() pipe.hmset('post:%s' % post_id, { "id": post_id, "title": title, "content": content, "content_markdown": markdown2.markdown(content, extras=['fenced-code-blocks']), "tags": tags }) for tag in tags.split(','): pipe.sadd('post:post-tags:%s' % tag.strip(), post_id) pipe.lpush('post:post-list', post_id) pipe.execute() return redirect(url_for('.detail', post_id=post_id))
def index(): posts = [{ 'author': { 'username': '******' }, 'body': 'Beautiful day in Portland!' }, { 'author': { 'username': '******' }, 'body': 'The Avengers movie was so cool!' }] redis.incr('hits') return render_template('index.html', title='Home', posts=posts, hits=redis.get('hits').decode('utf-8'))
def get_sqh(sq_type): """ 获取申请号 :sq_type 申请号的类型 JC LIS 等 :return: """ s = redis.incr('docking:sqh:{}'.format(sq_type)) return '{}{:08d}'.format(sq_type, int(s))
def get_ticket(imdbId, season='', episode=''): redisRes = redis.get(imdbId) ticket = redisRes.decode("utf-8") if redisRes else None if not ticket: ticket = req(imdbId) else: ticketUsage = redis.get(ticket) ticketUsage = int(ticketUsage) if ticketUsage else 0 # ticket as 50 usage if ticketUsage >= 49: redis.delete(ticket) ticket = req(imdbId) else: redis.incr(ticket) return str(ticket)
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 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
def hello(): try: visits = redis.incr("counter") except RedisError: visits = "<i>cannot connect to Redis, counter disabled</i>" html = "<h3>Hello {name}!</h3>" \ "<b>Hostname:</b> {hostname}<br/>" \ "<b>Visits:</b> {visits}" return html.format(name=os.getenv("NAME", "world"), hostname=socket.gethostname(), visits=visits)
def create_short_link(): """ post: create short link get: show short link if previous request was post short link """ full_link, short_link = None, None if request.method == 'POST': if not re.match(regex, request.form['full_link']): abort(400, 'Link is broken') full_link = request.form['full_link'] redis.incr('linked_id') counter = int(redis.get('linked_id')) short_link = comp.compress_url(counter) redis.set(short_link, full_link, nx=True) short_link = request.url + short_link app.logger.info(f'create short link: {short_link}') return render_template('main.html', context={ 'full_link': full_link, 'short_link': short_link })
def send_welcome_email(key): with app.app_context(): redis.incr(key) print "Welcome!!!"
def _gen_id(): """ generate incremental id for every call """ return str(redis.incr('next_id'))
def decorator(*args, **kwargs): redis.incr('blog_explore_count') return func(*args, **kwargs)
def handle_stellar_message(message): # What to do when we receive a message # Check it is of transaction type m = json.loads(message) if m['type'] == 'transaction': if m['transaction']['Destination'] == STELLAR_ADDRESS and m['transaction']['TransactionType'] == 'Payment' and m['validated'] is True and m['engine_result_code'] == 0: # Check with stellar to make sure tx is legit tx_hash = m['transaction']['hash'] ledger_index = m['ledger_index'] r = verify_tx(tx_hash, ledger_index) if r['result']['status'] == 'success': # Check tx type and destination address tx = r['result']['tx_json'] if 'ledger_index' in tx and tx['TransactionType'] == 'Payment' and tx['Destination'] == STELLAR_ADDRESS: # tx has been verified, add to database sender_address = tx['Account'] sender = SendbackAccount.query.filter_by(stellar_address=sender_address).first() if sender is None: sender_id = None else: sender_id = sender.id # Handle payments without destination tags if 'DestinationTag' in tx: dt = tx['DestinationTag'] else: dt = None sendback = SendbackTransaction( created_time=datetime.utcnow(), sendback_account=sender_id, account_sender=sender_address, amount_sender=tx['Amount'], destination_sender=tx['Destination'], destination_tag_sender=dt, fee_sender=tx['Fee'], flags_sender=tx['Flags'], sequence_sender=tx['Sequence'], signing_pub_key_sender=tx['SigningPubKey'], tx_signature_sender=tx['TxnSignature'], tx_hash_sender=tx['hash'], ledger_index_sender=tx['ledger_index'] ) db.session.add(sendback) db.session.commit() # Create new Payable amount_owed = sendback.amount_sender - calculate_fee(sendback.amount_sender) dest = sendback.account_sender payable = Payable( created_time=datetime.utcnow(), destination=dest, amount=amount_owed, sendback_transaction=sendback.id, sendback_account=sender_id, tx_signed=False, tx_submitted=False, tx_validated=False ) db.session.add(payable) db.session.commit() seq = redis.get('Sequence') redis.incr('Sequence') pending = PendingTransaction( payable=payable.id, destination=payable.destination, amount=payable.amount, created_time=datetime.utcnow(), tx_signed=False, tx_submitted=False, tx_validated=False, sequence=seq ) db.session.add(pending) db.session.commit() do_payment.delay(pending.id)