Example #1
0
def set_user_avatar():
    """
    设置用户头像
    参数: 图片(多媒体表单), 用户Iid
    :return:
    """
    image_file = request.files.get('avatar')

    if image_file is None:
        return R.err(RET.PARAMERR, '未上传图片')

    file_path = '/static/upload/' + secure_filename(image_file.filename)
    file_save_path = 'base' + file_path

    print(file_save_path)

    try:
        image_file.save(file_save_path)
    except Exception as e:
        current_app.logger.error(e)
        return R.err(RET.DATAERR, '保存图片文件失败')

    try:
        User.query.filter_by(id=g.user_id).update({'avatar_url': file_path})
        db_.session.commit()
    except Exception as e:
        db_.session.rollback()
        current_app.logger.error(e)
        return R.err(RET.DBERR, '保存图片信息失败')

    return R.ok('保存成功', {'avatar_url': file_path})
Example #2
0
def update():
    """
    修改用户
    参数格式: JSON
    :return:
    """

    # 获取前端JSON数据,返回字典
    req_dict = request.get_json()

    name = req_dict.get('name')
    mobile = req_dict.get('mobile')
    avatar_url = req_dict.get('avatar_url')

    # 判断手机号格式
    if mobile is not None:
        if not re.match(regex.MOBILE_RE, mobile):
            return R.err(RET.PARAMERR, '手机号格式错误')

    # 查询用户信息
    try:
        user = User.query.filter_by(id=g.user_id).first()
    except Exception as e:
        current_app.logger.error(e)
        return R.err(RET.DBERR, '数据库异常')

    if name is not None:
        user.name = name

    if mobile is not None:
        user.mobile = mobile

    if avatar_url is not None:
        user.avatar_url = avatar_url

    try:
        db_.session.commit()
    except IntegrityError as e:
        # 数据库操作失败后回滚
        db_.session.rollback()
        # 表示出现重复值
        current_app.logger.error(e)
        return R.err(RET.DATAEXIST, '用户以存在')
    except Exception as e:
        # 数据库操作失败后回滚
        db_.session.rollback()
        current_app.logger.error(e)
        return R.err(RET.DBERR, '数据库异常')

    return R.ok('修改成功')
Example #3
0
def get_image_code(uuid):
    """
    图片验证码
    :param uuid: 验证码编号, UUID
    :return:
    """
    # 生成验证码图片
    captcha = Captcha()

    # 名字, 真实文本, 图片数据
    name, text, image_data = captcha.generate_captcha()

    # 将验证码保存到redis中
    try:
        redis_.setex(RedisKeys.image_code_key(uuid),
                     constants.IMAGE_CODE_REDIS_EXPIRES, text)
    except Exception as e:
        current_app.logger.error(e)
        return R.err(RET.DBERR, '保存图片验证码失败')

    # 创建返回对象
    resp_ = make_response(image_data)
    resp_.headers['Content-Type'] = 'image/jpg'

    # 设置cookie值, csrf防护
    resp_.set_cookie('csrf_token', csrf.generate_csrf())

    return resp_
Example #4
0
def page_list():
    """
    分页查询
    :return:
    """

    page = Page()

    page.page = request.args.get('page')
    page.limit = request.args.get('limit')
    user_name = request.args.get('user_name')

    # 过滤条件的参数容器
    filter_params = []

    # 用户名
    if user_name:
        filter_params.append(User.user_name.ilike('%{}%'.format(user_name)))

    # 排序条件
    house_query = User.query.filter(*filter_params).order_by(
        User.create_time.desc())

    # 处理分页
    try:
        page_obj = house_query.paginate(page=page.page,
                                        per_page=page.limit,
                                        error_out=False)
    except Exception as e:
        current_app.logger.error(e)
        return R.err(RET.DBERR, '数据库异常')

    # 获取页面数据
    user_li = page_obj.items
    users = [user.to_dict() for user in user_li]
    page.list = users

    # 总页数
    page.total_page = page_obj.pages

    # 总条数
    page.total_count = page_obj.total

    return R.ok('OK', page.to_dict())
Example #5
0
def check_token():

    oauth_str = OauthFilter.check_url_oauth(request.path)

    if oauth_str != 'anon':
        token = request.headers.get('token')
        if token is None:
            token = request.args.get('token')
        try:
            user_token = sys_models.UserToken.query.filter_by(
                token=token).first()
        except Exception as e:
            current_app.logger.error(e)
            return R.err(RET.TOKENINVALID, 'token 失效')
        else:
            if user_token is None:
                return R.err(RET.TOKENINVALID, 'token 失效')

            if datetime.now() >= user_token.expire_time:
                return R.err(RET.TOKENINVALID, 'token 失效')
            # 传递参数
            g.user_id = user_token.user.id
Example #6
0
def task():
    """
    定时任务 返回数据
     - 通过get方法能获取celery异步执行结果
     - get 方法默认是阻塞的行为, 会等到有了执行结果子后才返回
     - get 方法也接受参数timeout, 超时时间, 超时后立即返回
    """
    result = demo2.delay()

    data = {
        'id': result.id,
        'data': result.get(),
    }

    return R.ok('OK', data)
Example #7
0
def delete():
    """
    删除用户
    参数格式: JSON
    :return:
    """

    # 获取前端JSON数据,返回字典
    req_dict = request.get_json()

    user_id = req_dict.get('user_id')

    # 查询用户信息
    try:
        user = User.query.filter_by(id=user_id).first()
        db_.session.delete(user)
        db_.session.commit()
    except Exception as e:
        # 数据库操作失败后回滚
        db_.session.rollback()
        current_app.logger.error(e)
        return R.err(RET.DBERR, '数据库异常')

    return R.ok('删除成功')
Example #8
0
def task():
    """无参数定时任务"""
    demo1.delay('/task/test1')
    return R.ok('OK')
Example #9
0
def task():
    """无参数定时任务"""
    demo.delay()
    return R.ok('OK')
Example #10
0
def add():
    """
    添加用户
    参数格式: JSON
    :return:
    """

    # 获取前端JSON数据,返回字典
    req_dict = request.get_json()

    user_name = req_dict.get('user_name')
    image_code = req_dict.get('image_code')
    image_code_id = req_dict.get('image_code_id')
    password = req_dict.get('password')
    password2 = req_dict.get('password2')

    name = req_dict.get('name')
    mobile = req_dict.get('mobile')
    avatar_url = req_dict.get('avatar_url')

    # 校验参数
    if not all([user_name, image_code, password]):
        return R.err(RET.PARAMERR, '参数不完整')

    # 密码校验
    if password != password2:
        return R.err(RET.PARAMERR, '两次输入密码不一致')

    # 判断手机号格式
    if mobile is not None:
        if not re.match(regex.MOBILE_RE, mobile):
            return R.err(RET.PARAMERR, '手机号格式错误')

    # 取出图片验证码
    try:
        real_image_code = redis_.get(RedisKeys.image_code_key(image_code_id))
    except Exception as e:
        current_app.logger.error(e)
        return R.err(RET.DBERR, '读取真实图片验证码异常')

    # 判断图片验证码
    if real_image_code is None:
        return R.err(RET.NODATA, '图片验证码失效')

    # 判断用户填写的图片验证码
    if real_image_code.upper().decode('ascii') != image_code.upper():
        return R.err(RET.DATAERR, "图片验证码错误")

    # 删除redis中的短信验证码,防止重复使用
    try:
        redis_.delete(RedisKeys.image_code_key(image_code_id))
    except Exception as e:
        current_app.logger.error(e)

    # 保存用户数据
    user = User()

    user.user_name = user_name
    user.mobile = mobile
    user.name = name
    user.avatar_url = avatar_url

    user.password = password
    try:
        db_.session.add(user)
        db_.session.commit()
    except IntegrityError as e:
        # 数据库操作失败后回滚
        db_.session.rollback()
        # 表示出现重复值
        current_app.logger.error(e)
        return R.err(RET.DATAEXIST, '用户名以存在')
    except Exception as e:
        # 数据库操作失败后回滚
        db_.session.rollback()
        current_app.logger.error(e)
        return R.err(RET.DBERR, '数据库异常')

    return R.ok('注册成功')
Example #11
0
def login():
    """
    用户登陆
    参数: 用户名,密码,验证码
    """
    req_dict = request.get_json()

    user_name = req_dict.get('user_name')
    password = req_dict.get('password')
    image_code = req_dict.get('image_code')
    image_code_id = req_dict.get('image_code_id')

    # 校验参数
    if not all([user_name, password, image_code, image_code_id]):
        return R.err(RET.PARAMERR, '参数不完整')

    # 判断验证码
    try:
        real_image_code = redis_.get(RedisKeys.image_code_key(image_code_id))
    except Exception as e:
        current_app.logger.error(e)
        return R.err(RET.DBERR, 'redis数据库异常')

    # 判断图片验证码是否过期
    if real_image_code is None:
        return R.err(RET.DBERR, '图片验证码失效')

    # 删除 图片验证码
    try:
        redis_.delete(RedisKeys.image_code_key(image_code_id))
    except Exception as e:
        current_app.logger.error(e)

    # 对比用户输入
    if real_image_code.upper().decode('ascii') != image_code.upper():
        return R.err(RET.DATAERR, '验证码错误')

    # 判断错误次属是否超过限制,如果超过限制则返回
    user_ip = request.remote_addr  # 用户的IP地址

    try:
        access_nums = redis_.get(RedisKeys.access_err_num_key(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:
            return R.err(RET.REQERR, '错误次数过多,请稍后重试')

    try:
        user = User.query.filter_by(user_name=user_name).first()
    except Exception as e:
        current_app.logger.error(e)
        return R.err(RET.DBERR, '获取用户信息失败')

    if user is None or not user.check_password(password):
        try:
            redis_.incr(RedisKeys.access_err_num_key(user_ip))
            redis_.expire(RedisKeys.access_err_num_key(user_ip),
                          constants.LOGIN_ERROR_FORBID_TIME)
        except Exception as e:
            current_app.logger.error(e)
        return R.err(RET.DATAERR, '用户名或密码错误')

    # 校验用户是否生成token
    user_token = None
    try:
        user_token = UserToken.query.filter(user_id=user.id).first()
    except Exception as e:
        current_app.logger.error(e)

    # 生成 token
    token_data, expire_time = TokenUtil.create_token(user_name=user.user_name,
                                                     user_id=user.id)

    # 判断 是否生成token
    if user_token is None:
        try:
            user_token = UserToken()
            user_token.user_id = user.id
            user_token.token = token_data
            user_token.expire_time = expire_time

            db_.session.add(user_token)
            db_.session.commit()
        except Exception as e:
            db_.session.rollback()
            current_app.logger.error(e)
            return R.err(RET.DBERR, '数据库异常')
    else:
        user_token.token = token_data
        user_token.expire_time = expire_time

        try:
            db_.session.commit
        except Exception as e:
            db_.session.rollback()
            current_app.logger.error(e)
            return R.err(RET.DBERR, '数据库异常')

    # 生成result
    result_data = {'token': token_data, 'expire_time': expire_time}
    return R.ok('登录成功', result_data)