Esempio n. 1
0
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='发送成功')
Esempio n. 2
0
def get_iamge_code(image_code_id):
    """
    获取图片验证码
    : params image_code_id:图片 验证码
    :return: 正常返回验证码图片 异常:返回json错误信息
    """
    # 业务逻辑处理
    # 生成验证码图片与编号保存到redis中
    # 名字 真实文本,图片数据
    name, text, image_data = captcha.generate_captcha()
    # 将验证码真实值与编号保存到redis中,设置有效期
    # redis:字符串,列表,哈希,set
    # “key”:"***"
    # redis命令设置图片验证码键值对
    # 设置键值对

    # 选用字符串类型
    # "image_code_编号1":"真实值"
    # redis_store.set("image_code_%s" % image_code_id, text)
    # # 设置过期时间
    # redis_store.setexpire("image_code_%s" % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES)
    # 设置值同时设置有效期
    try:
        redis_store.setex("image_code_%s" % image_code_id,
                          constants.IMAGE_CODE_REDIS_EXPIRES, text)
    except Exception as e:
        # 记录日志
        current_app.logger.error()
        return jsonify({"status": RET.DATAERR, "msg": "设置状态码信息失败"})
    # 返回图片数据
    resp = make_response(image_data)
    resp.headers["Content-Type"] = "image/jpg"
    return resp
Esempio n. 3
0
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"}
Esempio n. 4
0
def get_image_code(image_code_id):
    #获取图片验证码,返回验证码图片 image_code_id图片验证码编号
    name, text, image_data = captcha.generate_captcha() #名字,真实文本,图片数据

    #单挑维护记录 'imagecaodeid':'真实值'
    #redis_store.set('image_code_%s' % image_code_id, text)
    #redis_store.expire('image_code_%s' % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRE) #180秒
    try:
        redis_store.setex('image_code_%s' % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRE, text)
    except Exception as e:
        current_app.logger.error(e)#记录异常
        return jsonify(errno=RET.DBERR, errmsg='保存图片验证码失败')

    #返回图片
    resp = make_response(image_data)
    resp.headers['Content-Type'] = 'image/jpg'
    return resp
Esempio n. 5
0
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"}
Esempio n. 6
0
def get_image_code(image_code_id):
    """
    获取图片验证码
    :param image_code_id: 图片验证码编号
    :return: 图片验证码
    """

    # 业务逻辑处理
    # 生成图片验证码 name验证码名称 text图片真实值 image_code 图片验证码
    name, text, image_code = captcha.captcha.generate_captcha()
    # 将图片验证码编号和验证码真实值保存到redis中
    try:
        redis_store.setex('image_code_%s' % image_code_id,
                          REDIS_IMAGE_CODE_EXPIRE, text)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, message='保存图片验证码失败')

    # 返回图片验证码
    resp = make_response(image_code)
    resp.headers['Content-Type'] = 'image/jpg'

    return resp
Esempio n. 7
0
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
Esempio n. 8
0
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)