Beispiel #1
0
 def post(self):
     """
     post方法,添加用户,会进行参数校验
     账号的长度限制在4-18位之间 并且
     :return:
     """
     response = Response()
     args = parser.parse_args()
     valid = UserValid()
     add_arg(valid, args)
     ret = valid.valid_data()
     connection = pool.connection()
     if ret:
         response.data = ret
         response.errno = len(ret)
         response.code = 405
         return jsonify(response.dict_data)
     try:
         ret = self._add_user(args, connection)
         response.data = ret
     except UserAlreadyExistException as e:
         response.code = 405
         response.errno = 1
         response.data = {"msg": str(e)}
     except Exception:
         response.code = 500
         response.data = trace()
         response.errno = 1
     finally:
         connection.close()
     return jsonify(response.dict_data)
Beispiel #2
0
 def get(self):
     response = Response()
     try:
         _id = request.args["id"]
         course = fetchone_dict(SelectMap.course_by_id, [_id, ], CourseTemplate)
         if course is None:
             raise UserDoesNotExistException("课程不存在")
         response.data = {
             "id": course.id, "name": course.name,
             "level": course.level, "type": course.type,
             "burning": course.burning
         }
     except KeyError:
         response.code = FORMAT_ERROR
         response.errno = 1
         response.data = {"msg": "缺少id"}
     except UserDoesNotExistException:
         response.code = FORMAT_ERROR
         response.errno = 1
         response.data = {"msg": "课程不存在"}
     except Exception as e:
         response.code = 500
         response.errno = 1
         response.data = {"msg": str(e)}
     return jsonify(response.dict_data)
Beispiel #3
0
 def delete(self):
     response = Response()
     try:
         user_id = request.json["id"]
         connection = pool.connection()
         response = self._delete_user(user_id, connection)
     except UserDoesNotExistException as e:
         response.code = 405
         response.errno = 1
         response.data = {"msg": str(e)}
     except KeyError:
         response.code = 405
         response.errno = 1
         response.data = {"msg": "你必须传一个id"}
     return jsonify(response.dict_data)
Beispiel #4
0
 def _delete_user(self, user_id, connection):
     """
     删除一个用户的具体逻辑,包括判断用户是否存在等,此方法如果用户不存在会
     抛出异常
     :param user_id: 想要删除的用户的id
     :param connection: 数据库连接的conn对象
     :return: 抛出异常或者返回response对象
     """
     cursor = connection.cursor()
     user = get_one(cursor, SelectMap.user_valid_by_id, user_id)
     response = Response()
     if user:
         try:
             ret1 = delete_sql_execute(cursor, DeleteMap.user_by_id,
                                       user_id)
             ret2 = delete_sql_execute(cursor,
                                       DeleteMap.user_info_by_user_id,
                                       user_id)
             connection.commit()
             response.data = {"msg": ret1 + ret2}
         except Exception as e:
             connection.rollback()
             connection.commit()
             response.code = 500
             response.errno = 1
             response.data = {"msg": "内部错误:" + str(e)}
         finally:
             cursor.close()
             connection.close()
             return response
     raise UserDoesNotExistException("用户不存在")
Beispiel #5
0
def post(valid_class, parse, template):
    """
    一些固定的对象的方法模板 多用于post和put
    :param valid_class:
    :param parse:
    :param template:
    :return:
    """
    if isinstance(parse, dict):
        valid = valid_class(parse)
    elif isinstance(parse, reqparse.RequestParser):
        valid = valid_class(parse.parse_args())
    else:
        raise ValueError("parse must be dict or RequestParser")
    err_map = valid.valid_data()
    if err_map:
        response = Response()
        response.data = err_map
        response.errno = len(err_map)
        response.code = FORMAT_ERROR
        return response
    clean_data = valid.clean_data
    # for key in template.__dict__:
    #     if template.__dict__[key] is None:
    #         setattr(template, key, clean_data[key])
    for key in clean_data:
        if not key.startswith("_"):
            setattr(template, key, clean_data[key])
Beispiel #6
0
 def post(self):
     """
     文件上传的接口,可以上传多个文件
     :return:
     """
     files = request.files.getlist(current_app.config["UPLOAD_FILE_KEY"])
     response = Response()
     media_url = current_app.config["MEDIA_URL"]
     media_dir = current_app.config["MEDIA_DIR"]
     err_list = []
     suffix_list = []
     for f in files:
         if is_safe(f.filename):
             suffix_list.append(get_suffix(f.filename))
             continue
         err_list.append(f.filename)
     if err_list:
         response.errno = len(err_list)
         response.code = FORMAT_ERROR
         response.data = {"msg": "错误的文件类型:" + ",".join(err_list)}
         return jsonify(response.dict_data)
     file_url = []
     for index, f in enumerate(files):
         file_name = generate_filename() + "." + suffix_list[index]
         path = os.path.join(media_dir, file_name)
         file_name = self._save(f, path, file_name)
         file_url.append({
             "url": os.path.join(media_url, file_name),
             "filename": file_name
         })
     response.data = {"msg": file_url}
     return jsonify(response.dict_data)
Beispiel #7
0
 def inner(*args, **kwargs):
     response = Response()
     user_permission = getattr(g, "user", {}).get("permission", 0)
     if permission & user_permission == permission:
         return func(*args, **kwargs)
     else:
         response.code = PERMISSION_ERROR
         response.errno = 1
         response.data = {"msg": "权限不足"}
         return jsonify(response.dict_data)
Beispiel #8
0
 def inner(*args, **kwargs):
     response = Response()
     key = current_app.config["AUTH_CODE_SESSION_KEY"]
     try:
         auth_code = session[key].lower()
         code = request.args.get(key).lower()
         if code != auth_code:
             raise InvalidArgumentException()
         ret = func(*args, **kwargs)
         session.clear()
         return ret
     except (KeyError, AttributeError):
         response.code = FORMAT_ERROR
         response.errno = 1
         response.data = {"msg": "验证码已失效 重新输入"}
     except InvalidArgumentException:
         response.code = FORMAT_ERROR
         response.errno = 1
         response.data = {"msg": "验证码校验错误"}
     return jsonify(response.dict_data)
Beispiel #9
0
def jwt_handler():
    """
    json web token的处理函数,如果携带了token 则处理 否则略
    :return:
    """
    if request.is_json:
        token = request.json.get("token")
    elif request.method != "GET":
        token = request.form.get("token")
    else:
        token = request.args.get("token")
    if token is not None:
        response = Response()
        try:
            header, payload, signature = token.split(".")
            header = decode_base64(header)
            payload = decode_base64(payload)
            payload_handler(payload)
            alg = header_handler(header)
            signature_handler(header, payload, signature, alg)
        except TokenTimeOutException as e:
            response.code = PERMISSION_ERROR
            response.errno = 1
            response.data = {"msg": str(e)}
        except (KeyError, IndexError, IllegalTokenException) as e:
            response.code = FORMAT_ERROR
            response.errno = 1
            response.data = {"msg": "错误的token:" + str(e)}
        except ValueError:
            response.code = FORMAT_ERROR
            response.errno = 1
            response.data = {"msg": "token格式错误"}
        except Exception as e:
            response.code = SERVER_ERROR
            response.errno = 1
            response.data = {"msg": "服务端错误:" + str(e)}
        finally:
            if response.errno > 0:
                if hasattr(request, "user"):
                    delattr(request, "user")
                return jsonify(response.dict_data)
Beispiel #10
0
 def inner(*args, **kwargs):
     response = Response()
     ip = request.remote_addr
     if ip not in ip_map:
         ip_map[ip] = _IpStack(times, seconds)
     ret = ip_map[ip].append(time.time())
     if ret:
         return func(*args, **kwargs)
     else:
         response.errno = 1
         response.code = THROTTLE_ERROR
         response.data = {"msg": "请求过于频繁,稍后再试"}
         return jsonify(response.dict_data)
 def inner(*args, **kwargs):
     response = Response()
     content = f"{request.url}:{request.remote_addr}"
     md5 = hashlib.md5(current_app.config["SALT"].encode(
         current_app.config["DB_CHARSET"]))
     md5.update(content.encode(current_app.config["DB_CHARSET"]))
     val = md5.hexdigest()
     if val in content_set:
         response.code = THROTTLE_ERROR
         response.errno = 1
         response.data = {"msg": "请求正在处理中"}
         return jsonify(response.dict_data)
     content_set.add(val)
     ret = func(*args, **kwargs)
     content_set.remove(val)
     return ret
Beispiel #12
0
 def _rollback(self, upper):
     response = Response()
     user_id = getattr(request, "user")["id"]
     ret = execute_sql(UpdateMap.update_upper_by_user_and_blog,
                       (upper.blog_id, user_id))
     if ret == 0:
         response.code = FORMAT_ERROR
         response.errno = 1
         response.data = {"msg": "点赞失败"}
         return response
     response.data = {
         "user_id": upper.user_id,
         "blog_id": upper.blog_id,
         "create_time": upper.create_time
     }
     return response
Beispiel #13
0
 def _real_insert(self, upper):
     response = Response()
     now = datetime.datetime.now()
     user_id = getattr(request, "user")["id"]
     ret = execute_sql(InsertMap.upper, (upper.blog_id, user_id, now), True)
     if ret == 0:
         response.code = FORMAT_ERROR
         response.errno = 1
         response.data = {"msg": "点赞失败"}
         return response
     response.data = {
         "id": ret,
         "user_id": upper.user_id,
         "blog_id": upper.blog_id,
         "create_time": now
     }
     return response
Beispiel #14
0
 def get(self):
     """
     get方法的接口,获取单个的用户,通过账号密码,如果用户存在,则返回用户信息和token
     :return:
     """
     account = request.args["account"]
     password = md5(request.args["password"])
     response = Response()
     connection = pool.connection()
     cursor = connection.cursor()
     try:
         if account == "" or password == "":
             raise InvalidArgumentException("账号或密码不可为空")
         ret = get_one(cursor, SelectMap.user_info_with_login,
                       [account, password])
         if ret is None:
             raise UserDoesNotExistException("错误的用户名或密码")
         response.data = {
             "id": ret[0],
             "account": ret[1],
             "permission": ret[2],
             "phone": ret[3],
             "email": ret[4],
             "gender": ret[5],
             "avatar": ret[6],
             "description": ret[7],
             "nick_name": ret[10],
             "create_time": ret[9],
             "age": ret[11],
             "token": self._make_jwt(ret)
         }
     except UserDoesNotExistException as e:
         init_key_error_handler(response, e, "提示:")
     except Exception as e:
         response.code = 500
         response.errno = 1
         response.data = {"msg": "获取用户失败:" + str(e)}
     finally:
         cursor.close()
         connection.close()
     return jsonify(response.dict_data)
Beispiel #15
0
 def post(self):
     valid = CourseValid(parse.parse_args())
     err_map = valid.valid_data()
     response = Response()
     if err_map:
         response.data = err_map
         response.errno = len(err_map)
         response.code = FORMAT_ERROR
         return jsonify(response.dict_data)
     try:
         data = valid.clean_data
         execute_sql(InsertMap.course, [
             data["type"], data["name"], datetime.datetime.now(),
             data["level"], data["burning"]
         ])
         ret = execute_query_sql(SelectMap.course_by_create, [data["name"], ], lambda c: c.fetchone())
         response.data = {
             "id": ret[0], "type": ret[1], "name": ret[2], "create_time": ret[3],
             "level": ret[4], "burning": ret[5]
         }
     except Exception as e:
         init_key_error_handler(response, e, "插入数据失败:")
     return jsonify(response.dict_data)
Beispiel #16
0
 def put(self):
     """
     修改挑战的接口 和post接口相比 需要多传一个id的key 如果id不存在 则无法执行
     :return:
     """
     challenge = ChallengeTemplate()
     response = post(ChallengeValid, parse, template=challenge)
     if response is None:
         response = Response()
         try:
             _id = challenge.id
             ret = execute_sql(UpdateMap.update_challenge_by_id, [
                 challenge.picture, challenge.content, challenge.start_time,
                 challenge.end_time, _id
             ])
             if ret == 0:
                 raise InvalidArgumentException("数据不存在")
         except InvalidArgumentException as e:
             response.errno = 1
             response.code = 403
             response.data = {"msg": str(e)}
         except Exception as e:
             init_key_error_handler(response, e, "信息:")
     return jsonify(response.dict_data)