コード例 #1
0
ファイル: views.py プロジェクト: anukat2015/datal
def embed(request, guid):
    """
    Show an embed microsite view
    """
    account = request.account
    preferences = request.preferences
    msprotocol = 'https' if account.get_preference('account.microsite.https') else 'http'
    base_uri = msprotocol + '://' + preferences['account_domain']

    try:
        visualization_revision = VisualizationDBDAO().get(request.user,
            published=True, guid=guid )

        datastream = DataStreamDBDAO().get(request.user,
            datastream_revision_id=visualization_revision["datastream_revision_id"]
        )
    except:
        return render_to_response('viewChart/embed404.html',{'settings': settings, 'request' : request})

    #VisualizationHitsDAO(visualization_revision.visualization).add(ChannelTypes.WEB)
    VisualizationHitsDAO(visualization_revision).add(ChannelTypes.WEB)

    width = request.REQUEST.get('width', False) # TODO get default value from somewhere
    height = request.REQUEST.get('height', False) # TODO get default value from somewhere

    visualization_revision_parameters = RequestProcessor(request).get_arguments(visualization_revision["parameters"])
    visualization_revision_parameters['pId'] = visualization_revision["datastream_revision_id"]
    
    command = AbstractCommandFactory('microsites').create("invoke", 
            "vz", (visualization_revision_parameters,))
    json, type = command.run()
    visualization_revision_parameters = urllib.urlencode(visualization_revision_parameters)

    return render_to_response('viewChart/embed.html', locals())
コード例 #2
0
ファイル: views.py プロジェクト: berserkwarwolf/datal
def embed(request, guid):
    """
    Show an embed microsite view
    """
    account = request.account
    preferences = request.preferences
    msprotocol = 'https' if account.get_preference('account.microsite.https') else 'http'
    base_uri = msprotocol + '://' + preferences['account_domain']

    try:
        visualization_revision = VisualizationDBDAO().get(
            preferences['account_language'], published=True, guid=guid )

        datastream = DataStreamDBDAO().get(
            preferences['account_language'],
            datastream_revision_id=visualization_revision["datastream_revision_id"]
        )
    except:
        return render_to_response('viewChart/embed404.html',{'settings': settings, 'request' : request})

    #VisualizationHitsDAO(visualization_revision.visualization).add(ChannelTypes.WEB)
    VisualizationHitsDAO(visualization_revision).add(ChannelTypes.WEB)

    width = request.REQUEST.get('width', False) # TODO get default value from somewhere
    height = request.REQUEST.get('height', False) # TODO get default value from somewhere

    visualization_revision_parameters = RequestProcessor(request).get_arguments(visualization_revision["parameters"])
    visualization_revision_parameters['pId'] = visualization_revision["datastream_revision_id"]
    
    command = AbstractCommandFactory('microsites').create("invoke", 
            "vz", (visualization_revision_parameters,))
    json, type = command.run()
    visualization_revision_parameters = urllib.urlencode(visualization_revision_parameters)

    return render_to_response('viewChart/embed.html', locals())
コード例 #3
0
    def build(self, table_id, header_row, dataset_revision_id, app):

        data = {'pId': dataset_revision_id, 'pLimit': 50}
        command = AbstractCommandFactory(app).create("load", "dt", [data])
        result = command.run()
        if not result:
            # TODO: correct handling
            raise Exception('Wrong engine answer')

        soup = BeautifulSoup(result[0])
        table = soup.find(attrs={'tableid': 'table%d' % table_id or 'table0'})
        try:
            if not table:
                raise DatasetTableNotFoundException(table_id)
            number_of_columns = len(table.findAll('tr')[0].findAll())
        except:
            logger.error("DataSourceBuilder ERROR --> %s" % result[0])
            raise

        header = ''
        if header_row is not None:
            header = "<Headers><Row>row%s</Row></Headers>" % header_row

        impl_details_xml = '<dataSource><DataStructure><Field id="%s">%s<type></type><format><languaje></languaje><country></country><style></style></format><Table>' % (
            (table_id or 'table0'), header)
        for i in range(number_of_columns):
            impl_details_xml = impl_details_xml + '<Field id="column%d"><alias></alias><type></type><format><languaje></languaje><country></country><style></style></format></Field>' % i
        impl_details_xml = impl_details_xml + '</Table></Field></DataStructure></dataSource>'
        return impl_details_xml
コード例 #4
0
ファイル: views.py プロジェクト: mxabierto/datal
def embed(request, guid):
    """
    Show an embed microsite view
    """
    account = request.account
    preferences = request.preferences
    msprotocol = "https" if account.get_preference("account.microsite.https") else "http"
    base_uri = msprotocol + "://" + preferences["account_domain"]

    try:
        visualization_revision = VisualizationDBDAO().get(preferences["account_language"], published=True, guid=guid)

        datastream = DataStreamDBDAO().get(
            preferences["account_language"], datastream_revision_id=visualization_revision["datastream_revision_id"]
        )
    except:
        return render_to_response("viewChart/embed404.html", {"settings": settings, "request": request})

    # VisualizationHitsDAO(visualization_revision.visualization).add(ChannelTypes.WEB)
    VisualizationHitsDAO(visualization_revision).add(ChannelTypes.WEB)

    width = request.REQUEST.get("width", False)  # TODO get default value from somewhere
    height = request.REQUEST.get("height", False)  # TODO get default value from somewhere

    visualization_revision_parameters = RequestProcessor(request).get_arguments(visualization_revision["parameters"])
    visualization_revision_parameters["pId"] = visualization_revision["datastream_revision_id"]

    command = AbstractCommandFactory("microsites").create("invoke", "vz", (visualization_revision_parameters,))
    json, type = command.run()
    visualization_revision_parameters = urllib.urlencode(visualization_revision_parameters)

    return render_to_response("viewChart/embed.html", locals())
コード例 #5
0
ファイル: views.py プロジェクト: Junar/datal
    def engine_call(self, request, engine_method, format=None, is_detail=True, form_class=RequestForm, serialize=True):
        mutable_get = request.GET.copy()
        mutable_get.update(request.POST.copy())
        mutable_get['output'] = format or 'json'
        
        resource = {}
        if is_detail:
            resource = self.get_object()
            mutable_get['revision_id'] = resource[self.dao_pk]
           
        items = dict(mutable_get.items())
        
        formset=formset_factory(form_class, formset=RequestFormSet)
        form = formset(items)
        if not form.is_valid():
            logger.info("form errors: %s" % form.errors)
            # TODO: correct handling
            raise Exception("Wrong arguments")        

        command = AbstractCommandFactory().create(engine_method, 
            self.data_types[0], form.cleaned_data)
        result = command.run()
        if not result:
            # TODO: correct handling
            raise Exception('Wrong engine answer')

        
        resource['result'] = result[0] if result[0] else {}
        resource['format'] = result[1]

        if serialize:
            serializer = self.get_serializer(resource)
            return Response(serializer.data)

        serializer = EngineSerializer(resource, 
            context={'dao_filename': self.dao_filename})
        if 'redirect' in serializer.data and serializer.data['redirect']:
            response = HttpResponse(mimetype='application/force-download')
            response['Content-Disposition'] = 'attachment; filename="{0}"'.format(serializer.data['filename'])
            redir = urllib2.urlopen(serializer.data['result']['fUri'])
            status = redir.getcode()
            resp = redir.read()
            if settings.DEBUG: logger.info('REDIR %d %s -- %s' % (status, redir.geturl(), redir.info()))
            response.write(resp)
            return response

        response = Response(serializer.data['result'], content_type=result[1])
        
        #TODO hacer una lista de los formatos que esperan forzar una descarga y los que se mostraran en pantalla
        output = mutable_get['output']
        if output != 'json' and output != 'html': 
            # reemplazar la extension si la tuviera
            filename = serializer.data['filename']
            name = filename if len(filename.split('.')) == 1 else '.'.join(filename.split('.')[:-1])
            final_filename = '{}.{}'.format(name, output)
            response['Content-Disposition'] = 'attachment; filename="{}"'.format(final_filename)
            
        return response
コード例 #6
0
ファイル: datastreams.py プロジェクト: mxabierto/datal
    def build(self, table_id, dataset_revision_id, app):

        data = {'pId': dataset_revision_id, 'pLimit': 50}
        command = AbstractCommandFactory(app).create("load", "dt", [data])
        result = command.run()
        if not result:
            # TODO: correct handling
            raise Exception('Wrong engine answer')

        soup = BeautifulSoup(result[0])
        table = soup.find(attrs={'tableid': 'table%d' % table_id or 'table0'})
        try:
            if not table:
                raise DatasetTableNotFoundException(table_id) 
            number_of_columns = len(table.findAll('tr')[0].findAll())
        except:
            logger.error("DataSourceBuilder ERROR --> %s" % result[0])
            raise

        impl_details_xml = '<dataSource><DataStructure><Field id="%s"><type></type><format><languaje></languaje><country></country><style></style></format><Table>' % (table_id or 'table0')
        for i in range(number_of_columns):
            impl_details_xml = impl_details_xml + '<Field id="column%d"><alias></alias><type></type><format><languaje></languaje><country></country><style></style></format></Field>' % i
        impl_details_xml = impl_details_xml + '</Table></Field></DataStructure></dataSource>'
        return impl_details_xml
コード例 #7
0
    def engine_call(self,
                    request,
                    engine_method,
                    format=None,
                    is_detail=True,
                    form_class=RequestForm,
                    serialize=True,
                    download=True):
        mutable_get = request.GET.copy()
        mutable_get.update(request.POST.copy())
        mutable_get['output'] = 'json'
        if format is not None:
            format = 'prettyjson' if format == 'pjson' else format
            format = 'json_array' if format == 'ajson' else format
            mutable_get['output'] = format

        resource = {}
        if is_detail:
            resource = self.get_object()
            mutable_get['revision_id'] = resource[self.dao_pk]

        items = dict(mutable_get.items())

        formset = formset_factory(form_class, formset=RequestFormSet)
        form = formset(items)
        if not form.is_valid():
            logger.info("form errors: %s" % form.errors)
            # TODO: correct handling
            raise Exception("Wrong arguments")

        command = AbstractCommandFactory(self.app).create(
            engine_method, self.data_types[0], form.cleaned_data)
        result = command.run()
        if not result:
            # TODO: correct handling
            raise Exception('Wrong engine answer')

        resource['result'] = result[0] if result[0] else {}
        resource['format'] = result[1]

        if serialize:
            serializer = self.get_serializer(resource)
            return Response(serializer.data)

        serializer = EngineSerializer(
            resource, context={'dao_filename': self.dao_filename})

        if download and 'redirect' in serializer.data and serializer.data[
                'redirect']:
            response = HttpResponse(mimetype='application/force-download')
            filename = serializer.data['filename']
            # UGLY HOTFIX
            # ENGINE SEND SOMETHING LIKE
            ### Nivel_Rendimiento_anio_2008.xlsx?AWSAccessKeyId=AKIAI65****H2VI25OA&Expires=1452008148&Signature=u84IIwXrpIoE%3D
            filename2 = filename.split('?AWSAccessKeyId')[0]
            #TODO get the real name (title) or someting nice

            response[
                'Content-Disposition'] = 'attachment; filename="{0}"'.format(
                    filename2)
            redir = urllib2.urlopen(serializer.data['result']['fUri'])
            status = redir.getcode()
            resp = redir.read()
            url = redir.geturl()
            if settings.DEBUG:
                logger.info('REDIR %d %s -- %s -- %s -- %s' %
                            (status, url, redir.info(), filename, filename2))
            response.write(resp)
            return response

        response = Response(serializer.data['result'],
                            content_type=resource['format'])

        #TODO hacer una lista de los formatos que esperan forzar una descarga y los que se mostraran en pantalla
        output = mutable_get['output']
        if download and output not in ['json', 'html']:
            # reemplazar la extension si la tuviera
            filename = serializer.data['filename']
            name = filename if len(filename.split('.')) == 1 else '.'.join(
                filename.split('.')[:-1])
            final_filename = '{}.{}'.format(name, output)
            response[
                'Content-Disposition'] = 'attachment; filename="{}"'.format(
                    final_filename)

        return response
コード例 #8
0
ファイル: views.py プロジェクト: mxabierto/datal
    def engine_call(self, request, engine_method, format=None, is_detail=True, 
                    form_class=RequestForm, serialize=True, download=True):
        mutable_get = request.GET.copy()
        mutable_get.update(request.POST.copy())
        mutable_get['output'] = 'json'
        if format is not None:
            format = 'prettyjson' if format == 'pjson' else format
            format = 'json_array' if format == 'ajson' else format
            mutable_get['output'] = format 
        
        resource = {}
        if is_detail:
            resource = self.get_object()
            mutable_get['revision_id'] = resource[self.dao_pk]
           
        items = dict(mutable_get.items())
        
        formset=formset_factory(form_class, formset=RequestFormSet)
        form = formset(items)
        if not form.is_valid():
            logger.info("form errors: %s" % form.errors)
            # TODO: correct handling
            raise Exception("Wrong arguments")        

        command = AbstractCommandFactory(self.app).create(engine_method, 
            self.data_types[0], form.cleaned_data)
        result = command.run()
        if not result:
            # TODO: correct handling
            raise Exception('Wrong engine answer')

        
        resource['result'] = result[0] if result[0] else {}
        resource['format'] = result[1]

        if serialize:
            serializer = self.get_serializer(resource)
            return Response(serializer.data)

        serializer = EngineSerializer(resource, 
            context={'dao_filename': self.dao_filename})

        if download and 'redirect' in serializer.data and serializer.data['redirect']:
            response = HttpResponse(mimetype='application/force-download')
            filename = serializer.data['filename']
            # UGLY HOTFIX
            # ENGINE SEND SOMETHING LIKE 
            ### Nivel_Rendimiento_anio_2008.xlsx?AWSAccessKeyId=AKIAI65****H2VI25OA&Expires=1452008148&Signature=u84IIwXrpIoE%3D
            filename2 = filename.split('?AWSAccessKeyId')[0]
            #TODO get the real name (title) or someting nice
            
            response['Content-Disposition'] = 'attachment; filename="{0}"'.format(filename2)
            redir = urllib2.urlopen(serializer.data['result']['fUri'])
            status = redir.getcode()
            resp = redir.read()
            url = redir.geturl()
            if settings.DEBUG: logger.info('REDIR %d %s -- %s -- %s -- %s' % (status, url, redir.info(), filename, filename2))
            response.write(resp)
            return response

        response = Response(serializer.data['result'], content_type=resource['format'])
        
        #TODO hacer una lista de los formatos que esperan forzar una descarga y los que se mostraran en pantalla
        output = mutable_get['output']
        if download and output not in ['json', 'html']: 
            # reemplazar la extension si la tuviera
            filename = serializer.data['filename']
            name = filename if len(filename.split('.')) == 1 else '.'.join(filename.split('.')[:-1])
            final_filename = '{}.{}'.format(name, output)
            response['Content-Disposition'] = 'attachment; filename="{}"'.format(final_filename)
            
        return response