Пример #1
0
class CubesView(APIView):
    permission_classes = (permissions.IsAuthenticated,)
    workspace = None
    SET_CUT_SEPARATOR_CHAR = '~'

    def __init__(self, *args, **kwargs):
        super(CubesView, self).__init__(*args, **kwargs)
        self._fix_cut_separators()

    def _fix_cut_separators(self):
        browser.PATH_ELEMENT = r"(?:\\.|[^:%s|-])*" % self.SET_CUT_SEPARATOR_CHAR
        browser.RE_ELEMENT = re.compile(r"^%s$" % browser.PATH_ELEMENT)
        browser.RE_POINT = re.compile(r"^%s$" % browser.PATH_ELEMENT)
        browser.SET_CUT_SEPARATOR_CHAR = self.SET_CUT_SEPARATOR_CHAR
        browser.SET_CUT_SEPARATOR = re.compile(r'(?<!\\)%s' % self.SET_CUT_SEPARATOR_CHAR)
        browser.RE_SET = re.compile(r"^(%s)(%s(%s))*$" % (
            browser.PATH_ELEMENT, self.SET_CUT_SEPARATOR_CHAR, browser.PATH_ELEMENT
        ))

    def initialize_slicer(self):
        if self.workspace is None:
            try:
                config = settings.SLICER_CONFIG_FILE
                cubes_root = settings.SLICER_MODELS_DIR
            except AttributeError:
                raise ImproperlyConfigured('settings.SLICER_CONFIG_FILE and settings.SLICER_MODELS_DIR are not set.')

            self.workspace = Workspace(config=config, cubes_root=cubes_root)

    def get_cube(self, request, cube_name):
        self.initialize_slicer()
        try:
            cube = self.workspace.cube(cube_name, request.user)
        except NoSuchCubeError:
            raise Http404

        return cube

    def get_browser(self, cube):
        return self.workspace.browser(cube)

    def get_cell(self, request, cube, argname="cut", restrict=False):
        """Returns a `Cell` object from argument with name `argname`"""
        converters = {
            "time": CalendarMemberConverter(self.workspace.calendar)
        }

        cuts = []
        for cut_string in request.QUERY_PARAMS.getlist(argname):
            cuts += cuts_from_string(
                cube, cut_string, role_member_converters=converters
            )

        if cuts:
            cell = Cell(cube, cuts)
        else:
            cell = None

        if restrict:
            if self.workspace.authorizer:
                cell = self.workspace.authorizer.restricted_cell(
                    request.user, cube=cube, cell=cell
                )
        return cell

    def get_info(self):
        self.initialize_slicer()
        if self.workspace.info:
            info = OrderedDict(self.workspace.info)
        else:
            info = OrderedDict()

        info["cubes_version"] = __version__
        info["timezone"] = self.workspace.calendar.timezone_name
        info["first_weekday"] = self.workspace.calendar.first_weekday
        info["api_version"] = API_VERSION
        return info

    def assert_enabled_action(self, request, browser, action):
        features = browser.features()
        if action not in features['actions']:
            message = u"The action '{}' is not enabled".format(action)
            logging.error(message)
            raise ParseError(detail=message)

    def _handle_pagination_and_order(self, request):
        try:
            page = request.QUERY_PARAMS.get('page', None)
        except ValueError:
            page = None
        request.page = page

        try:
            page_size = request.QUERY_PARAMS.get('pagesize', None)
        except ValueError:
            page_size = None
        request.page_size = page_size

        # Collect orderings:
        # order is specified as order=<field>[:<direction>]
        order = []
        for orders in request.QUERY_PARAMS.getlist('order'):
            for item in orders.split(","):
                split = item.split(":")
                if len(split) == 1:
                    order.append((item, None))
                else:
                    order.append((split[0], split[1]))
        request.order = order

    def initialize_request(self, request, *args, **kwargs):
        request = super(CubesView, self).initialize_request(request, *args, **kwargs)
        self._handle_pagination_and_order(request)
        return request