コード例 #1
0
def get_areas():
    """
    获取地区地址
    :return: 返回地址信息
    """
    # 尝试从缓存里获取数据,如果没有从读数据库获取
    try:
        areas_dict = redis_conn.get('areas_info') # string
    except Exception as e:
        current_app.logger.error(e)


    if areas_dict:
        areas_dict = eval(areas_dict) # string --> dict
    else:
        try:
            all_areas = Area.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DATAERR,errmsg=u'数据库错误')

        areas_dict = {}
        for area in all_areas:
            areas_dict[area.id] = area.name
        # 将数据缓存到redis
        try:
            redis_conn.setex('areas_info',3600,areas_dict)
        except Exception as e:
            current_app.logger.error(e)

    return jsonify(errno=RET.OK,data=areas_dict)
コード例 #2
0
def get_area_info():
    """获取城区信息"""
    try:
        # 1.先尝试从redis中读取数据
        area_info = redis_conn.get("area_info")
    except Exception as e:
        current_app.logger.error(e)
    else:
        if area_info:
            # redis有缓存数据
            current_app.logger.info("hit redis area_info")
            # Content-Type默认是text/html
            return area_info, 200, {"Content-Type": "application/json"}

    try:
        # 2.redis没有数据再去查询数据库
        area_li = Area.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库异常")

    areas = []
    # 将对象转换为字典
    for area in area_li:
        areas.append(area.to_dict())
    area_info = json.dumps(dict(areas))

    try:
        # 3.将mysql查询数据保存到redis中
        redis_conn.setex("area_info", constants.AREA_INFO_REDIS_CACHE_EXPIRES,
                         area_info)
    except Exception as e:
        current_app.logger.error(e)

    return area_info, 200, {"Content-Type": "application/json"}
コード例 #3
0
def get_image_code(image_code_id):
    """
    获取图片验证码
    :param image_code_id: 图片验证码的编号
    :return: 正常:返回图片验证码  异常:返回json信息
    注意:前端修改js文件后要在浏览器清除缓存,不然浏览器还会使用之前缓存的js
    """

    # 1.使用captcha库生成验证码(名称,文本值,图片数据)
    name, text, value = captcha.generate_captcha()

    # 2.将验证码文本值和编号保存到redis
    # 分析:如果用hash数据结构,"image_codes": {"id1":"aaa", "id2":"bbb"}只能整体维护"image_codes"这个key的有效期
    #      合理做法应该是单独维护每个验证码的有效期,所以选择字符串"image_code_id1": "aaa", "image_code_id2": "bbb"
    try:
        # redis操作字符串时,在设置键和值的同时可以设置有效期
        redis_conn.setex('image_code_%s' % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='保存图片验证码失败')

    # 返回图片数据
    response = make_response(value)
    response.headers['Content-Type'] = 'image/jpg'
    return response
コード例 #4
0
def get_house_detail(house_id):
    """
    展示房屋的详细信息
    前端在房屋详情页面展示时,如果浏览页面的用户不是该房屋的房东,则展示预定按钮,否则不展示,
    所以需要后端返回登录用户的user_id
    尝试获取用户登录的信息,若登录,则返回给前端登录用户的user_id,否则返回user_id=-1
    :param house_id: int<house_id>
    :return: json
    """
    user_id = session.get('user_id',0)

    # 检查参数
    if not house_id:
        return jsonify(errno=RET.PARAMERR,errmsg=u'参数错误')

    # 尝试从redis读取缓存
    try:
        cache_data = redis_conn.get('house_detail_%s' %house_id)
    except Exception as e:
        current_app.logger.error(e)
    if cache_data:
        print ('从redis中读取缓存数据')
        response = {'errno': RET.OK, 'errmsg': u'ok', 'data': {'user_id': user_id, 'house_info': eval(cache_data)}}
        return json.dumps(response), 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=u'查询失败')

    if not house:
        return jsonify(errno=RET.DATAEXIST, errmsg=u'房屋不存在')
    # 获取详细信息(dict)
    house_data = house.to_full_dict()
    # json_data = json.dumps(house_data)

    # 设置缓存数据
    try:
        redis_conn.setex('house_detail_%s' %house_id,3600,house_data)
    except Exception as e:
        current_app.logger.error(e)

    response = {'errno':RET.OK,'errmsg':u'ok','data':{'user_id':user_id,'house_info':house_data}}

    return json.dumps(response),200,{'Content-Type':'application/json'}
コード例 #5
0
def get_houses_index():
    """
    获取房屋的index_image_url图片,并展示到主页
    :return: image_urls
    """
    # 尝试从redis获取缓存
    try:
        cache_data = redis_conn.get('index_urls_data')
    except Exception as e:
        current_app.logger.error(e)

    if cache_data:
        print ('从redis读取数据')
        response = {'errno': RET.OK, 'errmsg': 'ok', 'data': {'houses_info': eval(cache_data)}}
        return json.dumps(response), 200, {'Content-Type': 'application/json'}

    try:
        houses = House.query.order_by(House.order_count.desc()).limit(5)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg=u'获取数据失败')

    index_data = []

    for house in houses:
        if not house.index_image_url:
            continue
        index_data.append({'img_url':current_app.config.get('IMAGE_STORAGE_URL') + house.index_image_url,
                           'title':house.title,
                           'house_id':house.id})

    # 设置缓存
    try:
        redis_conn.setex('index_urls_data',3600,index_data)
    except Exception as e:
        current_app.logger.error(e)

    response = {'errno':RET.OK,'errmsg':'ok','data':{'houses_info':index_data}}
    return json.dumps(response),200,{'Content-Type':'application/json'}
コード例 #6
0
def get_sms_code(mobile):
    """
    获取短信验证码
    :param mobile:
    :return:
    """

    # 1.获取参数
    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='参数不完整')

    # 2.校验图片验证码
    try:
        # 从redis中取出图片验证码
        image_code_redis = redis_conn.get('image_code_%s' % image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='redis连接异常')
    # 判断验证码是否过期
    if image_code_redis is None:
        return jsonify(errno=RET.NODATA, errmsg='验证码失效')
    # 取完就删掉防止用户多次使用同一个验证码
    try:
        redis_conn.delete('image_code_%s' % image_code_id)
    except Exception as e:
        current_app.logger.error(e)
    # 与用户填写的图片验证码比对
    if image_code.lower() != image_code_redis.lower():
        return jsonify(errno=RET.DATAERR, errmsg='验证码输入错误')

    # 3.校验手机号是否已注册
    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger.error(e)
    else:
        if user:
            return jsonify(errno=RET.DATAERR, errmsg='手机号已存在')
    # 判断该手机号60秒内是否有过操作
    try:
        flag = redis_conn.get(mobile)
    except Exception as e:
        current_app.logger.error(e)
    else:
        if flag:
            return jsonify(errno=RET.REQERR, errmsg='请求过于频繁,请稍后重试')

    # 4.未注册的话就生成短信验证码并保存
    sms_code = "%06d" % random.randint(0, 999999)
    try:
        # 将验证码保存到redis
        redis_conn.setex('sms_code_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 同时也保存发送给该手机号的记录,防止用户60s内再次发送发短信请求
        redis_conn.setex(mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
    except Exception as e:
        current_app.logger.eror(e)
        return jsonify(errno=RET.DBERR, errmsg='保存验证码失败')

    # 5.调用接口发送短信
    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.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="发送异常")
    # 返回值
    if result == 0:
        # 发送成功
        return jsonify(errno=RET.OK, errmsg="发送成功")
    else:
        return jsonify(errno=RET.THIRDERR, errmsg="发送失败")