def get_sms_code(mobile): image_code = request.args.get("image_code") image_code_id = request.args.get("image_code_id") if not all([image_code, image_code_id]): return jsonify(errno=RET.PARAMERR, errmsg='参数不完整') try: real_image_code = redis_store.get('image_code_%s' % image_code_id) except Exception as e: current_app.logger.error(e) return jsonify(errno=RET.DBERR, errmsg='redis异常') if real_image_code == None: return jsonify(errno=RET.NODATA, errmsg='验证码过期') #删除图片验证码 写前一点 防止同一个验证码验证多次(撞库) try: redis_store.delete('image_code_%s' % image_code_id) except Exception as e: current_app.logger.error(e) #都装小写对比 if real_image_code.lower() != image_code.lower(): return jsonify(error=RET.DATAERR, errmsg='验证码错误') #检查手机60s有木有发送过 try: send_flag = redis_store.get('send_sms_code_%s' % mobile) except Exception as e: current_app.logger.error(e) else: if send_flag is not None: #60s有过记录 return jsonify(errno=RET.REQERR, errmsg='发送短信过于频繁60s后重试') #手机号是否重复 try: user = User.query.filter_by(phone_num=mobile).first() #怕数据库突然崩了 except Exception as e: current_app.logger.error(e) else: if user is not None: return jsonify(errno=RET.DATAEXIST, errmsg='手机号已经存在') #生成短信验证码 sms_code = '%06d' % random.randint(0, 999999) #06d 最少6位 少的前边加0 try: redis_store.setex('sms_code_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRE, sms_code) #5分钟 #保存发送给手机号的记录防止60s重复发送 redis_store.setex('send_sms_code_%s' % mobile, constants.SEND_SMS_CODE_EXPIRE, 1) #发送间隔60秒 1随便写 except Exception as e: current_app.logger.error(e)#记录异常 return jsonify(errno=RET.DBERR, errmsg='保存图片验证码失败') #发送短信 tasks_send_sms.delay(mobile, [sms_code, int(constants.SMS_CODE_REDIS_EXPIRE)/60], 1) return jsonify(errno=RET.OK, errmsg='发送成功')
def get_area_info(): #reids 读一下有木有数据 try: resp_json = redis_store.get("area_info") except Exception as e: current_app.logger.error(e) else: if resp_json is not None: #有缓存数据 return resp_json, 200, {"Content-Type": "application/json"} #获取地点信息 try: area_li = Area.query.all() except Exception as e: current_app.logger.error(e) return jsonify(error=RET.DBERR, errmsg='数据库异常') #转字典列表 area_dict_li = [] for area in area_li: area_dict_li.append(area.to_dict()) #存进redis resp_dict = dict(errno=RET.OK, errmsg='OK', data=area_dict_li) #字典 resp_json = json.dump(resp_dict) try: redis_store.setex("area_info", constants.AREA_INFO_REDIS_CACHAE_TIME, resp_json) #缓存2小时 except Exception as e: current_app.logger.error(e) return resp_json, 200, {"Content-Type": "application/json"}
def login(): req_dict = request.get_json() mobile = req_dict.get('mobile') password = req_dict.get('password') if not all([mobile, password]): return jsonify(errno=RET.PARAMERR, errmsg='参数不完整') if not re.match(r'1[34578]\d{9}]', mobile): return jsonify(errno=RET.PARAMERR, errmsg='手机号格式不对') #判断错误次数是否超过限制 user_ip = request.remote_addr #获取用户ip try: access_nums = redis_store.get('access_num_%s' % user_ip) except Exception as e: current_app.logger.error(e) else: if access_nums is not None and int( access_nums) >= constants.LOGIN_ERROR_MAX_TIMES: #5次 return jsonify(errno=RET.REQERR, errmsg='错误次数超过限制') try: user = User.query.filter_by(phone_num=mobile).first() except Exception as e: current_app.logger.error(e) return jsonify(errno=RET.DBERR, errmsg='获取用户失败') # 用户和密码一起校验(防止暴力刷取手机号码信息) if user is None or user.check_password(password): try: #记录错误次数 incr 有加一 没有创建 redis_store.incr('access_num_%s' % user_ip) redis_store.expire('access_num_%s' % user_ip, constants.LOGIN_ERROR_TIME) #60秒 except Exception as e: current_app.logger.error(e) return jsonify(errno=RET.DBERR, errmsg='用户不存在或密码失败') session['name'] = mobile session['mobile'] = mobile session['user_id'] = user.id return jsonify(errno=RET.OK, errmsg='登陆成功')
def get_area_info(): """ 获取城区信息 访问信息: http://127.0.0.1:5000/api/v1.0/areas :return: """ # 尝试redis中获取数据 try: resp_json = redis_store.get("area_info") except Exception as e: current_app.logger.error(e) else: if resp_json is not None: # redis 有缓存数据 current_app.logger.info("hit data redis") return resp_json, 200, {"Content-type": "application/json"} # 如果没有缓存数据就去查数据库 # 查询数据库,读取城区信息 try: area_list = Area.query.all() except Exception as e: current_app.logger.error(e) return jsonify(errno=RET.DBERR, errmsg="数据库异常") area_dict_list = [] # 将对象转成字典 for area in area_list: area_dict_list.append(area.to_dict()) # 将数据转换为json字符串 resp_dict = dict(errno=RET.OK, errmsg="OK", data=area_dict_list) # resp_json resp_json = json.dumps(resp_dict) # 将数据保存到redis中 try: redis_store.setex("area_info", constants.AREA_INFO_REDIS_CACHE_EXPIRES, resp_json) except Exception as e: current_app.logger.error(e) return resp_json, 200, {"Content-type": "application/json"}
def get_house_detail(house_id): """ 获取房屋详情 # 前端在房屋详情页面展示时,如果浏览页面的用户不是该房屋的房东,则展示预定按钮,否则展示 # 所以需要后端返回登录用户的user_id # 尝试获取用户登录的信息,若登录,则返回给前端登录用户的user_id,否则返回user_id=-1 # 就是如果访问的登录用户与房屋发布的用户一致前端就有一些不需要展示 访问URL: http://127.0.0.1:5000/api/v1.0/houses/1 返回数据: { "errno": "0", "errmsg": "OK", "data": { "user_id": 2, "house": { "hid": 1, "user_id": 2, "user_name": "18611111111", "user_avatar": "", "title": "测试1", "price": 39900, "address": "测试地址111", "room_count": 3, "acreage": 90, "unit": "三室两厅", "capacity": 6, "beds": "三床", "deposit": 100000, "min_days": 5, "max_days": 0, "img_urls": [], "facilities": [ 1, 2, 5, 6, 9, 16 ], "comments": [] } } :param house_id: :return: """ user_id = session.get("user_id", "-1") # 校验参数 if not house_id: return jsonify(errno=RET.PARAMERR, errmsg="参数缺失") # 先从redis缓存中获取信息 try: ret = redis_store.get("house_info_%s" % house_id) except Exception as e: current_app.logger.error(e) ret = None if ret: current_app.logger.info("hit house info redis") return '{"errno":"0","errmsg":"OK","data":{"user_id":%s,"house_info":%s}' % ( user_id, ret), 200, { "Content-Type": "application/json" } # 查询数据库 try: house = House.query.get(house_id) except Exception as e: current_app.logger.error(e) return jsonify(errno=RET.DBERR, errmsg="查询数据失败") if not house: return jsonify(errno=RET.NODATA, errmsg="房屋不存在") # 将房屋对象数据转为字典 try: house_data = house.to_full_dict() except Exception as e: current_app.logger.error(e) return jsonify(errno=RET.DBERR, errmsg="数据库出错") # 存入到redis中 json_house = json.dumps(house_data) try: redis_store.setex("house_info_%s" % house_id, constants.HOUSE_DETAIL_REDIS_EXPIRE_SECOND, json_house) except Exception as e: current_app.logger.error(e) resp = '{"errno":"0","errmsg":"OK","data":{"user_id":%s,"house":%s}' % ( user_id, json_house), 200, { "Content-Type": "application/json" } return resp
def get_house_index(): """ 获取主页幻灯片的房屋信息接口 访问url: http://127.0.0.1:5000/api/v1.0/houses/index 返回数据为: # redis缓存中取出来的数据: { "errno":0, "errmsg": "OK", "data":b'[ { "house_id": 1, "title": "\测\试1", "price": 39900, "area_name": "\西\城\区", "img_url": "D:\\\\pyCode\\\\flaskProject\\\\Flask_home\\\\home\\\\static\\\\images\\\\home01.jpg", "room_count": 3, "order_count": 5, "address": "\测\试\地\址111", "user_avatar": "", "ctime": "2020-08-06" } ]' } # 数据库中取出来的数据: { "data": [ { "address": "测试地址111", "area_name": "西城区", "ctime": "2020-08-06", "house_id": 1, "img_url": "D:\\pyCode\\flaskProject\\Flask_home\\home\\static\\images\\home01.jpg", "order_count": 5, "price": 39900, "room_count": 3, "title": "测试1", "user_avatar": "" } ], "errmsg": "OK", "errno": 0 } :return: """ # 从缓存中尝试获取数据 try: ret = redis_store.get("home_page_data") print(ret) except Exception as e: current_app.logger.error(e) ret = None if ret: current_app.logger.info("hit house index of redis") # 因为redis 中保存的是json字符串,所以直接进行字符串拼接返回 return '{"errno":0,"errmsg":"OK","data":%s}' % ret, 200, { "Content-Type": "application/json" } else: try: # 查询数据库,返回房屋订单数目最多的5条数据 # 根据订单的数量分组 houses = House.query.order_by(House.order_count.desc()).limit( constants.HOME_PAGE_MAX_HOUSES) except Exception as e: current_app.logger.error(e) return jsonify(errno=RET.DBERR, errmsg="查询数据失败") if not houses: return jsonify(errno=RET.NODATA, errmsg="查询无数据") house_list = [] for house in houses: # 如果房屋未设置图片,则跳过(因为首页展示的需要房屋图片) if not house.index_image_url: continue house_list.append(house.to_basic_dict()) # 将数据转换成json,并保存到redis缓存中 # json_houses = json.dumps(house_list) # try: # redis_store.setex("home_page_data", constants.HOME_PAGE_DATA_REDIS_EXPIRES, json_houses) # except Exception as e: # current_app.logger.error(e) # # return '{"errno":0,"errmsg":"OK","data":%s}' % json_houses, 200, {"Content-Type": "application/json"} return jsonify(errno=0, errmsg="OK", data=house_list)
def get_sms_code(mobile): """ 获取短信验证码 验证URL: http://127.0.0.1:5000/api/v1.0/sms_codes/18666951518?image_code=QNCV&image_code_id=11a98b32-6fb6-401d-b0d1-1b28f8566070 验证步骤,首先在首页刷新图片验证码,然后获取image_code_id 和图片验证码 在用postman向服务端发起get请求 :return: """ # 获取参数 image_code = request.args.get("image_code") image_code_id = request.args.get("image_code_id") # 校验 if not all([image_code, image_code_id]): # 表示参数不完整 return jsonify(errno=RET.PARAMERR, errmsg="请求参数错误!") # 业务逻辑处理 # 从redis中取出真实的图片验证码 try: real_image_code = redis_store.get("image_code_%s" % image_code_id) except Exception as e: current_app.logger.error(e) # {"status": RET.DATAERR, "msg": "redis数据库异常"} return jsonify(errno=RET.DATAERR, errmsg="redis数据库异常") if real_image_code is None: # 表示图片验证码没有或者过期 return jsonify(errno=RET.NODATA, errmsg="图片验证失效") # 删除图片验证码防止用户使用同一图片验证多次 # try: # redis_store.delete("image_code_%s" % image_code_id) # except Exception as e: # current_app.logger.error(e) if real_image_code.lower() == image_code.lower(): # 表示用户填写错误 return jsonify(errno=RET.DATAERR, errmsg="图片验证码错误") # 判断手机号请求验证码60秒内,不接受处理 try: send_flag = redis_store.get("send_sms_code_%s" % mobile) except Exception as e: current_app.logger.error(e) else: if send_flag is not None: # 表示在60秒之前有过发送的记录 return jsonify(errno=RET.REQERR, errmsg="请求过于频繁,请一分钟后重试!") # 判断手机号是否存在,根据此结果是否产生短信验证码 # db.session(User) try: user = User.query.filter_by(mobile=mobile).first() except Exception as e: current_app.logger.error(e) return jsonify(errno=RET.DATAERR, errmsg="mysql数据库异常") if user is not None: # 表示手机号已存在 return jsonify(errno=RET.DATAEXIST, errmsg="手机号已存在") # 返回值 sms_code = "%06d" % random.randint(0, 999999) # 保存真实短信验证码 try: redis_store.setex("sms_code_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code) redis_store.setex("send_sms_code_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1) except Exception as e: current_app.logger.error(e) return jsonify(errno=RET.DATAERR, errmsg="短信验证码异常") # 发送短信 # try: # ccp = CCP() # result = ccp.send_template_sms(mobile, [sms_code, int(constants.SMS_CODE_REDIS_EXPIRES / 60)], 1) # except Exception as e: # current_app.logger(e) # return jsonify(errno=RET.THIRDERR, errmsg="发送异常!") # 使用异步的方式放松短信 # 使用celery异步发送短信, delay函数调用后立即返回(非阻塞) # send_sms.delay(mobile, [sms_code, int(constants.SMS_CODE_REDIS_EXPIRES / 60)], 1) # # 返回异步任务的对象 result_obj = send_sms.delay( mobile, [sms_code, int(constants.SMS_CODE_REDIS_EXPIRES / 60)], 1) # print(result_obj) # print(result_obj.id) # 如果有id就说明异步任务处理了 # 使用这样判断会又变成同步了 # # 通过异步任务对象的get方法获取异步任务的结果, 默认get方法是阻塞的 # 默认get方法是阻塞的 会等到执行结果在返回 # ret = result_obj.get() # print("ret=%s" % ret) # # if ret == 0: # # 返回值 # return jsonify(errno=RET.OK, errmsg="发送成功,%s" % sms_code) # else: # return jsonify(errno=RET.THIRDERR, errmsg="发送失败!") return jsonify(errno=RET.OK, errmsg="发送成功,%s" % sms_code)
def register(): req_dict = request.get_json() mobile = req_dict.get('mobile') sms_code = req_dict.get('sms_code') password = req_dict.get('password') password2 = req_dict.get('password2') if not all([mobile, sms_code, password]): return jsonify(errno=RET.PARAMERR, errmsg='参数不完整') if not re.match(r'1[34578]\d{9}]', mobile): return jsonify(errno=RET.PARAMERR, errmsg='手机号格式不对') if password != password2: return jsonify(errno=RET.PARAMERR, errmsg='2个密码不对') try: real_sms_code = redis_store.get('send_sms_code_%s' % mobile) except Exception as e: current_app.logger.error(e) return jsonify(error=RET.DBERR, errmsg='读取验证码验证码异常') if real_sms_code is None: return jsonify(errno=RET.NODATA, errmsg='短信验证码失效') #删除短信验证码 防止多次验证(后边再删 一条短信可以多次验证) try: redis_store.delete('send_sms_code_%s' % mobile) except Exception as e: current_app.logger.error(e) if real_sms_code != sms_code: return jsonify(errno=RET.DBERR, errmsg='短信验证码错误') ''' 2次查询(不用) try: user = User.query.filter_by(phone_num=mobile).first() except Exception as e: current_app.logger.error(e) return jsonify(errno=RET.DBERR, errmsg='数据库异常') else: if user is not None: return jsonify(errno=RET.DATAEXIST, errmsg='手机号已经存在') user = User() db.session.add(user) db.session.commit() ''' user = User(phone_num=mobile, name=mobile) user.password_hash = password #方法变属性 try: db.session.add(user) db.session.commit() except IntegrityError as e: db.session.rollback() #回滚操作 current_app.logger.error(e) return jsonify(errno=RET.DATAEXIST, errmsg='手机号已经存在') except Exception as e: db.session.rollback() # 回滚操作 current_app.logger.error(e) return jsonify(errno=RET.DATAEXIST, errmsg='数据库存异常') #保存登录状态 session['name'] = mobile session['mobile'] = mobile session['user_id'] = user.id return jsonify(errno=RET.OK, errmsg='注册成功')
def register(): """ 注册 http://127.0.0.1:5000/api/v1.0/users/ 请求的参数:手机号、短信验证码、密码 参数格式:json { "mobile":"18611111111", "sms_code":"404989", "password":"******" } :return: """ # 获取请求的json数据,返回字典 req_dict = request.get_json() mobile = req_dict.get("mobile") sms_code = req_dict.get("sms_code") password = req_dict.get("password") # 校验参数 if not all([mobile, sms_code, password]): return jsonify(errno=RET.PARAMERR, errmsg="参数不完整") # 判断手机格式 if not re.match(r"1[345678]\d{9}", mobile): # 表示格式不对 return jsonify(errno=RET.PARAMERR, errmsg="手机格式错误") # 从redis中取出短信验证码 try: real_sms_code = redis_store.get("sms_code_%s" % mobile) except Exception as e: current_app.logger.error(e) return jsonify(error=RET.DBERR, errmsg="读取真实短信验证码异常") # 判断短信验证码是否过期 if real_sms_code is None: return jsonify(error=RET.NODATA, errmsg="短信验证码失效") # 删除redis中的短信验证码,防止重复使用校验 # try: # redis_store.delete("sms_code_%s" %mobile) # except Exception as e: # current_app.logger.error(e) # 判断用户填写短信验证码的正确性 # print(real_sms_code, type(real_sms_code)) if real_sms_code.decode('utf-8') != sms_code: return jsonify(error=RET.DATAERR, errmsg="短信验证码错误") # 判断用户的手机号是否注册过 # try: # user = User.query.filter_by(mobile=mobile).first() # except Exception as e: # current_app.logger.error(e) # else: # if user is not None: # # 表示手机号已经存在 # return jsonify(errno=RET.DATAEXIST,errmsg="手机号已存在") # 盐值 salt # 注册 # 用户1 password="******" + "abc" sha1 abc$hxosifodfdoshfosdhfso # 用户2 password="******" + "def" sha1 def$dfhsoicoshdoshfosidfs # 比较安全用sha256 # 用户登录 password ="******" "abc" sha256 sha1 hxosufodsofdihsofho # 保存用户的注册数据到数据库中 user = User(name=mobile, mobile=mobile) # user.generate_password_hash(password) user.password = password # 设置属性 # print(user.password) # 读取属性 # 保存用户的注册数据到数据库中 try: db.session.add(user) db.session.commit() except IntegrityError as e: # 出错的话就回滚 db.session.rollback() # 表示手机号出现重复值 current_app.logger.error(e) return jsonify(errno=RET.DATAEXIST, errmsg="手机号已存在") except Exception as e: db.session.rollback() current_app.logger.error(e) return jsonify(error=RET.DBERR, errmsg="查询数据库异常") # 保存登录状态到session中 session['name'] = user.name session['mobile'] = user.mobile session['user_id'] = user.id # 返回结果 return jsonify(errno=RET.OK, errmsg="注册成功!")
def login(): """ 用户登录 参数:手机号,密码 在同个地方登录超过5次后10分钟内不能再次登录 接口测试: 访问URL: http://127.0.0.1:5000/api/v1.0/sessions { "mobile":"18611111111", "password":"******" } :return: """ # 获取参数 req_dict = request.get_json() mobile = req_dict.get("mobile") password = req_dict.get("password") # 校验参数 # 参数完整的校验 if not all([mobile, password]): return jsonify(errno=RET.PARAMERR, errmsg="参数不完整") # 判断手机号 if not re.match(r"1[345678]\d{9}", mobile): # 表示格式不对 return jsonify(errno=RET.PARAMERR, errmsg="手机格式错误") # 密码错误次数的限制 # 判断错误次数是否超过限制,如果超过限制,如果超过限制,则返回 # # request.remote_addr user_ip = request.remote_addr try: access_nums = redis_store.get("access_nums_%s" % user_ip) except Exception as e: current_app.logger.error(e) else: print(access_nums) if access_nums is not None and int(access_nums) >= constants.LOGIN_ERROR_MAX_TIMES: return jsonify(errno=RET.REQERR, eermsg="错误次数过多,请稍后重试") # 从数据库中根据手机号查询用户的数据对象 print("111111111111") try: user = User.query.filter_by(mobile=mobile).first() print(user, type(user)) except Exception as e: current_app.logger.error(e) return jsonify(errno=RET.DBERR, errmsg="获取用户信息失败!") # 用数据库的密码与用户填写的密码进行对比验证 print(user) print(user.check_password(password)) if user is None or not user.check_password(password): try: redis_store.incr("access_nums_%s" % user_ip) redis_store.expire("access_nums_%s" % user_ip, constants.LOGIN_ERROR_FORBIN_TIME) return jsonify(errno=RET.DATAERR, errmsg="用户名或密码错误!") except Exception as e: current_app.logger.error(e) # 保存登录状态到session中 session['name'] = user.name session['mobile'] = user.mobile session['user_id'] = user.id # 返回结果 return jsonify(errno=RET.OK, errmsg="登录成功!")