def get_areas(): '''获取地区 使用redis缓存数据库 访问redis 如果redis中没有就访问mysql,再把数据存入redis ''' areas = [] # 查询redis try: if redis_store.get('areas'): # 转成列表 areas = json.loads(redis_store.get('areas')) return jsonify(errno=RET.OK, errmsg='ok', data=areas) except Exception as e: logging.error(e) return jsonify(errno=RET.DBERR, errmsg='数据错误') # 查询mysql try: areas_list = Area.query.all() except Exception as e: logging.error(e) return jsonify(errno=RET.DBERR, errmsg='数据错误') for area in areas_list: areas.append(area.to_dict()) # 转成字符串存入 redis try: redis_store.setex("areas", constants.AreasTime, json.dumps(areas)) except Exception as e: logging.error(e) return jsonify(errno=RET.OK, errmsg='ok', data=areas)
def warn_about_daily_message_limit(service, messages_sent): nearing_daily_message_limit = messages_sent >= NEAR_DAILY_LIMIT_PERCENTAGE * service.message_limit over_daily_message_limit = messages_sent >= service.message_limit current_time = datetime.utcnow().isoformat() cache_expiration = int(timedelta(days=1).total_seconds()) # Send a warning when reaching 80% of the daily limit if nearing_daily_message_limit: cache_key = near_daily_limit_cache_key(service.id) if not redis_store.get(cache_key): redis_store.set(cache_key, current_time, ex=cache_expiration) send_notification_to_service_users( service_id=service.id, template_id=current_app.config["NEAR_DAILY_LIMIT_TEMPLATE_ID"], personalisation={ "service_name": service.name, "contact_url": f"{current_app.config['ADMIN_BASE_URL']}/contact", "message_limit_en": "{:,}".format(service.message_limit), "message_limit_fr": "{:,}".format(service.message_limit).replace(",", " "), }, include_user_fields=["name"], ) # Send a warning when reaching the daily message limit if over_daily_message_limit: cache_key = over_daily_limit_cache_key(service.id) if not redis_store.get(cache_key): redis_store.set(cache_key, current_time, ex=cache_expiration) send_notification_to_service_users( service_id=service.id, template_id=current_app. config["REACHED_DAILY_LIMIT_TEMPLATE_ID"], personalisation={ "service_name": service.name, "contact_url": f"{current_app.config['ADMIN_BASE_URL']}/contact", "message_limit_en": "{:,}".format(service.message_limit), "message_limit_fr": "{:,}".format(service.message_limit).replace(",", " "), }, include_user_fields=["name"], ) current_app.logger.info( "service {} has been rate limited for daily use sent {} limit {}". format(service.id, int(messages_sent), service.message_limit)) if service.restricted: raise TrialServiceTooManyRequestsError(service.message_limit) else: raise LiveServiceTooManyRequestsError(service.message_limit)
def collection_count(): return jsonify( { "matches": redis_store.get("match_count") or 0, "players": redis_store.get("player_count") or 0, "success": redis_store.get("api_success") or 0, "failure": redis_store.get("api_failure") or 0, "daily": redis_store.get("api_daily") or 0, } )
def douban_items(): # 分虚构类和非虚构类通过`subcat` query string判断 默认虚构类 data = redis_store.lrange('douban_book_fiction:data', 0, -1) timestamp = redis_store.get('douban_book_fiction:timestamp') if request.args.get('subcat', None) == 'I': data = redis_store.lrange('douban_book_non_fiction:data', 0, -1) timestamp = redis_store.get('douban_book_non_fiction:timestamp') return jsonify({ 'update_timestamp': timestamp.decode('utf-8'), 'data': [json.loads(d.decode('utf-8')) for d in data] })
def render_scoreboard(): users = [u for u in user_logins if u not in hidden_users] scores = [] for login in users: try: score = int(redis_store.get(login + ':score') or 0) coins = int(redis_store.get(login + ':coins') or 0) name = redis_store.get(login + ':name').decode() except: continue scores.append((score, coins, name)) scores.sort(key=lambda x: (-x[0], -x[1], x[2])) return scores
def getIncEntityID(eventName): ID = redis_store.get(eventName + '.entityID') if ID is None: redis_store.set(eventName + '.entityID', 1) ID = 1 redis_store.incr(eventName + '.entityID') return int(ID)
def check_image_captcha(): """ 校验图片验证码是否正确 :return: """ try: image_captcha = request.form.get("image_captcha") image_code_id = request.form.get("image_code_id") if not image_captcha: return jsonify(status=RET.PARAMERR, errmsg="请输入验证码") flag_captcha = redis_store.get("image_code:%s" % image_code_id).decode() if flag_captcha == image_captcha: return jsonify(status=RET.OK, errmsg="成功") else: return jsonify(status=RET.DATAERR, errmsg="验证码错误,请重新输入") except Exception as e: current_app.logger.error(e) return jsonify(status=RET.SERVERERR, errmsg="数据异常,请联系管理员")
def wrapped(*args, **kw): # 存入redis的key key = ":".join(["ratelimit", by()]) # 获取单位时间内剩余的请求次数 try: remaining = requests - int(redis_store.get(key)) except (ValueError, TypeError): remaining = requests redis_store.set(key, 0) # 获取剩余单位时间周期的时间(秒) ttl = redis_store.ttl(key) if ttl < 0: # 已过期,则设置过期时间(ttl = -2, ttl = -1) redis_store.expire(key, window) ttl = window # 将rate limites情况写入g g.view_limits = (requests, remaining - 1, time.time() + ttl) if remaining > 0: # 剩余请求次数>0,则redis记录+1,并进入后续处理 redis_store.incr(key, 1) # 未达到限制次数,记录到g,方便dispatch处理 g.status_code = 200 return func(*args, **kw) else: # return make_response('Too Many Requests', 429) # 这里无法直接返回429,而是记录到g.status_code, 方便dispatch处理 g.status_code = 429 return func(*args, **kw)
def send_find_password_sms(): req_dict = request.get_json() phone = req_dict.get("phone") phone = str(phone) # 判断对于这个手机号的操作,在60秒内有没有之前的记录,如果有,则认为用户操作频繁,不接受处理 try: send_flag = redis_store.get("send_sms_code_%s" % phone) except Exception as e: print(e) else: if send_flag is not None: # 表示在60秒内之前有过发送的记录 return jsonify(code=4001, msg="请求过于频繁,请60秒后重试") # 判断账号是否存在 try: user = User.query.filter_by(phone=phone).first() except Exception as e: current_app.logger.error(e) else: if user is None or not user.is_normal(): # 账号不存在 return jsonify(code=4002, msg="账号不存在或账号异常!") # 如果账号存在且正常 发送验证码 return send_sms_origin(phone=phone)
def check_service_over_daily_message_limit(key_type, service): if key_type != KEY_TYPE_TEST: if current_app.config['REDIS_ENABLED']: cache_key = daily_limit_cache_key(service.id) service_stats = redis_store.get(cache_key) if not service_stats: service_stats = services_dao.fetch_todays_total_message_count( service.id) redis_store.set(cache_key, service_stats, ex=3600) if int(service_stats) >= service.message_limit: current_app.logger.error( "service {} has been rate limited for daily use sent {} limit {}" .format(service.id, int(service_stats), service.message_limit)) raise TooManyRequestsError(service.message_limit) return # TODO: remove this block when redis is re-enabled in live service_stats = services_dao.fetch_todays_total_message_count( service.id) if int(service_stats) >= service.message_limit: current_app.logger.error( "service {} has been rate limited for daily use sent {} limit {}" .format(service.id, int(service_stats), service.message_limit)) raise TooManyRequestsError(service.message_limit)
def is_door_opened(login, x, y): if ('%d,%d' % (x, y)) not in level['doors']: return True prob_id = level['doors'].get('%d,%d' % (x, y)) if redis_store.get(login + ':solved:' + str(prob_id)): return True return False
def record_name(name): # 检查是否访问过 result = redis_store.get(name) if result is not None: return True redis_store.set(name, 1, 86400) return False
def scheduler_redis_job(): #print('Redis_job: updating data in redis DB') logger.info('Redis_job: updating data in redis DB') database_lxdservers_list = redis_store.keys('servers:*') #print(database_lxdservers_list) for serverkey in database_lxdservers_list: lxdserver = json.loads(redis_store.get(serverkey)) all = [] try: res = lxd_api_get_scheduler(lxdserver, 'instances') for c in res.json()['metadata']: all.append(c[15:]) # get instance name from api url except Exception as e: print(e) #print(all) if len(all) > 0: for c in all: res = lxd_api_get_scheduler(lxdserver, 'instances/' + c) redis_store.set( 'server:' + lxdserver['name'] + ':instance:' + c + ':info', json.dumps(res.json()['metadata'])) # print(res.json()['metadata']) res_state = lxd_api_get_scheduler(lxdserver, 'instances/' + c + '/state') redis_store.set( 'server:' + lxdserver['name'] + ':instance:' + c + ':state', json.dumps(res_state.json()['metadata']))
def send_sms(): req_json = request.get_json() phone = req_json.get("phone") if not all([phone]): # 表示参数不完整 return jsonify(code=4000, msg="参数不完整") # 判断对于这个手机号的操作,在60秒内有没有之前的记录,如果有,则认为用户操作频繁,不接受处理 try: send_flag = redis_store.get("send_sms_code_%s" % phone) except Exception as e: print(e) else: if send_flag is not None: # 表示在60秒内之前有过发送的记录 return jsonify(code=4001, msg="请求过于频繁,请60秒后重试") # 判断手机号是否存在 try: user = User.query.filter_by(phone=phone).first() except Exception as e: current_app.logger.error(e) else: if user is not None: # 表示手机号已存在 return jsonify(code=4002, msg="手机号已存在") return send_sms_origin(phone)
def get_areas_info(): """ 查询城区信息 :return: """ # 0.先从缓存中去取,如果缓存中没有,再去数据库中取 try: areas = redis_store.get('area_info') except Exception as e: logging.error(e) areas = None # 0.1 如果不为空,做查询操作 if areas and len(re.findall(r'aid', areas)) > 0: return jsonify(errno=RET.OK, errmsg='获取成功', data=eval(areas)) # 1.查询数据库 try: areas = Area.query.all() except Exception as e: logging.error(e) return jsonify(errno=RET.DBERR, errmsg='获取城区信息失败') # 2.组成字典,以便json areas_list = [] for area in areas: areas_list.append(area.to_dict()) # 0.2 存储json_areas数据到redis缓存中 try: redis_store.set('area_info', areas_list, constants.AREA_INFO_REDIS_EXPIRES) except Exception as e: logging.error(e) # 3. 返回数据 return jsonify(errno=RET.OK, errmsg='获取成功', data=areas_list)
def test(): a = 'abc' redis_store.set('aa', a) b = redis_store.get('aa') #job.delay(1, 2) #c = current_app.config['TEST'] return str(c)
def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] captcha = request.form['captcha'] # 接收前端提交过来的验证码 image_code_id = request.form[ 'image_code_id'] # 接收前端提交过来的 image_code_id real_image_code = str( redis_store.get('ImageCode_' + image_code_id)) # 把image_code_id转成字符串,然后存入redis # print(real_image_code.lower()) # print(captcha.lower()) # 验证码验证 if real_image_code.lower() != captcha.lower(): flash('图片验证码不一致') return redirect(request.referrer) user = User.query.filter_by(username=username).first() if user is None or not user.check_password(password): flash('用户名或密码输入错误') return redirect(request.referrer) session['user'] = user return redirect('/admin') return render_template('admin/user/login.html')
def register(): """ 1. 获取参数 2. 判断是否为空 3. 获取redis保存的短信验证码 4. 验证对比,并删除验证码 5. 将用户数据保存到数据库,并缓存到Session 6. 返回用户信息 :return: """ # 1.获取参数 手机号 密码 短信验证码 dict_json = request.get_json() if not dict_json: return jsonify(errno=RET.PARAMERR, errmsg='参数不完整') mobile = dict_json['mobile'] sms_code = dict_json['phonecode'] password = dict_json['password'] # 2. 判断是否参数为空 if not all([mobile, sms_code, password]): return jsonify(errno=RET.PARAMERR, errmsg='参数不完整') # 3.获取redis中保存的短信验证码 try: real_sms_code = redis_store.get('SMSCode_' + mobile) except Exception as e: logging.error(e) return jsonify(errno=RET.DBERR, errmsg='短信验证码读取异常') if not real_sms_code: return jsonify(errno=RET.DATAERR, errmsg='短信验证码已过期') # 4. 验证对比,并删除验证码 if real_sms_code != str(sms_code): return jsonify(errno=RET.DATAERR, errmsg='短信验证码无效') # 删除短信验证码 try: redis_store.delete('SMSCode_' + mobile) except Exception as e: logging.error(e) # 5. 将用户数据保存到数据库 new_user = User(mobile=mobile, name=mobile) new_user.password = password try: db.session.add(new_user) db.session.commit() except Exception as e: logging.error(e) db.session.rollback() return jsonify(errno=RET.DATAEXIST, errmsg='手机号已存在') # 缓存到session session['user_id'] = new_user.id session['mobile'] = mobile session['name'] = mobile # 返回用户信息 return jsonify(errno=RET.OK, errmsg='OK')
def get_list(page, force_reload=False): list_cache = redis_store.get(redis_plugin_prefix) if list_cache and force_reload is False: cache_list = pickle.loads(list_cache) else: cache_list = update_cache() return cache_list
def confirm_role_details(): redis_store.set('roles_seen', 0) if request.method == 'POST': redis_store.hmset('contact', request.form.to_dict()) data = { 'role': { 'caption': 'Role details', 'row_data': redis_store.hgetall('role') }, 'logistics': { 'caption': 'Logistical details', 'row_data': redis_store.hgetall('logistics') }, 'security': { 'caption': 'Security details', 'row_data': redis_store.hgetall('security') } } skills = redis_store.lrange('skills', 0, -1) for s in skills: skill_data = { 'row_data': json.loads(redis_store.get(s)), 'caption': s } data[s] = skill_data return render_template('submit/confirm-role-details.html', data=data)
def result(): res = [(key, redis_store.get(key)) for key in current_app.candidates] print(res, flush=True) return '<br>'.join( map( lambda x: current_app.candidates[x[0]] + ': ' + (x[1].decode('utf-8') if x[1] else '0'), res))
def get_(self): """ 获取聊天记录,建议保存到缓存数据库中,以用户的聊天为ID为ID """ # 从缓存数据库获取聊天记录,根据ID + 产生时间为key # '1-add_time' = {'message': 消息内容, 'add_time': '添加时间', 'user_id': '发送的用户ID'} print('获取数据:', self.request_data) chat_id = self.request_data.get('chat_id') chat = self.check_chat(chat_id) if not chat: return # 如果chat.type为1,则是单聊,取chat_user_touser_* if chat.type == 1: user_to_user = '******'.join( sorted([str(chat.user_id), str(chat.chat_obj_id)])) chat_keys = redis_store.keys('chat_%s_*' % user_to_user) # 否则为群组聊天,取chat_group_groupid else: chat_keys = redis_store.keys('chat_group_%s_*' % chat.chat_obj_id) chat_keys.sort() print('---------输出聊天keys和记录-------------------------') print(chat_keys) data_list = [] for chat_key in chat_keys: message = redis_store.get(chat_key) try: data_list.append(eval(message)) except Exception as e: continue print(data_list) print('-------------end-----------------------') self.result = success(data=data_list)
def segmentfault_items(): data = redis_store.lrange('segmentfault:data', 0, -1) timestamp = redis_store.get('segmentfault:timestamp') return jsonify({ 'update_timestamp': timestamp.decode('utf-8'), 'data': [json.loads(d.decode('utf-8')) for d in data] })
def get_session(force=False): session = None if not force: session = redis_store.get(REDIS_KEY) if session: return session.decode() try: session = subprocess.check_output([ EJUDGE_CONTESTS_CMD_PATH, str(EJUDGE_CONTEST_ID), "master-login", "STDOUT", EJUDGE_USER_LOGIN, EJUDGE_USER_PASSWORD ]) session = session.strip() except: return None if not session: return None redis_store.set(REDIS_KEY, session) redis_store.expire(REDIS_KEY, TTL) return session.decode()
def io_map_send(): login = session['user'] try: x = int(redis_store.get(login + ':player.x')) y = int(redis_store.get(login + ':player.y')) visible = msgpack.loads(redis_store.get(login + ':visible')) coins = int(redis_store.get(login + ':coins')) except: return data = copy.deepcopy(level) data['player']['x'] = x data['player']['y'] = y data['coins'] = coins data['ghosts'] = {} for k in user_logins: if k in hidden_users: continue try: px = int(redis_store.get(k + ':player.x')) py = int(redis_store.get(k + ':player.y')) except: continue data['ghosts'][k] = {'x': px, 'y': py} for door in level['doors']: if redis_store.get(login + ':solved:' + str(level['doors'][door])): data['doors'][door] = -1 for i in range(level['width']): for j in range(level['height']): if level['level'][j][i] == '$': if is_coin_picked(i, j): data['level'][j][i] = ' ' emit('map.recv', msgpack.dumps(data)) if update_visible(visible, x, y, True): redis_store.set(login + ':visible', msgpack.dumps(visible)) emit('map.visible', msgpack.dumps(visible))
def check_service_message_limit(key_type, service): if key_type != KEY_TYPE_TEST: cache_key = redis.daily_limit_cache_key(service.id) service_stats = redis_store.get(cache_key) if not service_stats: service_stats = services_dao.fetch_todays_total_message_count(service.id) redis_store.set(cache_key, service_stats, ex=3600) if int(service_stats) >= service.message_limit: raise TooManyRequestsError(service.message_limit)
def get_cookie(): one_time_code = request.form.get("one_time_code") valid = redis_store.get(one_time_code) if valid and redis_store.hget(valid, "uuid"): session["logged_in"] = True session["username"] = valid redis_store.set(valid + ":logged_in", True) return "successful login" return "failed"
def get_access_token(): access_token = redis_store.get('access_token') if access_token: return jsonify(errno=0, errmsg="OK", token=access_token) else: obj = AccessToken() access_token = obj.get_access_token() redis_store.setex('access_token', 7200, access_token) return jsonify(errno=0, errmsg="OK", token=access_token)
def autocomplete_cities(): """Autocomplete for cities.""" query = request.args.get("query") redis_key = f"autocomplete_cities|{query}" # Try to find with Redis. try: result = redis_store.get(redis_key) redis_is_connected = True if result: return jsonify(suggestions=pickle.loads(result)) except RedisConnectionError: redis_is_connected = False # Try to find with Elasticsearch. try: cities = es.search( index="airtickets-city-index", from_=0, size=10, doc_type="CityName", body={ "query": { "bool": { "must": { "match_phrase_prefix": { "value": { "query": query } } } } }, "sort": { "population": { "order": "desc" } }, }, ) result = [city["_source"] for city in cities["hits"]["hits"]] except (ElasticConnectionError, NotFoundError, AttributeError): # Try to find with PostgreSQL. cities = (CityName.query.join( City.city).filter(CityName.name.like(query + "%")).distinct( City.population, CityName.city_id).order_by(City.population.desc(), CityName.city_id).limit(10).all()) result = [city.autocomplete_serialize() for city in cities] if redis_is_connected: redis_store.set(redis_key, pickle.dumps(result), 86400) return jsonify(suggestions=result)
def wechatView(): TOKEN = current_app.config['TOKEN'] EncodingAESKey = current_app.config['EA'] AppId = current_app.config['APPID'] Raw = current_app.config['RAW'] signature = request.args.get('signature', '') timestamp = request.args.get('timestamp', '') nonce = request.args.get('nonce', '') echo_str = request.args.get('echostr', '') encrypt_type = request.args.get('encrypt_type', '') msg_signature = request.args.get('msg_signature', '') print('signature:', signature) print('timestamp: ', timestamp) print('nonce:', nonce) print('echo_str:', echo_str) print('encrypt_type:', encrypt_type) print('msg_signature:', msg_signature) try: check_signature(TOKEN, signature, timestamp, nonce) except InvalidSignatureException: abort(403) if request.method == 'GET': return echo_str else: if Raw: print('Raw message: \n%s' % request.data) crypto = WeChatCrypto(TOKEN, EncodingAESKey, AppId) try: msg = crypto.decrypt_message(request.data, msg_signature, timestamp, nonce) print('Descypted message: \n%s' % msg) except (InvalidSignatureException, InvalidAppIdException): abort(403) else: msg = request.data msg = parse_message(msg) print('request data:\n%s' % msg) if msg.type == 'text': if msg.content == 'ip': reply = create_reply(redis_store.get('pi_ip'), msg) else: reply = create_reply(msg.content, msg) elif msg.type == 'voice': reply = create_reply('voice msg', msg) else: reply = create_reply('Sorry, can not handle this for now', msg) if Raw: return crypto.encrypt_message(reply.render(), nonce, timestamp) else: return reply.render()
def get_last_crawled_eth_block_height(): key = "%s_last_crawled_eth_block_height" % config_model height = redis_store.get(key) if height is not None: try: return int(height) except Exception as _: return None else: return None
def sms_code(): """ 获取手机验证码 :return: """ try: dist_data = request.json if dist_data is None: return jsonify(status=RET.REQERR, errmsg="非法请求或请求次数受限") mobile = dist_data.get("mobile") image_code = dist_data.get("image_code") image_code_id = dist_data.get("image_code_id") if not mobile: return jsonify(status=RET.PARAMERR, errmsg="手机号为空") if not image_code: return jsonify(status=RET.PARAMERR, errmsg="图片验证码为空") if not image_code_id: return jsonify(status=RET.PARAMERR, errmsg="图片ID为空") if not common.check_mobile(mobile): return jsonify(status=RET.DATAERR, errmsg="手机号的格式错误") redis_img_code = redis_store.get("image_code:%s" % image_code_id) if redis_img_code is None: return jsonify(status=RET.DBERR, errmsg="数据错误,请联系管理员") if image_code.lower() != redis_img_code.lower().decode(): return jsonify(status=RET.DATAERR, errmsg="图片验证码填写错误") flag = redis_store.delete("image_code:%s" % image_code_id) if not flag: return jsonify(status=RET.DBERR, errmsg="操作数据库失败") # 生成一个随机短信验证码,判断验证码是否发送成功 verity_code = "%06d" % random.randint(0, 999999) if verity_code: redis_flag = redis_store.set("sms_code:%s" % mobile, verity_code, constants.SMS_CODE_REDIS_EXPIRES) print(verity_code) if redis_flag is False: return jsonify(status=RET.DBERR, errmsg="图片验证码保存到redis失败") # 10. 返回响应 return jsonify(status=RET.OK, errmsg="短信发送成功") except Exception as e: current_app.logger.error(e) return jsonify(status=RET.DBERR, errmsg="删除redis图片验证码失败")
def post(self): """ 用户认证 :return: """ # 获取前端传参 req_data = request.get_json() username = req_data.get("username") password = req_data.get("password") # 判断数据是否为空 if not all([username, password]): return jsonify(code=RET.NODATA, codemsg="Username or Passowrd is None.") try: # 按用户查找数据是否存在 User_Data = Users_Models.query.filter_by(username=username).first() token = Users_Models.generate_auth_token(User_Data) except (IntegrityError, AttributeError) as e: current_app.logger.error(e) return jsonify(code=RET.NODATA, codemsg="User Data No Exist.") except Exception as e: current_app.logger.error(e) return jsonify(code=RET.DBERR, codemsg="Database Error.") try: # 从redis获取用户错误次数 Access_Nums = redis_store.get("access_login_error_number_%s" % username) except Exception as e: current_app.logger.error(e) else: # 判断redis访问错误是否为空或是否大于限制。 if Access_Nums is not None and int( Access_Nums) >= LOGIN_ERROR_MAX_TIMES: return jsonify(code=RET.REQERR, codemsg="Login errors are excessive.") # 判断用户是否存在或密码是否正确。 if User_Data is None or not User_Data.check_password(password): try: # 如果检测失败则保存信息到redis中,expire设置错误信息有效期 redis_store.incr("access_login_error_number_%s" % username) redis_store.expire("access_login_error_number_%s" % username, LOGIN_ERROR_FORBID_TIME) except Exception as e: current_app.logger.error(e) return jsonify(code=RET.DATAERR, codemsg="User or Password Auth Error.") return jsonify(code=RET.OK, codemsg="Succeed.", token=token)
def authenticate(): username = request.form.get("username") uuid = request.form.get("uuid") one_time_code = request.form.get("one_time_code") if not (username and uuid and one_time_code): return "ERROR - INVALID INFO" key = redis_store.get(username + ":temp_key") correct_uuid = redis_store.hmget(username, "uuid")[0] if not (one_time_code and uuid) or uuid != correct_uuid or (key != one_time_code): return "INCORRECT AUTH INFO" redis_store.setex(one_time_code, username, 30) return "valid login!"
def a(): query = request.args.get('domain') if query: domain = query else: http_request = request.json result = {} if not request.json: abort(500) domain = http_request.get('domain') if not domain: return bad_request() result_domain = redis_store.get(domain) province = get_ip_locality(request.remote_addr) if result_domain: if result_domain == '0': a_record = redis_store.get('%s_%s' % (domain, province)) matched = True if not a_record: invalid_province_domain = Domain.query.filter_by(domain=domain).first() a_record = IP.query.filter_by(domain_id=invalid_province_domain.id).first().ip matched = False result = {domain: a_record, province: matched} elif result_domain: ip_list = pickle.loads(redis_store.get(domain)) priority_list = pickle.loads(redis_store.get('%s_priority' % domain)) index = random.choice(priority_list) result = {domain: ip_list[index], 'index': index} else: return bad_request() return jsonify(result) else: return bad_request()
def register(): username = request.form.get("username") uuid = request.form.get("uuid") push_key = request.form.get("push_key") one_time_code = request.form.get("one_time_code") print("{} {} {} {}".format(username, uuid, push_key, one_time_code)) if not (username and uuid and push_key and one_time_code): return "ERROR - INVALID INFO" key = redis_store.get(one_time_code) if not one_time_code: return "INCORRECT ONE TIME CODE" redis_store.hmset(username, {"uuid": uuid, "push_key": push_key}) redis_store.setex(one_time_code, username, 60) return "Great success!"
def logout(cls, token='', fb_id=''): """ """ if not all([token, fb_id]): raise custome_status.InvalidRequest( details='Bad request: Missing token or fb_id' ) # Invalidate the user token. stored_fb_id = redis_store.get(token) if not stored_fb_id or fb_id != stored_fb_id: raise custome_status.InvalidRequest( details='Bad request: Invalidate token' ) redis_store.delete(token) return {}
def get_users(): output = { 'c': 0, 'users': [] } query_time = redis_store.get('query_time') if query_time is None: query_time = time.time() redis_store.set('query_time', query_time, 3600) output['query_time'] = query_time user = User.query.all() for u in user: output['users'].append({'uid': u.uid, 'name': u.name}) session['time'] = time.time() return api_response(output)
def get_code(): username = session.get("username") if username: if not redis_store.get(username + ":pinged"): token_hex = redis_store.hmget(username, "push_key")[0] redis_store.setex(username + ":pinged", True, 60) random_str = str(random.randint(1, 100000000)) #''.join([x % 10 for x in os.urandom(8)]) send_notification(token_hex, random_str) redis_store.setex(username + ":temp_key", random_str, 30) return random_str code_bytes = os.urandom(128) code = "".join(map(lambda x: string.ascii_letters[ord(x) % len(string.ascii_letters)], code_bytes)) if username: redis_store.setex(username + ":temp_key", str(code), 30) else: redis_store.setex(code, False, 30) return str(code)
def match_incr(): matches = redis_store.get("match_count") or db.session.query(Match).count() redis_store.set("match_count", int(matches) + 1)
def player_incr(): players = redis_store.get("player_count") or db.session.query(Player).count() redis_store.set("player_count", int(players) + 1)
def get(): name = session.get("logged_in", None) redis_time = redis_store.get(name) return time.time() - redis_time
def test(): users = redis_store.get('users:GeorgeWashington') print "from redis: {0}".format(users) return 'test'