コード例 #1
0
def socket(data):
    data_mine = data["data"].get("mine")
    data_to = data["data"].get("to")

    # 消息来源
    data_mine_id = data_mine.get("id")  # 我的id
    data_mine_username = data_mine.get("username")  # 我的昵称
    data_mine_avatar = data_mine.get("avatar")  # 我的头像
    data_mine_mine = data_mine.get("mine")  # 是否是我发送的消息
    data_mine_content = data_mine.get("content")  # 消息内容

    # 消息目标
    data_to_id = data_to.get("id")  # 目标id
    data_to_username = data_to.get("username")  # 目标昵称
    data_to_avatar = data_to.get("avatar")  # 目标头像
    data_to_type = data_to.get("type")  # 目标类型:friend,group
    data_to_name = data_to.get("name")  # 目标姓名
    data_to_sign = data_to.get("sign")  # 上一次打开聊天框时发送的最后一条消息
    data_to_content = data_to.get("content")  # 上一次打开聊天框时发送的最后一条消息
    data_to_historyTime = data_to.get("historyTime")  # 打开对话框的时间

    data_timestamp = time.time() * 1000

    if data_mine_mine:
        to_sid = redis_store.get(data_to_id)
        data = {"username": data_mine_username, "avatar": data_mine_avatar, "id": data_mine_id, "type": data_to_type,
                "content": data_mine_content, "mine": data_mine_mine, "timestamp": data_timestamp}
        # emit("chatMessage", data, room=to_sid)
        emit("chatMessage", data, broadcast=True)
コード例 #2
0
ファイル: views.py プロジェクト: lotapp/layIM-python
def register():
    print(request.form)
    val_cellphone = request.form.get("cellphone")
    val_password = request.form.get("password")
    val_repass = request.form.get("repass")
    val_vercode = request.form.get("vercode")
    val_nickname = request.form.get("nickname")
    val_agreement = request.form.get("agreement")

    # 校验参数
    if not all([
            val_cellphone, val_vercode, val_password, val_repass, val_nickname,
            val_agreement
    ]):
        return jsonify(code=RET.PARAMERR, msg="参数不完整")

    # 判断手机号格式
    if not re.match(r"1[345789]\d{9}", val_cellphone):
        return jsonify(code=RET.DATAERR, msg="手机号格式错误")

    if val_password != val_repass:
        return jsonify(code=RET.DATAERR, msg="两次密码不同")

    # 业务逻辑
    # 获取真实的短信验证码
    try:
        real_sms_code = redis_store.get("sms_code_%s" % val_cellphone)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="查询短信验证码错误")

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

    # 对于用户输入的短信验证码是否正确
    if real_sms_code != val_vercode:
        return jsonify(code=RET.DATAERR, msg="短信验证码错误")

    # 删除短信验证码
    try:
        redis_store.delete("sms_code_%s" % val_cellphone)
    except Exception as e:
        current_app.logger.error(e)

    # 保存用户的数据到数据库中
    user = UserInfo(username=val_nickname, phone=val_cellphone)
    # 对于password属性的设置,会调用属性方法,进行加密操作
    user.password = val_password

    resp = model_commit(user)
    if resp:
        return jsonify(code=RET.DATAEXIST, msg="用户手机号已经注册")

    if val_agreement != "on":
        return jsonify(code=RET.DATAEXIST, msg="请同意协议")

    # 返回值
    resp = {"code": RET.OK, "msg": "注册成功"}
    return jsonify(resp)
コード例 #3
0
ファイル: views.py プロジェクト: lotapp/layIM-python
def login():
    val_username = request.form.get("username")
    val_password = request.form.get("password")
    val_vercode = request.form.get("vercode")
    val_image_code = request.form.get("image_code")
    val_access_token = request.form.get("access_token")
    val_remember = request.form.get("remember")

    # 校验参数
    if not all([val_username, val_password, val_vercode, val_image_code]):
        return jsonify(code=RET.PARAMERR, msg="参数不完整")

    # 判断手机号格式
    if not re.match(r"1[34578]\d{9}", val_username):
        return jsonify(code=RET.DATAERR, msg="手机号格式错误")

    # 业务逻辑
    try:
        redis_image_code = redis_store.get("image_code_%s" % val_image_code)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="查询图片验证码错误")

    if redis_image_code is None:
        return jsonify(code=RET.NODATA, msg="图片验证码过期")

    if val_vercode.lower() != redis_image_code.lower():
        return jsonify(code=RET.DATAERR, msg="图片验证码错误")

    user = UserInfo.query.filter_by(phone=val_username).first()
    if user is None:
        return jsonify(code=RET.DATAERR, msg="账号或密码错误")

    if not user.check_password(val_password):
        return jsonify(code=RET.DATAERR, msg="账号或密码错误")

    # 利用session记录用户的登录状态

    access_token = str(uuid.uuid3(uuid.NAMESPACE_URL, str(val_username)))

    session["user_id"] = user.id
    session["user_name"] = val_username
    session["access_token"] = access_token

    resp = {
        "code": RET.OK,
        "msg": "登陆成功",
        "data": {
            "access_token": access_token
        }
    }
    # 删除验证码
    try:
        redis_store.delete("image_code_%s" % val_username)
    except Exception as e:
        current_app.logger.error(e)

    return jsonify(resp)
コード例 #4
0
ファイル: views.py プロジェクト: lotapp/layIM-python
def get_image():
    image_code = request.args.get("code")
    image_code = "image_" + image_code
    image = redis_store.get(image_code)

    # 返回验证码图片
    resp = make_response(image)
    resp.headers["Content-Type"] = "image/jpg"
    return resp
コード例 #5
0
def send_sms_code():

    # 1.获取数据
    print(request)
    json_dict = request.json
    print(json_dict)
    phone_number = json_dict.get('mobile')
    client_image_code = json_dict.get("image_code")
    image_code_id = json_dict.get("image_code_id")

    # 2.检验数据
    if not all([phone_number, client_image_code, image_code_id]):
        return jsonify(errno=response_code.RET.PARAMERR, errmsg="缺少必传参数")
    if not re.match("^1[3-8]\d{9}$", phone_number):
        return jsonify(errno=response_code.RET.PARAMERR, errmsg="电话号码有误")
    try:
        server_image_code = redis_store.get("imageID:" + image_code_id)

    except Exception as e:
        logging.error(e)
        return jsonify(errno=response_code.RET.DBERR, errmsg='查询图片验证码失败')

    if not server_image_code:
        return jsonify(errno=response_code.RET.NODATA, errmsg='图片验证码不存在')

    if client_image_code.lower() != server_image_code.lower():
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='验证码输入有误')

    sms_code = "%06d" % random.randint(0, 999999)
    # print(sms_code)
    logging.debug(sms_code)
    # 调用阿里云接口发送验证码
    __business_id = uuid.uuid1()
    code_json = "{'code':" + sms_code + "}"
    res = json.loads(
        send_sms(__business_id, phone_number, "hcf1425", "SMS_145595939",
                 code_json).decode())
    status = res.get('Code')
    # print(res)

    if status != "OK":
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='短信发送失败')

    try:
        redis_store.set("SMS:" + phone_number, sms_code,
                        constants.SMS_CODE_REDIS_EXPIRES)

    except Exception as e:
        logging.error(e)
        return jsonify(errno=response_code.RET.DATAERR, errmsg='存储短信失败')

    # 8.返回短信验证码发送的结果
    return jsonify(errno=response_code.RET.OK, errmsg='发送短信成功')
コード例 #6
0
def verify_code():
    # 验证手机号和验证码
    phone = request.form.get('phone')
    msg_code = request.form.get('msg_code')
    print(phone)
    # 校验参数是否为空
    if not all([phone, msg_code]):
        return jsonify(phone=phone, msg_code=msg_code, msg='有参数为空')
    # 校验手机号码是否合法
    if not re.match(r'1[3456789]\d{9}', phone):
        return jsonify(msg='手机号码不合法')
    # 校验验证码是否一致
    try:
        # 取到是bytes类型
        save_code = redis_store.get('msg_%s' % phone).decode()
        print(save_code)
        if save_code == msg_code:
            print('与本地一致')
        else:
            return jsonify(err_msg='msg_code error')
    except Exception as e:
        logging.error(e)
        return jsonify(msg='redis error')
    # 如果不存在则创建用户
    user_obj = User.query.filter_by(phone=phone).first()

    try:
        if user_obj:
            print('用户已存在')
        else:
            print('用户不存在则创建')
            user_obj = User(phone=phone)
            db.session.add(user_obj)
            db.session.commit()
    except Exception as e:
        print(e)
        db.session.rollback()
        return jsonify(msg='mysql error')

    # 添加到session,也就是存在不存在都登录
    session['user_id'] = user_obj.id
    session['user_phone'] = phone
    # 响应
    return jsonify(msg='ok')
コード例 #7
0
def register():
    # 1.接受参数
    print("正在注册..............")
    json_dict = request.json
    phone_num = json_dict.get("mobile")
    client_sms_code = json_dict.get("smscode")
    password = json_dict.get("password")

    # 2. 校验参数
    if not all([phone_num, client_sms_code, password]):
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='参数不完整')

    try:
        server_sms_code = redis_store.get("SMS:" + phone_num)

    except Exception as e:
        logging.error(e)
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='数据库查询异常')

    if client_sms_code.lower() != server_sms_code.lower():
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='验证码输入有误')

    # 3.进行注册,将用户数据记录到数据
    user = Users()
    user.mobile = phone_num
    user.nick_name = phone_num
    user.password = password

    # 记录用户登录时间
    user.last_login = datetime.datetime.now()

    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        logging.error(e)
        return jsonify(errno=response_code.RET.PARAMERR, errmsg='数据库异常')

    # 4.状态保持
    session["user_id"] = user.id

    # 5.响应注册成功
    return jsonify(errno=response_code.RET.OK, errmsg='注册成功')
コード例 #8
0
def cat_detail():
    # 这个是详情页,只需要获取car_id
    car_id = request.args.get('car_id')
    car_obj = Car.query.get(car_id)
    # 检验数据是否为空
    if not car_obj:
        return jsonify(errcode=constant.RET_CAR_NOTFOUND, errmsg='car_id出错')
    # todo 当用户登录的情况下,存储car_id到redis数据库8中,类型用列表,有个g变量存了user_id
    user_id = session.get('user_id')
    if user_id:
        try:
            history_key = 'history_%s' % user_id
            # 可能插入重复,所以要删除原来的再加入
            redis_store.lrem(history_key, 0, car_id)
            # 进行存储,左插入,获取使用lrange
            redis_store.lpush(history_key, car_id)
        except Exception as e:
            print(e)
            return jsonify(errcode=constant.RET_REDIS_INSERT_ERR,
                           errmsg='redis插入错误')

    print(request.args)
    print(car_obj)  # todo 获取到了这辆车,然后展示六个表内容和图片,to_detail_dict()
    # todo 防止频繁访问mysql,存进redis
    redis_key = 'mysql-redis_%s' % car_id  # 存进redis的key名
    redis_data = redis_store.get(redis_key)
    if redis_data:
        # 注意bytes转码
        ret_dict = redis_data.decode()
    else:
        # 字典存进redis要序列化
        try:
            ret_dict = json.dumps(car_obj.to_detail_dict())
            redis_store.set(redis_key, ret_dict,
                            constant.CAR_INFO_REDIS_EXPIRES)
        except Exception as e:
            print(e)
            return jsonify(errcode=constant.RET_REDIS_INSERT_ERR,
                           errmsg='redis插入错误')
    # 返回信息,和data
    ret_dict = json.loads(ret_dict)
    return jsonify(msg='ok', data=ret_dict)
コード例 #9
0
ファイル: info.py プロジェクト: JAZ-C/jobspider
 def post(self, address):
     """
     :param address: 搜索城市
     post的数据
     info_id:选择的地址ID  "info_id: 50488"
     search_month:搜索的月份  "search_month: 10"
     search_year: 搜索的年份  "search_year: 2018"
     search_datetime: 搜索的日期,当需要查询某一天的具体时间的时候才传入这个字段的数据,其他时候不传,该数据的月份年份需与
                 search_month,search_year相同 "search_datetime: 10/16/2018"
     :return:
         如果有search_datetime这个字段, 则返回当日可用时间:["09:00 AM", "12:00 PM", "03:00 PM"]
         如果没有,则返回当月可选日期 ['10/11/2018', '10/13/2018', '10/16/2018', '10/17/2018', '10/20/2018',
         '10/29/2018', '11/01/2018', '11/05/2018', '11/08/2018', '11/15/2018', '11/22/2018', '11/29/2018']
     """
     args = parser.parse_args()
     info_id = args.get('info_id')
     search_month = args.get('search_month')
     search_year = args.get('search_year')
     search_datetime = args.get('search_datetime')
     search_data = dict(
         zip(['id', 'month', 'year', 'datetime'],
             [info_id, search_month, search_year, search_datetime]))
     redis_key = address + info_id + "_" + search_month+ "_" + search_year if not search_datetime \
         else address + info_id + "_" + search_datetime
     rv = redis_store.get(redis_key)
     code = 200
     if not rv:
         try:
             rv = self.sp.doSearchData(address, search_data)
             redis_store.set(redis_key, rv)
             redis_store.expire(redis_key, 1296000)  #设置过期时间为15天
         except Exception as e:
             print(e)
             code = 500
             rv = []
     else:
         rv = eval(rv)
     return jsonify({"code": code, "data": rv})
コード例 #10
0
ファイル: info.py プロジェクト: JAZ-C/jobspider
 def get(self, address):
     openId = request.args["openId"]
     user = User.query.filter_by(openId=openId).first()
     if user is None:
         return []
     rv = redis_store.get(address)
     if not rv:
         try:
             results = self.sp.doSearchData(address)
             redis_store.set(address, results)
             redis_store.expire(address, 1296000)  #设置过期时间为15天
             rv = {address: results}
             rv["code"] = 200
             # user.sharedNum = (user.sharedNum - 1) if user.sharedNum > 1 else 0
             # db.session.add(user)
             # db.session.commit()
         except Exception as e:
             print(e)
             rv = {"code": 500, "msg": "Get Address Info List Fail!"}
     else:
         rv = {address: eval(rv)}
         rv["code"] = 200
     return jsonify(rv)
コード例 #11
0
    def post(self):
        """
        发送手机验证码
        1. 取得参数:
            手机号 图片验证码 图片验证码uuid
        2. 判断参数是否有值,是否符合规则
        3. 从redis去去取图片验证码的text对比用户传来的是否一致
            如果不一致,返回验证码错误
        4. 一致,生成验证码的内容(随机数据)
        5. 发送手机验证码
        6. 保存手机验证码到redis中
        6. 返回数据,告知发送结果
        :return: 告知发送手机验证码结果
        """

        # 1.取得参数
        # params_dict = json.loads(request.data)
        params_dict = request.json

        #  1. 取得参数:
        #  手机号 图片验证码 图片验证码uuid
        phone = params_dict.get("mobile", None)
        image_code = params_dict.get("image_code", None)
        image_uuid = params_dict.get("image_code_id", None)

        # 2. 判断参数是否有值,是否符合规则
        if not all([phone, image_code, image_uuid]):
            return jsonify(errno=RET.PARAMERR, errmsg="传入参数有误")

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

        try:
            frequently_sms = redis_store.get("Frequently_SMS_" + phone)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

        if frequently_sms:
            return jsonify(errno=RET.REQERR, errmsg="请求频繁")

        # 3. 从redis去去取图片验证码的text对比用户传来的是否一致
        try:
            real_image_code = redis_store.get("imageCodeId:" + image_uuid)
            redis_store.delete("imageCodeId:" + image_uuid)
        except Exception as e:
            current_app.logger.error("redis获取图片验证码错误:" + str(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="图片验证码输入错误")

        try:
            user = User.query.filter_by(mobile=phone).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
        if user:
            # 该手机已被注册
            return jsonify(errno=RET.DATAEXIST, errmsg="该手机已被注册")

        # 5. 生成验证码的内容(随机数据)
        sms_code = "%06d" % random.randint(0, 999999)

        # TODO 方便测试,记得删除
        current_app.logger.error("当前{}手机的验证码为: {}".format(phone, sms_code))

        # 6. 发送手机验证码
        result = ccp.send_template_sms(
            phone, [sms_code, constants.SMS_CODE_REDIS_EXPIRES / 60], 1)

        try:
            redis_store.setex("Frequently_SMS_:" + phone, 60, 1)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

        # 4. 保存手机验证码文字到redis
        try:
            redis_store.setex("SMS_:" + phone,
                              constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        except Exception as e:
            current_app.logger.error("redis保存手机验证码错误:" + str(e))
            return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

        if result != 0:
            current_app.logger.error("第三方发送手机验证码错误")
            return jsonify(errno=RET.SERVERERR, errmsg="发送手机验证码失败")
        return jsonify(errno=RET.OK, errmsg="发送手机验证码成功")
コード例 #12
0
    def post(self):
        """
        注册用户
        1. 取得参数
        2. 判断参数是否有值
        3. 取到数据库保存的真实手机验证码验证是否一致
        4. 一致,初始化User模型,创建用户
        5. 不一致,返回手机验证码错误
        6. 返回响应
        :return: 返回响应
        """

        params_dict = request.json

        #  1. 取得参数:
        #  手机号 图片验证码 图片验证码uuid
        phone = params_dict.get("mobile", None)
        sms_code = params_dict.get("sms_code", None)
        password = params_dict.get("password", None)

        # 2. 判断参数是否有值,是否符合规则
        if not all([phone, sms_code, password]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

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

        # 3. 取到数据库保存的真实手机验证码验证是否一致
        try:
            real_sms_code = redis_store.get("SMS_:" + phone)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

        # 数据为空,即是验证码已过期
        if not real_sms_code:
            return jsonify(errno=RET.NODATA, errmsg="手机验证码过期")

        # 判断手机验证码是否一致
        if real_sms_code != sms_code:
            return jsonify(errno=RET.DATAERR, errmsg="手机验证码输入错误")

        # 删除短信验证码
        try:
            redis_store.delete("SMS_:" + phone)
        except Exception as e:
            current_app.logger.error(e)

        # 4. 一致,初始化User模型,创建用户
        user = User()
        user.mobile = phone
        # 没有nickname,默认保存手机号
        user.nick_name = phone
        # 保存用户最后一次登录时间
        user.last_login = datetime.now()
        # 密码的处理,已经在模型中处理密码加密
        user.password = password

        # 添加到数据库
        try:
            db.session.add(user)
            db.session.commit()
        except Exception as e:
            current_app.logger.error("创建用户到数据库失败:" + str(e))
            db.session.rollback()
            return jsonify(errno=RET.DBERR, errmsg="数据库错误")

        # 登录,添加用户信息到session中
        session["user_id"] = user.id
        session["mobile"] = user.mobile
        session["nick_name"] = user.nick_name

        # 5. 返回响应
        return jsonify(errno=RET.OK, errmsg="注册成功")
コード例 #13
0
ファイル: views.py プロジェクト: lotapp/layIM-python
def sms():
    val_vercode = request.form.get("vercode")
    val_phone = request.form.get("phone")
    val_uuid = request.form.get("uuid")

    # 校验参数
    if not all([val_uuid, val_vercode, val_phone]):
        return jsonify(code=RET.PARAMERR, msg="参数不完整")

    # 业务处理
    # 取出真实的图片验证码
    try:
        real_image_code = redis_store.get("image_code_%s" % val_uuid)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="获取图片验证码失败")

    # 判断验证码的有效期
    if real_image_code is None:
        # 表示redis中没有这个数据
        return jsonify(code=RET.NODATA, msg="图片验证码过期")

    # 判断用户填写的验证码与真实的验证码
    if real_image_code.lower() != val_vercode.lower():
        # 表示用户填写错误
        return jsonify(code=RET.DATAERR, msg="图片验证码有误")

    # 判断用户手机号是否注册过
    try:
        user = UserInfo.query.filter_by(phone=val_phone).first()
    except Exception as e:
        current_app.logger.error(e)
    else:
        if user is not None:
            # 用户已经注册过
            return jsonify(code=RET.DATAEXIST, msg="用户手机号已经注册过")

    # 创建短信验证码
    sms_code = "%06d" % random.randint(0, 999999)

    # 保存短信验证码
    try:
        redis_store.setex("sms_code_%s" % val_phone,
                          constants.SMS_CODE_REDIS_EXPIRES, sms_code)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="保存短信验证码异常")

    # 发送验证码短信
    # try:
    #     ccp = CCP()
    #     result = ccp.send_template_sms(val_phone, [sms_code, str(constants.SMS_CODE_REDIS_EXPIRES / 60)], 1)
    # except Exception as e:
    #     current_app.logger.error(e)
    #     return jsonify(code=RET.THIRDERR, msg="发送短信异常")
    result = 0

    if result == 0:
        # 发送成功
        # 删除redis中的图片验证码
        try:
            redis_store.delete("image_code_%s" % val_uuid)
        except Exception as e:
            current_app.logger.error(e)

        # return jsonify(code=RET.OK, msg="发送短信成功")
        return jsonify(code=RET.OK, msg="发送短信成功", data={"code": sms_code})
    else:
        return jsonify(code=RET.THIRDERR, msg="发送短信失败")