Exemplo n.º 1
0
    def post(self, request):
        req_data = request.data

        token_string = req_data.get('token')
        username = req_data.get('username')
        password = req_data.get('password')

        if not token_string:
            auth_user = authenticate(username=username, password=password)
        else:
            token_obj = Token.objects.select_related('user').filter(
                key=token_string
            ).first()
            if token_obj:
                auth_user = token_obj.user
            else:
                raise RsError('生成token失败,请检查token值')

        if auth_user:
            Token.objects.filter(user=auth_user).delete()
            token = Token.objects.create(user=auth_user)

            return Response({
                'token': token.key
            })
        else:
            raise RsError('生成token失败,请检查token值或用户信息')
Exemplo n.º 2
0
 def get(self, request):
     req_data = request.GET
     _id = req_data.get('id')
     if not _id:
         raise RsError('id不可缺少')
     cat_normal_obj = CatNormalResource.objects.filter(id=_id).first()
     if not cat_normal_obj:
         raise RsError('数据不存在')
     ser_data = CatNormalResourceListSerializer(cat_normal_obj).data
     return Response(ser_data)
Exemplo n.º 3
0
 def delete(self, request):
     req_data = request.data
     id = req_data.get('id')
     if id:
         try:
             obj = CatResource.objects.get(id=id)
             obj.delete()
         except Exception as e:
             raise RsError('不存在')
     else:
         raise RsError('id不可缺少')
     return Response({"result": True, "rows": id})
Exemplo n.º 4
0
    def post(self, request):
        req_data = request.data
        start_time = get_int_or_none(req_data.get('start_time'))
        end_time = get_int_or_none(req_data.get('end_time'))
        appid = get_int_or_none(req_data.get('appid'))
        if not all([start_time, end_time, appid]):
            raise RsError('缺少必要参数')

        algorithm_name = req_data.get('algorithm_name')
        if algorithm_name not in ["kmeans", "svdd", "random_forest"]:
            raise RsError("algorithm_name不存在")

        ser_data = get_cache_kmeans_result(appid, start_time, end_time)
        return Response(ser_data)
Exemplo n.º 5
0
 def put(self, request):
     req_data = request.data
     print(req_data)
     _id = req_data.get('id')
     if not _id:
         raise RsError('id不可缺少')
     cat_obj = CatResource.objects.filter(id=_id).first()
     if not cat_obj:
         raise RsError("id不存在")
     ser = CatResourceListSerializer(cat_obj, req_data, partial=True)
     if ser.is_valid():
         ser.save()
     else:
         raise RsError(ser.errors)
     return Response({"result": True, "id": _id})
Exemplo n.º 6
0
    def authenticate(self, request):
        http_auth = request.META.get('HTTP_AUTHORIZATION', None)

        if http_auth:
            auth_arr = http_auth.split(' ')
        else:
            raise RsError('需要token认证')

        if len(auth_arr) != 2:
            raise RsError('Token认证格式出错')

        if auth_arr[0] != self.keyword:
            raise RsError('Token认证模式为{0}'.format(self.keyword))

        return self.authenticate_credentials(request, auth_arr[1])
    def validate(self, attrs):
        request_count = attrs.get('request_count')
        fail_count = attrs.get('fail_count')
        if fail_count > request_count:
            raise RsError("失败次数不能大于请求数")

        return attrs
Exemplo n.º 8
0
    def record_api_history(self, request):
        request_info = request.META
        user_obj = request.user

        remote_addr = request_info.get('REMOTE_ADDR', None)
        method = request_info.get('REQUEST_METHOD', None)
        path_info = request_info.get('PATH_INFO', None)
        query_string = request_info.get('QUERY_STRING', None)

        # 验证用户有没有功资源平台的权限
        if not user_obj.is_superuser and 'rs_public' in path_info:
            raise RsError('用户权限禁止访问资源数据')

        # 获得post data
        post_data = request.data
        if len(post_data) > 0:
            post_data = json.dumps(post_data)
        else:
            post_data = None

        data = {
            'create_time': get_current_timestamp(),
            'update_time': get_current_timestamp(),
            'user_id': user_obj.id,
            'remote_addr': remote_addr,
            'method': method,
            'app_url': "/".join(path_info.split("/")[2:4]),
            'path_info': path_info,
            'query_string': query_string,
            'post_data': post_data,
        }
        save_api_record_task.delay(data)
Exemplo n.º 9
0
    def authenticate_credentials(self, request, token):
        token_obj = Token.objects.select_related('user').filter(
            key=token).first()

        if not token_obj:
            raise RsError('Token不合法,找不到对应的Token用户')

        if not token_obj.user.is_active:
            raise RsError('Token用户处于非激活状态')

        # 赋值用户信息
        user_obj = token_obj.user
        request.user = user_obj

        # 记录用户的请求信息
        # self.record_api_history(request)
        return token_obj.user, token_obj
Exemplo n.º 10
0
    def generate_doc_fields(self):
        if not isinstance(self.docs, dict):
            raise RsError('DOC SCHEMA 接受参数字典')

        for method_str, doc_dt in self.docs.items():
            method_location_arr = method_str.split('-')
            if len(method_location_arr) != 2:
                raise RsError('键名格式例如: `post-form`或者`get-query`')

            method = method_location_arr[0].lower()
            if method not in ('post', 'get', 'delete'):
                raise RsError('请求方法只支持`post,get,delete`')

            location = method_location_arr[1].lower()
            if location not in ('query', 'path', 'form', 'body'):
                raise RsError(
                    '请求方法的后缀只支持`query,path,form,body`,'
                    '详情参考:http://www.django-rest-framework.org/'
                    'api-guide/schemas/#location'
                )

            for dt in doc_dt:
                try:
                    field = dt[0]
                except Exception as e:
                    continue

                try:
                    description = dt[1]
                except Exception as e:
                    description = ''

                try:
                    required = dt[2]
                except Exception as e:
                    required = False

                coreapi_field = coreapi.Field(
                    field,
                    required=required,
                    location=location,
                    schema=coreschema.String(description=description))
                self.doc_fields.setdefault(
                    method, []
                ).append(coreapi_field)
Exemplo n.º 11
0
def insert_normal_cat_data(data):
    """
    使用异步,每次用bulk 批量插入 1000条数据
    :param data:
    :return:
    """
    try:
        for i in add_normal_cat_data(data):
            CatNormalResource.objects.bulk_create(i)
    except Exception as e:
        print(e)
        raise RsError('插入数据库失败')
Exemplo n.º 12
0
def insert_cat_data(start_time, end_time):
    """
    使用异步,批量插入指定时间段的cat数据
    :param start_time:
    :param end_time:
    :return:
    """
    try:
        for i in add_cat_data(start_time, end_time):
            CatNormalResource.objects.bulk_create(i)
    except Exception as e:
        print(e)
        raise RsError('插入数据库失败')