Exemplo n.º 1
0
def register():
    req_dict = request.json
    mobile = req_dict.get('mobile')
    phonecode = req_dict.get('phonecode')
    password = req_dict.get('password')

    if not all([mobile, phonecode, password]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不完整')
    try:
        sms_code = redis_store.get('sms_code:%s' % mobile)
    except Exception as e:
        current_app.logging.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询短信验证码失败')
    if not sms_code:
        return jsonify(errno=RET.NODATA, errmsg='短信验证码已过期')
    if sms_code != phonecode:
        return jsonify(errno=RET.DATAERR, errmsg='短信验证码错误')

    try:
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as e:
        current_app.logger.error(e)

    if user:
        return jsonify(errno=RET.DATAEXIST, errmsg='手机号已被注册')

    user = User()
    user.mobile = mobile
    user.name = mobile
    # todo:注册用户密码加密
    user.password = password
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.loggging.error(e)
        return jsonify(errno=RET.DBERR, errmsg='保存用户信息失败')

    session['user_id'] = user.id
    session['username'] = user.name
    session['mobile'] = user.mobile

    return jsonify(errno=RET.OK, errmsg='注册成功')
Exemplo n.º 2
0
Arquivo: house.py Projeto: xmstu/iHome
def get_area():
    """提供城区信息
    1.直接查询所有城区信息
    2.构造城区信息响应数据
    3.响应城区信息

    """
    # 在查询数据库之前,读取缓存的城区信息
    # eval: 会根据字符串的数据的结构,自动生成对应的对象
    try:
        area_dict_list = redis_store.get('Areas')
        if area_dict_list:
            return jsonify(errno=RET.OK, errmsg='OK', data=eval(area_dict_list))
    except Exception as e:
        logging.error(e)
        current_app.logger.error(e)

    # 1.直接查询所有城区信息
    try:
        areas = Area.query.all()
    except Exception as e:
        logging.error(e)
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询城区信息失败')

    # 2.构造城区信息响应数据
    area_dict_list = []
    for area in areas:
        area_dict_list.append(area.to_dict())

    # 缓存城区数据,set:存储字符串,hset:存储hash,lpush:列表
    # 非常重要的注意点:缓存时,如果出现了异常,不需要return,因为如果return了,会影响主线逻辑的正常执行
    # 缓存时附带逻辑,可有可无
    try:
        redis_store.set('Areas', area_dict_list, constants.AREA_INFO_REDIS_EXPIRES)
    except Exception as e:
        logging.error(e)
        current_app.logger.error(e)

    # 3.响应城区信息
    return jsonify(errno=RET.OK, errmsg='OK', data=area_dict_list)
Exemplo n.º 3
0
def get_areas():
    try:
        areas_dict = redis_store.get('areas_dict')
    except Exception as e:
        current_app.logger.error(e)
    if areas_dict:
        return jsonify(errno=RET.OK, errmsg='ok', data=eval(areas_dict))
    try:
        areas = Area.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询错误')
    areas_dict = []
    for area in areas:
        areas_dict.append(area.to_dict())
    try:
        redis_store.set('areas', areas_dict, constants.AREA_INFO_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)

    return jsonify(errno=RET.OK, errmsg='OK', data=areas_dict)
Exemplo n.º 4
0
def get_area_info():
    """获取城区信息"""

    # 尝试从redis中读取数据

    try:
        resp_json = redis_store.get("area_info")
    except Exception as ex:
        current_app.logger.error(ex)
    else:
        if resp_json is not None:
            # redis存在缓存数据
            current_app.logger.info("hit redis area_info")
            return resp_json, 200, {"Content-Type": "application/json"}

    # 查询数据库,读取城区信息
    try:
        area_list = Area.query.all()
    except Exception as ex:
        current_app.logger.error(ex)
        return jsonify(errno=RET.DBERR, errmsg="数据库异常")
    area_dict_li = []

    # 将对象转换为字典
    for area in area_list:
        area_dict_li.append(area.to_dict())

    # 将数据转换为json字符串
    resp_dict = dict(errno=RET.OK, errmsg="OK", data=area_dict_li)
    resp_json = json.dumps(resp_dict)

    # 将数据保存到redis中
    try:
        redis_store.setex("area_info", constains.AREA_INFO_REDIS_CACHE_EXPIRE,
                          resp_json)
    except Exception as ex:
        current_app.logger.error(ex)

    return resp_json, 200, {"Content-Type": "application/json"}
Exemplo n.º 5
0
def get_house_detail(house_id):
    user_id = session.get('user_id', -1)
    # if not user_id:
    #     user_id = -1
    if not house_id:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    try:
        house_info = redis_store.get('house_%d' % house_id)
        if house_info:
            return jsonify(errno=RET.OK, errmsg='OK', data={'house_info': house_info, 'user_id': user_id})
    except Exception as e:
        current_app.logger.error(e)

    try:
        house = House.query.get(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询错误')

    house_info = house.to_full_dict()

    return jsonify(errno=RET.OK, errmsg='OK', data={'house_info': house_info, 'user_id': user_id})
Exemplo n.º 6
0
def get_areas():
    """提供城区信息    将城区信息提供给主页的中的   需要一个列表:向视图
    1.直接查询所有城区信息
    2.构造城区信息响应数据
    3.响应城区信息
    """

    # 在查询数据库之前读取缓存的城区信息
    # 现在的代码形式:
    try:
        area_dict_list = redis_store.get('Areas')  #查
        if area_dict_list:
            return jsonify(errno=RET.OK,
                           errmsg='OK',
                           data=eval(area_dict_list))
    except Exception as e:
        current_app.logger.error(e)

    # 原来的代码形式:
    try:
        areas = Area.query.all()  #获取所有城区信息   areas里面存的是Area的模型对象
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询地区数据失败')

    # 2、构造城区信息响应数据,将aresa转成字典列表
    area_dict_list = []
    for area in areas:
        area_dict_list.append(area.to_dict())

    try:  #键:Areas    值:area_dict_list     缓存时间:constants.AREA_INFO_REDIS_EXPIRES
        redis_store.set("Areas", area_dict_list,
                        constants.AREA_INFO_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)

    # 响应城区信息:jsonify只认识字典或字典列表,所以把data中的内容都转换成了字典列表
    return jsonify(errno=RET.OK, errmsg='OK', data=area_dict_list)
Exemplo n.º 7
0
def get_areas():
    """提供城区信息
    1.查询所有的城区信息
    2.构造响应数据
    3.响应结果
    """

    # 查询缓存数据,如果有缓存数据,就使用缓存数据,反之,就查询,并缓存新查询的数据
    try:
        area_dict_list = redis_store.get('Areas')
        if area_dict_list:
            return jsonify(errno=RET.OK,
                           errmsg='OK',
                           data=eval(area_dict_list))
    except Exception as e:
        current_app.logger.error(e)

    # 1.查询所有的城区信息 areas == [Area,Area,Area,...]
    try:
        areas = Area.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询城区信息失败')

    # 2.构造响应数据
    area_dict_list = []
    for area in areas:
        area_dict_list.append(area.to_dict())

    # 缓存城区信息到redis : 没有缓存成功也没有影响,因为前爱你会判断和查询
    try:
        redis_store.set('Areas', area_dict_list,
                        constants.AREA_INFO_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)

    # 3.响应结果
    return jsonify(errno=RET.OK, errmsg='OK', data=area_dict_list)
Exemplo n.º 8
0
def get_areas():
    """提供城区的信息
    1.直接查询所有城区信息
    2.构造城区信息响应数据
    3.响应城区信息
    """
    # 先从缓存中去取,如果缓存中没有,再去数据库中取
    try:
        area_dict_list = redis_store.get('Areas')
        # 如果缓存的城区数据存在,就转成字典列表响应出去
        if area_dict_list:
            return jsonify(errno=RET.OK,
                           errmsg="OK",
                           data=eval(area_dict_list))
    except Exception as e:
        current_app.logger.error(e)

    # 1.直接查询所有城区信息areas == [Area, Area, Area]
    try:
        areas = Area.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询地区数据失败")

    # 2.构造城区信息响应数据
    area_dict_list = []
    for area in areas:
        area_dict_list.append(area.to_dict())

    # 缓存城区数据,set:储存
    try:
        redis_store.set('Areas', area_dict_list,
                        constants.AREA_INFO_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)

    # 3.响应城区信息
    return jsonify(errno=RET.OK, data=area_dict_list)
Exemplo n.º 9
0
def get_index_houses():
    try:
        houses = redis_store.get('house_index')
        if houses:
            return jsonify(errno=RET.OK, errmsg='ok', data=eval(houses))
    except Exception as e:
        current_app.logger.error(e)

    try:
        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='查询数据错误')
    houses_dict = []
    for house in houses:
        houses_dict.append(house.to_basic_dict())

    try:
        redis_store.set('house_index', houses_dict, constants.HOME_PAGE_DATA_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)

    return jsonify(errno=RET.OK, errmsg='ok', data=houses_dict)
Exemplo n.º 10
0
def get_areas():
    """提供城区信息
    1.直接查询所有城区信息
    2.构造城区信息响应数据
    3.响应城区信息
    """
    # 1.直接查询所有城区信息

    try:
        area_dict_list = redis_store.get('Areas')
        if area_dict_list:
            return jsonify(error_no=RET.OK,
                           error_msg=u'成功',
                           data=eval(area_dict_list))
    except Exception as e:
        current_app.logger.error(e)

    try:
        areas = Area.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(error_no=RET.DBERR, error_msg=u'查询地区数据失败')

    # 2.构造城区信息响应数据
    area_dict_list = []

    for area in areas:
        area_dict_list.append(area.to_dict())
    # 3.响应城区信息

    try:
        redis_store.set('Areas', area_dict_list,
                        constants.AREA_INFO_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)

    return jsonify(error_no=RET.OK, error_msg=u'成功', data=area_dict_list)
Exemplo n.º 11
0
def get_area_info():
    """获取城区信息"""

    # 先从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 redis area_info")
            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(errno=RET.DBERR, errmsg="数据库异常")

    # 将area对象转换为字典,并保存在列表中
    # area_dict_li = [ {"aid":area.id, "aname":area.name} for area in area_li]
    area_dict_li = [area.to_dict() for area in area_li]  # 使用模型中定义的对象转为字典的方法

    # 将数据保存到redis中 - 缓存
    # 将数据转换为json字符串
    resp_dict = dict(errno=RET.OK, errmsg="OK", data=area_dict_li)
    resp_json = json.dumps(resp_dict)
    # 将json字符串保存到redis中
    try:
        redis_store.setex("area_info", constants.AREA_INFO_REDIS_CACHE_EXPIRE,
                          resp_json)
    except Exception as e:
        current_app.logger.error(e)

    return resp_json, 200, {"Content-Type": "application/json"}
Exemplo n.º 12
0
def get_areas():
    """
    获取所有的城区信息
    1. 查询所有的Areas数据
    2. 返回
    :return:
    """

    # 先从缓存中取。如果取到直接返回,如果没有取到,那么再执行后面的逻辑
    try:
        areas_dict_li = redis_store.get("Areas")
        if areas_dict_li:
            return jsonify(errno=RET.OK, errmsg="ok", data=eval(areas_dict_li))
    except Exception as e:
        current_app.logger.error(e)

    try:
        areas = Area.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据失败")

    # 定义空列表,用于保存遍历的时候所转换的字典
    areas_dict_li = []
    # 转模型转字典
    for area in areas:
        areas_dict_li.append(area.to_dict())

    # 缓存数据到Redis中
    try:
        redis_store.set("Areas", areas_dict_li,
                        constants.AREA_INFO_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)

    # 返回
    return jsonify(errno=RET.OK, errmsg="ok", data=areas_dict_li)
Exemplo n.º 13
0
def get_areas():
    try:
        area_json_str = redis_store.get('areas')
        if area_json_str:
            areas_dict_li = json.loads(area_json_str)
            return jsonify(errno=RET.OK, errmsg='ok', data=areas_dict_li)
    except Exception as e:
        current_app.logger.error(e)
    try:
        areas = Area.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询城区信息失败')

    areas_dict_li = []
    for area in areas:
        areas_dict_li.append(area.to_dict())
    try:
        redis_store.set('areas', json.dumps(areas_dict_li),
                        constants.AREA_INFO_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)

    return jsonify(errno=RET.OK, errmsg='ok', data=areas_dict_li)
Exemplo n.º 14
0
def register():
    """
    注册
    1.获取用户的手机号码 密码 短信验证码
    2.判断参数是否缺少
    3.获取服务器存储的验证码
    4.服务器的验证码与客户端的验证码进行对比
    5.如果对比成功,则创建用户模型User对象,并给属性赋值
    6.将属性写入数据库
    7.响应注册结果

    """
    #获取用户的手机号码 密码 短信验证码
    #有3种方法获取前端ajax发来的json字符串
    #1.    # json_str = request.data
    # json_dict = json.loads(json_str)
    #下面两种要确保发来的数据是json字符串
    #2.json_dict = request.get_json()
    #第3种
    json_dict = request.json

    mobile = json_dict.get('mobile')
    sms_code_client = json_dict.get('sms_code')
    password = json_dict.get('password')

    #2.判断参数是否缺少
    if not all([mobile, sms_code_client, password]):
        return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')
    if not re.match(r'^1[3456789][0-9]{9}$', mobile):
        return jsonify(errno=RET.PARAMERR, errmsg='手机格式错误')

    #3.获取服务器存储的验证码
    try:
        sms_code_server = redis_store.get('SMS:%s' % mobile)
        current_app.logger.debug(sms_code_server)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询短信验证码失败')
    if not sms_code_server:
        return jsonify(errno=RET.NODATA, errmsg='短信验证码不存在')
    #4.服务器的验证码与客户端的验证码进行对比
    if sms_code_client != sms_code_server:
        return jsonify(errno=RET.PARAMERR, errmsg='短信验证码输出错误')
    #判断手机后是否已经存在
    if User.query.filter(User.mobile == mobile).first():
        return jsonify(errno=RET.DATAEXIST, errmsg='该手机号已经存在')

    #5.如果对比成功,则创建用户模型User对象,并给属性赋值
    user = User()
    user.mobile = mobile
    user.name = mobile

    #需要将密码加密后保存到数据库:调用password属性的setter方法
    user.password = password
    #6.将属性写入数据库
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='保存用户信息失败')
    session['user_id'] = user.id
    session['user_name'] = user.name
    #7.响应注册结果
    return jsonify(errno=RET.OK, errmsg='注册成功')
Exemplo n.º 15
0
def send_sms_code():
    '''
    获取手机号, 图片验证码
    对比图片验证码
    成功后生成短信验证码
    保存验证码, 发送短信   手机号: 短信验证码 redis
    :return:
    '''
    # json_data = request.data
    # data_dict = json.loads(json_data)
    data_dict = request.json

    image_code = data_dict['image_code']
    image_code_id = data_dict['image_code_id']
    mobile = data_dict['mobile']
    # 判断数据是否完整
    if not all([mobile, image_code, image_code_id]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不完整')
    # 判断手机号是否合法
    if not re.match("^1[3578][0-9]{9}$", mobile):
        return jsonify(errno=RET.PARAMERR, errmsg='手机号不正确')
    # 判断图片验证码是否正确
    # 获取真实验证码
    try:
        real_image_code = redis_store.get('ImageCode_' + image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询数据异常')

    # 验证码不存在
    if not real_image_code:
        return jsonify(errno=RET.DATAERR, errmsg='验证码已过期')

    # 验证码不正确
    if real_image_code.lower() != image_code.lower():
        return jsonify(errno=RET.DATAERR, errmsg='验证码不正确')

    # 删除图片验证码
    try:
        redis_store.delete('ImageCode_' + image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='删除本地验证码错误')

    try:
        user = User.quert.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        user = None
    if user:
        return jsonify(errno=RET.DATAEXIST, errmsg='手机号已被注册')

    sms_code = '%06d' % random.randint(0, 999999)

    current_app.logger.debug('短信验证码' + sms_code)

    # result = CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES / 60], '1')
    #
    # if result != 1:
    #     return jsonify(errno=RET.THIRDERR, errmsg='发送短信验证码失败')

    try:
        redis_store.set('SMS_' + mobile, sms_code,
                        constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='保存短信验证码错误')

    # 发送成功
    return jsonify(errno=RET.OK, errmsg='发送成功')
Exemplo n.º 16
0
def send_sms_code():
    """发送短信验证码
    1.获取参数:手机号,验证码,uuid
    2.判断是否缺少参数,并对手机号格式进行校验
    3.获取服务器存储的验证码
    4.跟客户端传入的验证码进行对比
    5.如果对比成功就生成短信验证码
    6.调用单例类发送短信
    7.如果发送短信成功,就保存短信验证码到redis数据库
    8.响应发送短信的结果
    """
    # 获取参数:手机号,验证码,uuid
    josn_str = request.data
    josn_dict = json.loads(josn_str)

    print ">" * 50, josn_dict

    mobile = josn_dict.get("mobile")
    imageCode_client = josn_dict.get("imageCode")
    uuid = josn_dict.get("uuid")

    # 判断是否缺少参数,并对手机号格式进行校验
    if not all([mobile, imageCode_client, uuid]):
        return jsonify(errno=RET.PARAMERR, errmsg="缺少参数")
    if not re.match(r"^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$",
                    mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号格式错误")

    # 获取服务器存储的验证码
    try:
        imageCode_server = redis_store.get('ImageCode:%s' % uuid)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询验证码错误")
    # 判断取得的数据是否为空
    if not imageCode_server:
        return jsonify(errno=RET.DBERR, errmsg="查询验证码不存在")

    # 跟客户端传入的验证码进行对比
    if imageCode_client.lower() != imageCode_server.lower():
        return jsonify(errno=RET.DBERR, errmsg="验证码输入有误")

    # 如果对比成功就生成短信验证码
    # "%06d"-不够六位补零
    sms_code = "%06d" % random.randint(0, 999999)

    # result = CCP().send_sms_code(mobile, [sms_code, 5], 1)
    #
    #
    # if result != 1:
    #     return jsonify(errno=RET.THIRDERR, errmsg="发送短信验证码失败")
    print "_" * 30, sms_code

    try:
        redis_store.set("SMS:%s" % mobile, sms_code,
                        constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='存储短信验证码失败')

        # 8.响应发送短信的结果
    return jsonify(errno=RET.OK, errmsg='发送短信验证码成功')
Exemplo n.º 17
0
def register():
    """实现注册
    1.获取请求参数:手机号,短信验证码,密码
    2.判断参数是否缺少
    3.获取服务器的短信验证码
    4.并与客户端传入的验证码比较,如果一致
    5.创建User模型类对象
    6.保存注册数据到数据库
    7.响应结果
    """

    # 1.获取请求参数:手机号,短信验证码,密码
    # json_str = request.data
    # json_dict = json.loads(json_str)
    # json_dict = request.get_json()
    json_dict = request.json

    mobile = json_dict.get('mobile')
    sms_code_client = json_dict.get('sms_code')
    password = json_dict.get('password')

    # 2.判断参数是否缺少
    if not all([mobile, sms_code_client, password]):
        return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')

    # 3.获取服务器的短信验证码
    try:
        sms_code_server = redis_store.get('Mobile:' + mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询短信验证码失败')
    # 判断数据是否为空
    if not sms_code_server:
        return jsonify(errno=RET.NODATA, errmsg='短信验证码不存在')

    # 4.并与客户端传入的验证码比较,如果一致
    if sms_code_server != sms_code_client:
        return jsonify(errno=RET.DATAERR, errmsg='输入验证码有误')

    # 判断该用户是否已经注册
    if User.query.filter(User.mobile == mobile).first():
        return jsonify(errno=RET.DATAEXIST, errmsg='用户已注册')

    # 5.创建User模型类对象
    user = User()
    # 注册时,默认手机号就是用户名,如果后面需要更换用户名,也是提供的有接口和界面
    user.name = mobile
    user.mobile = mobile
    # 密码需要加密后才能存储
    # user.password_hash = '加密后的密码'
    user.password = password

    # 6.保存注册数据到数据库
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='保存注册数据失败')

    # 实现注册成功即登录:记住状态保持信息即可
    session['user_id'] = user.id
    session['name'] = user.name
    session['mobile'] = user.mobile

    # 7.响应结果
    return jsonify(errno=RET.OK, errmsg='注册成功')
Exemplo n.º 18
0
def get_sms_code(mobile):
    """获取短信验证码"""
    image_code = request.args.get("code")
    image_code_id = request.args.get("codeId")

    if not all([image_code, image_code_id]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    try:
        real_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=error_map[RET.DBERR])

    if real_code is None:
        return jsonify(errno=RET.NODATA, errmsg=error_map[RET.NODATA])

    # 删除redis中的图片验证码,防止用户使用同一个图片验证码验证多次
    try:
        redis_store.delete("image_code_%s" % image_code_id)
    except Exception as e:
        current_app.logger.error(e)

    # 与用户填写的值进行对比
    if real_code.lower() != image_code.lower():
        return jsonify(errno=RET.DATAERR, errmsg=error_map[RET.DATAERR])

    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=error_map[RET.REQERR])

    # 判断手机号是否存在
    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=error_map[RET.DATAEXIST])

    # 如果手机号不存在,则生成短信验证码
    sms_code = "%06d" % random.randint(0, 999999)

    try:
        # 保存真实的短信验证码
        redis_store.setex("sms_code_%s" % mobile,
                          constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 保存发送给这个手机号的记录,防止用户在60s内再次出发发送短信的操作
        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.DBERR, errmsg=error_map[RET.DBERR])

    try:
        sms = SMS.instance()
        result = sms.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=error_map[RET.THIRDERR])

    if result == 0:
        return jsonify(errno=RET.OK, errmsg=error_map[RET.OK])
    else:
        return jsonify(errno=RET.THIRDERR, errmsg=error_map[RET.THIRDERR])
Exemplo n.º 19
0
def register():
    """注册
    1.获取注册参数:手机号,短信验证码,密码
    2.判断参数是否缺少
    3.获取服务器存储的短信验证码
    4.与客户端传入的短信验证码对比
    5.如果对比成功,就创建用户模型User对象,并给属性赋值
    6.将模型属性写入到数据库
    7.响应注册结果
    """

    # 1.获取注册参数:手机号,短信验证码,密码
    # json_str = request.data
    # json_dict = json.loads(json_str)
    # 当我们后端确定前端发来的是json字符串时
    # json_dict = request.get_json()
    json_dict = request.json
    mobile = json_dict.get('mobile')
    sms_code_client = json_dict.get('sms_code')
    password = json_dict.get('password')

    # 2.判断参数是否缺少
    if not all([mobile, sms_code_client, password]):
        return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')
    if not re.match(r'^1[345678][0-9]{9}$', mobile):
        return jsonify(errno=RET.PARAMERR, errmsg='手机号格式错误')

    # 3.获取服务器存储的短信验证码
    try:
        sms_code_server = redis_store.get('SMS:%s' % mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询短信验证码失败')
    if not sms_code_server:
        return jsonify(errno=RET.NODATA, errmsg='短信验证码不存在')

    # 4.与客户端传入的短信验证码对比
    if sms_code_client != sms_code_server:
        return jsonify(errno=RET.PARAMERR, errmsg='短信验证码输入有误')

    # 判断该手机号是否注册
    if User.query.filter(User.mobile == mobile).first():
        return jsonify(errno=RET.DATAEXIST, errmsg='该手机号已注册')

    # 5.如果对比成功,就创建用户模型User对象,并给属性赋值
    user = User()
    user.mobile = mobile
    user.name = mobile  # 默认把手机号作为用户名,如果不喜欢,后面会提供修改用户名的接口
    # 需要将密码加密后保存到数据库:调用password属性的setter方法
    user.password = password

    # 6.将模型属性写入到数据库
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='保存用户注册数据失败')

    # 7.响应注册结果
    return jsonify(errno=RET.OK, errmsg='注册成功')
Exemplo n.º 20
0
def send_sms_code():
    """
    #发送短信验证码
    json
    1. 获取参数(手机号,验证码, uuid)
    2. 验证参数完整和校验
    3. 从redis中获取图片验证码,(取不到,验证码过期)
    4. 对比图片验证码
    5. 生成短信验证码
    6. 保存redis短信验证码,
    7. 发送短信验证码
    8. 返回信息,发送验证码成功
    """
    # 1. 获取参数(手机号,验证码, uuid)
    req_data = request.data
    req_dict = json.loads(req_data)
    mobile = req_dict.get('mobile')
    image_code = req_dict.get('image_code')
    image_code_id = req_dict.get('image_code_id')
    # 2. 验证参数完整和校验
    if not all([mobile, image_code, image_code_id]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不完整')

    if not re.match(r"1[3456789]\d{9}", mobile):
        return jsonify(errno=RET.PARAMERR, errmsg='手机号格式不正确')

    if User.query.filter_by(name=mobile).all():
        return jsonify(errno=RET.PARAMERR, errmsg='用户已注册')

    # 3. 从redis中获取图片验证码,(取不到,验证码过期)
    try:
        real_image_id = redis_store.get('imagecode:%s' % image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询图片验证码错误')
    if not real_image_id:
        return jsonify(errno=RET.NODATA, errmsg='图片验证码已过期')

    # 4. 对比图片验证码
    if lower(real_image_id) != lower(image_code):
        return jsonify(errno=RET.DATAERR, errmsg='图片验证码错误')

    # 5. 生成短信验证码
    sms_code = '%06d' % random.randint(0, 999999)
    current_app.logger.info('短信验证码:' + sms_code)

    # 6. 保存redis短信验证码,
    try:
        redis_store.set('sms_code:%s' % mobile, sms_code, constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='保存验证码失败')

    # 7. 发送短信验证码
    # res = CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES/60],1)

    # if res != 1:
    #     return jsonify(errno=RET.THIRDERR, errsmg='发送短信失败')

    # 8. 返回信息,发送验证码成功
    return jsonify(errno=RET.OK, errmsg='发送短信成功')
Exemplo n.º 21
0
def register():
    """注册
    1.获取注册参数:手机号,短信验证码,密码
    2.判断参数是否缺少
    3.获取服务器存储的短信验证码
    4.与客户端传入的短信验证码对比
    5.如果对比成功,就创建用户模型User对象,并给属性赋值
    6.将模型属性写入到数据库
    7.响应注册结果
    """

    # 1.获取注册参数:手机号,短信验证码,密码
    # json_str = request.data
    # json_dict = json.loads(json_str)

    json_dict = request.get_json()
    mobile = json_dict.get('mobile')
    sms_code_client = json_dict.get('sms_code')
    password = json_dict.get('password')

    # 2.判断参数是否缺少
    if not all([mobile, sms_code_client, password]):
        return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')
    # 手机格式
    if not re.match(r'^1[345678][0-9]{9}$', mobile):
        return jsonify(errno=RET.PARAMERR, errmsg='手机号格式错误')

    # 检测手机号是否注册过
    if User.query.filter(User.mobile == mobile).first():
        return jsonify(errno=RET.DATAEXIST, errmsg='该手机号已存在')

    # 3.获取服务器存储的短信验证码
    try:
        sms_code_server = redis_store.get('SMS:%s' % mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询短信验证码失败')
    if not sms_code_server:
        return jsonify(errno=RET.NODATA, errmsg='短信验证码不存在')

    # 4.与客户端传入的短信验证码对比
    if sms_code_client != sms_code_server:
        return jsonify(errno=RET.PARAMERR, errmsg='短信验证码输入有误')

    # 5.如果对比成功,就创建用户模型User对象,并给属性赋值
    user = User()
    user.mobile = mobile
    user.name = mobile
    user.password = password

    # 6.将模型属性写入到数据库
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        logging.error(e)
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='保存用户数据失败')

    # 注册即登录,也就是保存注册时生成的数据
    session['user_id'] = user.id
    session['name'] = user.name
    session['mobile'] = user.mobile

    # 7.响应注册结果
    return jsonify(errno=RET.OK, errmsg='注册成功')
Exemplo n.º 22
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="参数不完整")

    # 业务逻辑处理

    # 从redis中提取真实的图片验证码
    try:
        real_image_code = redis_store.get("image_code_{}".format(image_code_id)).decode("UTF-8")
    except Exception as ex:
        current_app.logger.error(ex)
        return jsonify(errno=RET.DBERR, errmsg="redis数据库异常")

    # print("验证码", image_code)
    # print("真实验证码", real_image_code)

    print("判断验证码是否过期")

    # 判断验证码是否过期
    if real_image_code is None:
        # 图片验证码或过期
        return jsonify(errno=RET.NODATA, errmsg="图片验证码失效")

    # 删除Redis中图片验证码,防止用户使用同一个图片验证码验证多次
    try:
        redis_store.delete("image_code_{}".format(image_code_id))
    except Exception as ex:
        current_app.logger.error(ex)

    # print("验证码", image_code.lower())
    # print("真实验证码", real_image_code.lower())

    print(" 判断用户输入的验证码是否正确")

    # 判断用户输入的验证码是否正确
    if real_image_code.lower() != image_code.lower():
        # 用户输入的验证码错误
        return jsonify(errno=RET.DATAERR, errmsg="图片验证码错误")

    # 判断对于这个手机号的操作在60秒内有没有之前的记录, 如果有则认为用户操作频繁,不接受处理
    try:
        # send_flag = redis_store.get("send_sms_code_{}".format(mobile)).decode("UTF-8")
        send_flag = redis_store.get("send_sms_code_{}".format(mobile))
        if send_flag is not None:
            send_flag = redis_store.get("send_sms_code_{}".format(mobile)).decode("UTF-8")

        print("!" * 100)
        print("数据类型:", type(send_flag))
    except Exception as ex:
        current_app.logger.error(ex)
    else:
        if send_flag is not None:
            # 表示60秒内之前有发送过的记录
            return jsonify(errno=RET.REQERR, errmsg="请求过于频繁,请60秒后重试")

    # 进行对比与用户填写的值

    print("进行对比与用户填写的值")

    # 判断手机号是否已经注册
    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as ex:
        current_app.logger.error(ex)
    else:
        if user is not None:
            # 手机号已存在
            return jsonify(errno=RET.DATAEXIST, errmsg="手机号已存在")
    # 如果手机号不存在,则生成短信验证码(6位整数)
    sms_code = "%06d" % randint(0, 999999)

    # 保存真实验证码
    try:
        redis_store.setex("sms_code_{}".format(mobile), constains.SMS_CODE_REDIS_EXPIRE, sms_code)
        # 保存发送给这个手机号的记录,防止用户在60秒内再次触发发送短信的操作
        redis_store.setex("send_sms_code_{}".format(mobile), constains.SEND_SMS_CODE_INTERVAL, 1)
    except Exception as ex:
        current_app.logger.error(ex)
        return jsonify(errno=RET.DBERR, errmsg="保存短信验证码异常")

    print("保存真实验证码")

    print("准备异步发送短信")

    # 发送短信
    # 使用celery异步发送短信,delay函数调用后会立即返回
    # send_sms.delay(mobile, [sms_code, int(constains.SMS_CODE_REDIS_EXPIRE / 60)], 1)
    # result = tasks.send_sms.delay(mobile, [sms_code, int(constains.SMS_CODE_REDIS_EXPIRE / 60)], 1)
    result = send_sms.delay(mobile, [sms_code, int(constains.SMS_CODE_REDIS_EXPIRE / 60)], 1)
    print(result.id)

    # 通过get方法能获取celery异步执行的结果
    # get方法默认是阻塞行为,会等到有了执行结果之后才会返回
    # get方法也接受参数timeout, 超时时间,超过超时时间还拿不到结果则返回
    ret = result.get()

    print("异步发送短信成功")
    print(ret)
    # ccp.send_template_sms(mobile, [sms_code,int(constains.SMS_CODE_REDIS_EXPIRE / 60)],1)
    # 发送成功
    return jsonify(errno=RET.OK, errmsg="发送成功")
Exemplo n.º 23
0
def register():
    """用户注册
    请求的参数:手机号,短信验证码,密码,确认密码
    参数各式:json
    """
    # 获取请求的json数据,返回字典
    request_dict = request.get_json()

    # 获取参数
    mobile = request_dict.get("mobile")
    sms_code = request_dict.get("sms_code")
    password = request_dict.get("password")
    password2 = request_dict.get("password2")

    # 校验参数
    if not all([mobile, sms_code, password, password2]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")

    if not re.match(r"1[3-9]\d{9}", mobile):
        # 格式不对
        return jsonify(errno=RET.PARAMERR, errmsg="手机号格式错误")

    if password != password2:
        # 两次密码不一致
        return jsonify(errno=RET.PARAMERR, errmsg="两次密码不一致")

    # 从Redis中取出短信验证码
    try:
        real_sms_code = redis_store.get("sms_code_{}".format(mobile))
        if real_sms_code is not None:
            real_sms_code = redis_store.get(
                "sms_code_{}".format(mobile)).decode("UTF-8")
    except Exception as ex:
        current_app.logger.error(ex)
        return jsonify(errno=RET.DBERR, errmsg="读取真实短信验证码异常")

    # 判断短信验证码是否过期
    if real_sms_code is None:
        return jsonify(errno=RET.NODATA, errmsg="短信验证码失效")

    # 判断用户填写的短信验证码的正确性

    if real_sms_code != sms_code:
        return jsonify(errno=RET.DATAERR, errmsg="短信验证码错误")

    # 删除Redis中的短信验证码,防止重复使用校验
    try:
        redis_store.delete("sms_code_{}".format(mobile))
    except Exception as ex:
        current_app.logger.error(ex)

    # 判断用户的手机号是否注册过

    # try:
    #     user = User.query.filter_by(mobile=mobile).first()
    # except Exception as ex:
    #     current_app.logger.error(ex)
    #     return jsonify(errno=RET.DBERR, errmsg="数据库异常")
    # else:
    #     if user is not None:
    #         # 手机号已存在
    #         return jsonify(errno=RET.DATAEXIST, errmsg="手机号已存在")

    # 保存的用户的数据到数据库中
    user = User(name=mobile, mobile=mobile)
    # user.generate_password_hash(origin_password=password)
    user.password = password  # 设置属性

    try:
        db.session.add(user)
        db.session.commit()
    except IntegrityError as ie:
        # 事务回滚
        db.session.rollback()
        # 表示手机号出现了重复值,即手机号已经注册过
        current_app.logger.error(ie)
        return jsonify(errno=RET.DATAEXIST, errmsg="手机号已存在")

    except Exception as ex:
        current_app.logger.error(ex)
        return jsonify(errno=RET.DBERR, errmsg="查询数据库异常")

    # 保存登录状态到Session中
    session["name"] = mobile
    session["mobile"] = mobile
    session["user_id"] = user.id

    # 返回结果
    return jsonify(errno=RET.OK, errmsg="注册成功")
Exemplo n.º 24
0
def get_sms_code(mobile):
    """使用celery异步任务发送短信验证码"""

    # 1.获取参数
    image_code = request.args.get("image_code")
    image_code_id = request.args.get("image_code_id")

    # 2.校验参数
    # 参数是否完整
    if not all([image_code, image_code_id]):
        # 表示参数不完整
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")

    # 3.业务逻辑处理
    # 从redis中获取真实的图片验证码值
    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 is None:
        # 表示图片验证码没有或过期
        return jsonify(errno=RET.NODATA, errmsg="图片验证码失效")

    # 删除redis中的图片验证码: 防止用户使用同一个图片验证码验证多次(使用多次)
    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="请求过于频繁,请60秒后再试")

    # 判断注册的手机号是否存在
    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="手机号已存在")

    # 如果手机号不存在,则生成短信验证码
    sms_code = "%06d" % random.randint(0, 999999)

    # 保存真实的短信验证码到redis中
    try:
        redis_store.setex("sms_code_%s" % mobile,
                          constants.SMS_CODE_REDIS_EXPIRE, sms_code)
        # 保存发送给这个手机号的验证码记录,防止用户在60秒内再次触发发送短信验证码的操作
        # redis_store.setex("send_sms_code_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        redis_store.setex("send_sms_code_%s" % mobile,
                          constants.SEND_SMS_CODE_INTERVAL,
                          "保存发送验证码记录,防止60秒内再次发送的操作")
    except Exception as e:
        # 记录日志
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="保存短信验证码异常")

    # 发送短信
    # 使用celery异步发送手机短信验证码,delay调用后立即返回
    send_sms.delay(
        mobile, [sms_code, int(constants.SMS_CODE_REDIS_EXPIRE / 60)], 1)

    # 4.返回值
    return jsonify(errno=RET.OK, errmsg="发送成功")
Exemplo n.º 25
0
def login():
    """用户登录
    请求参数: 手机号 密码
    参数格式: json
    """
    print "bbb"
    # 获取参数
    print request.get_json()
    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="手机格式不正确")

    # 判断用户输入错误次数是否超过限制,如果超过限制,则不允许继续操作
    # redis记录: "access_nums_请求的IP":"次数"
    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:
            # redis中有记录并且错误次数大于5,阻止继续执行操作
            return jsonify(errno=RET.REQERR, errmsg="错误次数过多,请稍后重试")

    # 业务逻辑处理
    # 根据手机号从数据库查询用户的数据对象
    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        # 记录日志
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="获取用户信息失败")

    # 用数据库中的密码与用户填写的密码进行对比验证是否一致
    if user is None or not user.check_password(password):
        # 如果登录验证失败,记录错误次数,返回信息
        try:
            redis_store.incr("access_num_%s" % user_ip)
            redis_store.expire("access_num_%s" % user_ip,
                               constants.LOGIN_ERROR_FORBID_TIME)
        except Exception as e:
            # 记录日志
            current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="用户名或密码错误")

    # 如果登录验证相同,保存登录状态,在session中
    session["name"] = user.name
    session["mobile"] = user.mobile
    session["user_id"] = user.id

    # 返回值
    return jsonify(errno=RET.OK, errmsg="登录成功")
Exemplo n.º 26
0
def register():
    """"用户注册
    请求的参数: 手机号, 验证码, 密码, 确认密码
    参数格式: json
    """

    # 获取参数:
    # 获取请求的json数据,返回字典
    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')
    print(mobile, sms_code, password, password2)
    # 校验参数:
    # 校验参数是否完整
    if not all([mobile, sms_code, password, password2]):
        # 参数不完整
        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="两次密码不一致")

    # 业务逻辑处理:
    # 从redis中取出短信验证码
    try:
        real_sms_code = redis_store.get("sms_code_%s" % mobile)
    except Exception as e:
        # 记录日志
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="读取真实短信验证码异常")

    # 判断从redis中取出的短信验证码是否过期
    if real_sms_code is None:
        return jsonify(errno=RET.NODATA, errmsg="短信验证码失效")

    # 删除redis中的短信验证码,防止重复使用校验
    try:
        redis_store.delete("sms_code_%s" % mobile)
    except Exception as e:
        # 记录日志
        current_app.logger.error(e)

    # 判断用户填写的短信验证码与从redis中取出的短信验证码是否一致
    if real_sms_code != sms_code:
        return jsonify(errno=RET.DATAERR, errmsg="短信验证码错误")

    # 判断用户手机号是否注册过
    # try:
    #     user = User.query.filter_by(mobile=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="手机号已存在")

    # 保存用户注册信息到数据库
    # password_hash = generate_password_hash(password)  # 密码加密
    # user = User(name=mobile, password_hash=password_hash, mobile=mobile)
    user = User(name=mobile, password_hash=password, mobile=mobile)
    user.password = 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.DBERR, errmsg="查询数据库异常")

    # 保存登录状态到session中
    session['name'] = mobile
    session['mobile'] = mobile
    session['user_id'] = user.id

    # 返回值:
    return jsonify(errno=RET.OK, errmsg="注册成功")
Exemplo n.º 27
0
def register():
    """
    注册逻辑
    1. 获取参数:手机号, 短信验证码, 密码,
    2. 取到真实的短信验证码
    3. 进行验证码的对比
    4. 初始化User模型,保存相关数据
    5. 将user模型存到数据库中
    6. 给出响应:{"errno": "0", "errmsg": "注册成功"}
    :return:
    """

    # 1. 获取参数:手机号, 短信验证码, 密码,
    data_dict = request.json
    mobile = data_dict.get("mobile")
    phonecode = data_dict.get("phonecode")
    password = data_dict.get("password")
    # 判断参数是否都有值
    if not all([mobile, phonecode, password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 2. 取到真实的短信验证码
    try:
        real_phonecode = redis_store.get("Mobile:" + mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询短信验证码失败")

    if not real_phonecode:
        return jsonify(errno=RET.NODATA, errmsg="短信验证码过期")

    # 3. 进行验证码的对比
    if phonecode != real_phonecode:
        return jsonify(errno=RET.DATAERR, errmsg="短信验证码输入错误")

    # 3.1 判断当前手机是已经被注册
    if User.query.filter(User.mobile == mobile).first():
        return jsonify(errno=RET.DATAEXIST, errmsg="该手机号已被注册")

    # 4. 初始化User模型,保存相关数据
    user = User()
    user.mobile = mobile
    user.name = mobile
    # 保存密码
    user.password = password

    # 5. 将user模型存到数据库中
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存用户数据失败")

    # 保存当前用户信息到session
    session["user_id"] = user.id
    session["name"] = user.name
    session["mobile"] = user.mobile

    # 6. 给出响应:{"errno": "0", "errmsg": "注册成功"}
    return jsonify(errno=RET.OK, errmsg="注册成功")
Exemplo n.º 28
0
def send_sms_code():
    """
    发送短信验证码
    1. 接收前端发送过来的参数:手机号,用户输入图片验证码的内容,图片验证码的编号
    2. 判断参数是否都有值与参数校验
    3. 从redis中取出正确的图片验证码(如果没有到,代表验证码过期)
    4. 进行验证码的对比,如果用户输入的验证码与真实的验证码一样
    5. 生成短信验证码
    6. 发送短信
    7. 保存短信验证到redis中
    8. 告诉前端发送短信成功
    :return:
    """
    # 1. 接收前端发送过来的参数
    # JSON字符串
    json_data = request.data
    # 转成字典
    json_dict = json.loads(json_data)
    mobile = json_dict.get("mobile")
    image_code = json_dict.get("image_code")
    image_code_id = json_dict.get("image_code_id")

    # 2. 判断参数是否有值和参数校验
    if not all([mobile, image_code, image_code_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not re.match("^1[34578][0-9]{9}$", mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号格式有误")

    # 3. 从redis中取出正确的图片验证码(如果没有到,代表验证码过期)
    try:
        real_image_code = redis_store.get("ImageCode:" + image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询验证码出错")

    # 如果没有到,代表验证码过期
    if not real_image_code:
        return jsonify(errno=RET.NODATA, errmsg="验证码已过期")

    # 4. 进行验证码的对比,如果用户输入的验证码与真实的验证码一样
    if image_code.lower() != real_image_code.lower():
        return jsonify(errno=RET.DATAERR, errmsg="验证码输入不正确")

    # 5. 生成短信验证码
    sms_code = "%06d" % random.randint(0, 999999)
    current_app.logger.debug("短信验证码为:" + sms_code)
    # 6. 发送短信
    # result = CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES / 60], "1")
    # if result != 1:
    #     # 发送短信失败
    #     return jsonify(errno=RET.THIRDERR, errmsg="发送短信失败")

    # 7. 保存短信验证到redis中
    try:
        redis_store.set("Mobile:" + mobile, sms_code,
                        constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="保存验证码失败")
    # 8. 告诉前端发送短信成功
    return jsonify(errno=RET.OK, errmsg="发送成功")
Exemplo n.º 29
0
def send_sms_code():
    """发送短信验证码
    1.接受参数:手机号,图片验证码,uuid
    2.判断参数是否缺少,并且要对手机号进行校验
    3.获取服务器存储的图片验证码,uuid作为key
    4.与客户端传入的图片验证码对比,如果对比成功
    5.生成短信验证码
    6.使用云通讯将短信验证码发送到注册用户手中
    7.存储短信验证码到redis中
    8.响应短信发送的结果
    """

    # 1.接受参数:手机号,图片验证码,uuid
    # data : 保存请求报文里面的原始的字符串,开发文档约定,客户端发送的是json字符串
    json_str = request.data
    json_dict = json.loads(json_str)

    mobile = json_dict.get('mobile')
    imageCode_client = json_dict.get('imagecode')
    uuid = json_dict.get('uuid')

    # 2.判断参数是否缺少,并且要对手机号进行校验
    if not all([mobile, imageCode_client, uuid]):
        return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')
    # 校验手机号码是否合法
    if not re.match(r'^1[345678][0-9]{9}$', mobile):
        return jsonify(errno=RET.PARAMERR, errmsg='手机号码格式错误')

    # 3.获取服务器存储的图片验证码,uuid作为key
    try:
        imageCode_server = redis_store.get('ImageCode:' + uuid)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询服务器验证码失败')

    # 判断是否为空或者过期
    if not imageCode_server:
        return jsonify(errno=RET.NODATA, errmsg='验证码不存在')

    # 4.与客户端传入的图片验证码对比,如果对比成功
    if imageCode_server.lower() != imageCode_client.lower():
        return jsonify(errno=RET.DATAERR, errmsg='验证码输入有误')

    # 5.生成短信验证码
    sms_code = '%06d' % random.randint(0, 999999)
    current_app.logger.debug('短信验证码为:' + sms_code)

    # 6.使用云通讯将短信验证码发送到注册用户手中
    # 注释以下代码,是在我们验证逻辑通过的前提下,为了方便不在频繁的发送短信验证码,我就使用假的手机号绑定我们自己生产的验证码
    # result = CCP().send_template_sms(mobile, [sms_code , constants.SMS_CODE_REDIS_EXPIRES/60], '1')
    # if result != 1:
    #     return jsonify(errno=RET.THIRDERR, errmsg='发送短信验证码失败')

    # 7.存储短信验证码到redis中:短信验证码在redis中的有效期一定要和短信验证码的提示信息一致
    try:
        redis_store.set('Mobile:' + mobile, sms_code, constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='存储短信验证码失败')

    # 8.响应短信发送的结果
    return jsonify(errno=RET.OK, errmsg='发送短信验证码成功')
Exemplo n.º 30
0
def register():
    """"注册
    1,获取注册参数:手机号,短信验证码,密码
    2,判断参数是否缺少
    3,获取服务器存储的短信验证码
    4,与客户端传入的短信验证码对比
    5,对比成功,创建User对象,给属性赋值
    6,将模型属性写入到数据库
    7,响应注册结果
    """

    # 1,获取注册参数:手机号,短信验证码,密码
    # 当确定前端发来的是json字符串
    json_dict = request.get_json()
    mobile = json_dict.get('mobile')
    sms_code_client = json_dict.get('sms_code')
    password = json_dict.get('password')

    print '11111111111'
    print mobile
    print u'短信验证码为:' + sms_code_client
    print password
    print '22222222222'

    #    2,判断参数是否缺少
    if not all([mobile, sms_code_client, password]):
        return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')
    if not re.match(r'^1[345678][0-9]{9}$', mobile):
        return jsonify(errno=RET.PARAMERR, errmsg='手机号格式错误')

    # 3,获取服务器存储的短信验证码
    try:
        sms_code_server = redis_store.get('SMS:%s' % mobile)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询短信验证码失败')
    if not sms_code_server:
        return jsonify(errno=RET.NODATA, errmsg='短信验证码不存在')

    # 4,与客户端传入的短信验证码对比
    if sms_code_client != sms_code_server:
        return jsonify(errno=RET.PARAMERR, errmsg='短信验证码输入有误')

    # 判断该手机号是否注册
    if User.query.filter(User.mobile == mobile).first():
        return jsonify(errno=RET.DATAEXIST, errmsg='该手机号已注册')

    # 5,对比成功,创建User对象,给属性赋值
    user = User()
    user.mobile = mobile
    user.name = mobile  # 后面会有改用户名的逻辑
    # TODO 密码需要加密后加入到数据库
    # 调用password属性的setter方法
    user.password = password

    # 6,将模型属性写入到数据库
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='保存用户注册数据失败')

    # 注册即登录
    session['user_id'] = user.id
    session['name'] = user.name
    session['mobile'] = user.mobile

    # 7,响应注册结果
    return jsonify(errno=RET.OK, errmsg='注册成功')