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 login( cls, token='', expiration='', fb_id='', gcm_id='', deref_all=False ): """ """ if not all([token, fb_id, gcm_id, expiration]): raise custome_status.InvalidRequest( details='Bad request: Missing token or fb_id' ) # TODO(ajen): Perhaps we should validate fb access token. Not a big # deal at the moment. # Check if we have the given user in our database. If not, we add it. user_obj = models.User.query.filter_by(fb_id=fb_id).first() if not user_obj: user_obj = cls._create(fb_id, gcm_id) # Set token in redis. Override it as we don't care. redis_store.setex(token, expiration, user_obj.fb_id) return cls._to_Dict(user_obj, deref_all)
def login(): user = ctr.get_user(request.form['login'], request.form['password']) if not user: return redirect('/login') session['username'] = request.form['login'] redis_store.setex(request.form['login'], 60, request.form['password']) return redirect('/admin')
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 generate_image_code(): image_code_id = request.args.get('image_code_id') # 获取参数 if not image_code_id: # 判断参数是否存在 return jsonify(status=0, msg='参数缺失') name, text, image = captcha.generate_captcha() # 调用扩展来生成图片验证码 redis_store.setex('ImageCode_' + image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text) # 保存图片验证码到redis response = make_response(image) # 使用响应对象返回图片本身 response.headers['Content-Type'] = 'image/jpg' # 设置响应的数据类型 return response # 返回响应
def before_request(): user = session.get('loginusername', None) if user: # if browser session exists, but the timeout expires, then # logout the user if not redis_store.exists('loginusername:'******'loginusername') else: # else, reset the timeout since there is # browser activity redis_store.setex('loginusername:' + user, 60, datetime.datetime.now())
def sms_code(): 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) if send_flag is not None: # 表示在60秒内之前有过发送的记录 return jsonify(code=4001, msg="请求过于频繁,请60秒后重试") except Exception as e: print(e) # 判断手机号是否存在 try: user = User.query.filter_by(phone=phone).first() if user: # 表示手机号已存在 return jsonify(code=4002, msg="手机号已存在") except Exception as e: print(e) sms_code = random.randint(100000, 999999) # 生成验证码 minute = 10 # 验证码有效时间 分钟 # 保存真实的短信验证码 try: # sms_code_13634802934 redis_store.setex("sms_code_%s" % phone, minute * 60, str(sms_code)) # 保存发送给这个手机号的记录,防止用户在60s内再次出发发送短信的操作 redis_store.setex("send_sms_code_%s" % phone, 60, 1) except Exception as e: print(e) return jsonify(code=4003, msg="保存短信验证码异常,请稍后在试") # 发送验证码 try: code = send_sms(phone, sms_code, minute) if code == "Ok": return jsonify(code=200, msg="发送成功") else: return jsonify(code=4004, msg="发送失败") except Exception as e: print(e) return jsonify(code=4005, msg="发送异常")
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 save_to_redis(self, key, expire=0): """ :param key: :param expire: for seconds :return: """ redis_key = CLASS_TABLE % (type(self).__name__, key) if expire != 0: redis_store.setex(redis_key, expire, json.dumps(self.stored_data())) else: redis_store.set(redis_key, json.dumps(self.stored_data())) pass
def login(): if request.method == 'POST': user = request.form.get('loginusername') password = request.form.get('loginpassword') if ACCESS_CONTROL.get(user, None) and password == ACCESS_CONTROL[user]: if not redis_store.exists('loginusername:'******'loginusername'] = user redis_store.setex('loginusername:'******'content')) flash( "User {} is currently logged in another session".format(user)) if 'loginusername' not in session: return render_template('login.html') return redirect(url_for('index'))
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) if send_flag: # 表示在60秒内之前有过发送的记录 return jsonify(code=4001, msg="请求过于频繁,请60秒后重试") except Exception as e: print(e) # 判断账号是否存在 try: user = User.query.filter_by(phone=phone).first() if user is None or user.status is False: # 账号不存在 return jsonify(code=4002, msg="账号不存在或账号异常!") except Exception as e: print(e) # 如果账号存在且正常 发送验证码 sms_code = random.randint(100000, 999999) # 生成验证码 minute = 10 # 验证码有效时间 分钟 # 保存真实的短信验证码 try: # sms_code_13634802934 redis_store.setex("sms_code_%s" % phone, minute * 60, str(sms_code)) # 保存发送给这个手机号的记录,防止用户在60s内再次出发发送短信的操作 redis_store.setex("send_sms_code_%s" % phone, 60, 1) except Exception as e: print(e) return jsonify(code=4003, msg="保存短信验证码异常,请稍后在试") # 发送验证码 try: code = send_sms(phone, sms_code, minute) if code == "Ok": return jsonify(code=200, msg="发送成功") else: return jsonify(code=4004, msg="发送失败") except Exception as e: print(e) return jsonify(code=4005, msg="发送异常")
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 detail_house(house_id): ''' 获取房屋基本信息 ''' user_id = g.user_id # 尝试从redis获取 try: house_redis_data = redis_store.get('HouseId=' + str(house_id)) except Exception as e: logging.error(e) house_redis_data = None # 直接加载redis中的数据 if house_redis_data: logging.info("hit house_id=%d redis" % house_id) resp = '{"errno":"0", "errmsg":"OK", "data":{"user_id":%s, "house":%s}}' % ( user_id, house_redis_data) return resp, 200, { "Content-Type": "application/json", } try: house = HouseInfo.query.get(house_id) except Exception as e: logging.error(e) return jsonify(errno=RET.DBERR, errmsg="数据库错误") if not house: return jsonify(errno=RET.DATAERR, errmsg="房屋不存在") # 获取房屋信息 house_data = house.to_full_dict() # 存入redis house_data_str = json.dumps(house_data) try: redis_store.setex("HouseId=" + str(house_id), constants.HOUSE_DATA_STR, house_data_str) except Exception as e: logging.error(e) resp = '{"errno":"0", "errmsg":"OK", "data":{"user_id":%s, "house":%s}}' % ( user_id, house_data_str) return resp, 200, { "Content-Type": "application/json", }
def send_msg(template_id, openid, page, form_id, data): # access_token = redis_store.get('access_token') # if not access_token: obj = AccessToken() access_token = obj.get_access_token() redis_store.setex('access_token', 7200, access_token) params = { "touser": openid, "template_id": template_id, "page": page, "form_id": form_id, "data": data } params = json.dumps(params) result = requests.post( 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=%s' % access_token, params) return result
def get_image_code(image_code_id): """ 获取图片验证码 : params image_code_id:图片验证码编号 :return: 正常情况下:验证码图片 异常:返回json """ # 业务逻辑处理 # 生成验证码图片 # 名字,真实文本,图片数据 name, text, image_data = captcha.generate_captcha() # 将验证码真实值与编号保存到redis中,设置有效期 # redis中的数据类型:字符串 列表 哈希 set # "key": xxx # 使用哈希维护有效期的时候只能整体设置,对于本需求来说不是很合理,因为如果有效时间一到,整个数据都会被清除,这样不符合需求 # "image_codes": {"编号1":"真实文本1","编号2":"真实文本2"} 哈希 # 在python中 # 利用命令hset('image_codes',"id1","abc")、 # hset('image_codes',"id2","def")向redis中添加数据 # 获取redis中的数据 hget("image_codes",'id1') # 单条维护记录,选用字符串 # "image_code_编号1":"真实值" # "image_code_编号2":"真实值" # redis_store.set('image_code_%s' % image_code_id, text) # 设置有效期, 3分钟有效期 # redis_store.expire("image_code_%s" % image_code_id, IMAGE_CODE_REDIS_EXPIRES) # 将上边两步合成一步写 # 记录名字 有效期 记录值 try: redis_store.setex('image_code_%s' % image_code_id, IMAGE_CODE_REDIS_EXPIRES, text) # 记录验证码到session:https://www.bbsmax.com/A/n2d9bYK0zD/ session['image_code_id'] = image_code_id except Exception as e: # 捕获异常,记录日志 current_app.logger.error(e) return jsonify(errno=RET.DBERR, errmsg=u"save image verify code failed") # 返回图片 resp = make_response(image_data) resp.headers['Content-Type'] = 'image/jpg' return resp
def image_code(): """生成图片验证码并返回""" # js生成用于唯一标识验证码 image_code_id = request.args.get("image_code_id") if not image_code_id: return jsonify(errno=RET.PARAMERR, errmsg="image_code_id不存在") # 调用第三方工具得到验证码图片及验证码字符串 name, text, image = captcha.generate_captcha() # 将真实字符串保存到redis try: redis_store.setex("ImageCode" + image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text) except Exception as e: current_app.logger.error(e) return jsonify(errno=RET.DATAERR, errmsg="保存图片验证码错误") # 把图片返回给前段展示 else: # 生成响应对象返回image response = make_response(image) response.headers["Content--Type"] = "image/jpg" return response
def house_index(): '''获取房屋订单数目最多的5条数据''' # 尝试从redis获取 try: house_redis_data = redis_store.get("IndexHouseData") except Exception as e: logging.error(e) house_redis_data = None if house_redis_data: logging.info("hit house index info redis") resp = '{"errno":"0", "errmsg":"OK", "data":%s}' % house_redis_data return resp, 200, { "Content-Type": "application/json", } # 从数据库取 try: houses = HouseInfo.query.order_by(HouseInfo.order_count.desc()).limit( constants.IndexHouseNum) # 降序 except Exception as e: logging.error(e) return jsonify(errno=RET.DBERR, errmsg="数据库") house_datas = [] for house in houses: house_datas.append(house.house_bic()) # 存入redis house_datas_str = json.dumps(house_datas) try: redis_store.setex("IndexHouseData", constants.INDEX_HOUSE_DATA_TIME, house_datas_str) except Exception as e: logging.error(e) resp = '{"errno":"0", "errmsg":"OK", "data":%s}' % house_datas_str return resp, 200, { "Content-Type": "application/json", }
def login(): if request.method == 'POST': user = request.form.get('loginusername') password = request.form.get('loginpassword') if ACCESS_CONTROL.get(user, None) and password == ACCESS_CONTROL[user]: if not redis_store.exists('loginusername:'******'loginusername'] = user redis_store.setex('loginusername:'******'next') #print("** next_page = {}".format(next_page)) #if not next_page or url_parse(next_page).netloc != '': # print("*** NO NEXT PAGE detected ***") # next_page = url_for('content') #return redirect(next_page) return redirect(url_for('content')) flash( "User {} is currently logged in another session".format(user)) if 'loginusername' not in session: return render_template('login.html') return redirect(url_for('index'))
def get_image_code(): """ 获取图片验证码 :return: """ # 1.获取当前的图片编号id code_id = request.args.get('code_id') # 2.生成验证码 name, text, image, = captcha.generate_captcha() try: # 保存当前生成的图片验证码内容 redis_store.setex('ImageCode_' + code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text) except Exception as e: current_app.logger.error(e) return make_response(jsonify(errno=RET.DATAERR, errmsg='保存图片验证码失败')) # 返回相应内容 resp = make_response(image) # 设置内容类型 resp.headers['Content-Type'] = 'image/jpg' return resp
def send_sms_origin(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秒后重试") sms_code = random.randint(100000, 999999) # 生成验证码 minute = constant.Bind_PHONE_CODE_NEED # 验证码有效时间 # 保存真实的短信验证码 try: redis_store.setex("sms_code_%s" % phone, minute * 60, sms_code) # 保存发送给这个手机号的记录,防止用户在60s内再次出发发送短信的操作 redis_store.setex("send_sms_code_%s" % phone, 60, 1) except Exception as e: current_app.logger.error(e) return jsonify(code=4003, msg="保存短信验证码异常,请稍后在试") # 发送验证码 try: code = send.send_sms(phone, sms_code, minute) if code == "Ok": return jsonify(code=200, msg="发送成功") else: return jsonify(code=4004, msg="发送失败") except Exception as e: print(e) return jsonify(code=4005, msg="发送异常")
def img_code(): """图片验证码""" # 前一次的img_code_id pre_code_id = request.args.get('pre') # 当前的img_code_id current_code_id = request.args.get('cur') # 生成图片验证码 # name-图片验证码的名字, text-图片验证码的文本, image-图片的二进制数据 name, txt, img = captcha.generate_captcha() try: # 把 txt 存入redis 把上一次存入的该用户 验证码删除 redis_store.delete("ImageCode_"+pre_code_id) redis_store.setex(name="ImageCode_"+current_code_id,time=constants.ImgCodeTime,value=txt) except Exception as e: logging.error(e) return jsonify(errno=RET.DBERR, errmsg="保存图片验证码失败") else: # 给前端返回img #print(img) response = make_response(img) # 设置传回给前端的内容数据是图片格式 response.headers["Content-Type"] = "image/jpg" return response
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 SmsCode(): """短信验证码""" # 接收的数据格式 /api/v1.0/sms_code/ #data = json.loads(request.form.to_dict().keys()[0]) data = json.loads(request.get_data()) mobile = data.get("mobile") img_code_id = data.get('id') img_code_text = data.get('text') if not all([mobile, img_code_id, img_code_text]): return jsonify({"errcode": RET.DATAERR, "errmsg": "参数错误"}) # 检查数据正确性 if not all([mobile,img_code_id,img_code_text]): # 返回json格式 return jsonify({"errcode":RET.DATAERR,"errmsg":"数据错误"}) # 手机号格式校验 if not re.match(r"^1[34578]\d{9}$", mobile): return jsonify(errno=RET.PARAMERR, errmsg="手机号格式错误") # 检验图片验证码正确性 获取数据可能失败 try: redis_img_code = redis_store.get('ImageCode_'+img_code_id) except Exception as e: logging.error(e) return jsonify(errno=RET.DBERR, errmsg="查询数据异常") # 如果验证码已经过期 if redis_img_code == '': return jsonify(errno=RET.DBERR, errmsg="验证码已经失效") # 删除redis中的验证码 try: redis_store.delete("ImageCode_"+img_code_id) except Exception as e: logging.error(e) # 转大写 if img_code_text.upper() != redis_img_code: return jsonify(errno=RET.DATAERR,errmsg="图片验证码错误") # 检查该手机号是否已经注册 try: user = UserInfo.query.filter_by(user_mobile=mobile).first() except Exception as e: logging.error(e) return jsonify(errno=RET.DATAERR,errmsg='查询数据异常') if user: return jsonify(errno=RET.DATAEXIST,errmsg='该手机好已注册') # 0,1000000 的随机数 如果没有 6位 就在前面用 0 代替 sms_code = "%06d"%random.randint(0,1000000) # 存入redis try: redis_store.setex('SMSCode_'+mobile, constants.SMSCodeTime, sms_code) except Exception as e: logging.error(e) return jsonify(errno=RET.DATAERR,errmsg="保存短信验证码失败") # 发送短信验证码至手机 使用celery # mobile, [sms_code, constants.SMSCodeTime / 60], 1 把参数传给 delay() send_sms.delay(mobile, [sms_code, constants.SMSCodeTime / 60], 1) return jsonify(errno=RET.OK,errmsg="验证码发送成功")