Example #1
0
    def download(properties, iid):
        """Built in download method
        create pdf_context and return the results to celery backend.
        :param properties: properties of the pdf template to be generated
        :param iid: id of the item
        :return: return the iid of the task
        """
        User = get_user_model()
        user = properties['user']
        if user and user != str(AnonymousUser()):
            user = User.objects.get(email=user)
        else:
            user = AnonymousUser()
        item = MDR._concept.objects.get_subclass(pk=iid)
        item = get_if_user_can_view(item.__class__, user, iid)
        template = get_download_template_path_for_item(
            item, PDFDownloader.download_type)

        sub_items = [(obj_type, qs.visible(user).order_by('name').distinct())
                     for obj_type, qs in item.get_download_items()]

        PDFDownloader.cache_file(PDFDownloader.get_cache_key(user, iid),
                                 (render_to_pdf(
                                     template, {
                                         'title': properties['title'],
                                         'item': item,
                                         'subitems': sub_items,
                                         'tableOfContents': len(sub_items) > 0,
                                         'view': properties['view'].lower(),
                                         'pagesize': properties['page_size'],
                                     }), 'application/pdf', {}))

        return iid
    def download(properties, iid):
        """Built in download method
        create pdf_context and return the results to celery backend.
        :param properties: properties of the pdf template to be generated
        :param iid: id of the item
        :return: return the iid of the task
        """
        User = get_user_model()
        user = properties['user']
        if user and user != str(AnonymousUser()):
            user = User.objects.get(email=user)
        else:
            user = AnonymousUser()
        item = MDR._concept.objects.get_subclass(pk=iid)
        item = get_if_user_can_view(item.__class__, user, iid)
        template = get_download_template_path_for_item(item, PDFDownloader.download_type)

        sub_items = [
            (obj_type, qs.visible(user).order_by('name').distinct())
            for obj_type, qs in item.get_download_items()
        ]

        PDFDownloader.cache_file(PDFDownloader.get_cache_key(user, iid), (render_to_pdf(template, {
            'title': properties['title'],
            'item': item,
            'subitems': sub_items,
            'tableOfContents': len(sub_items) > 0,
            'view': properties['view'].lower(),
            'pagesize': properties['page_size'],
        }), 'application/pdf', {}))

        return iid
    def download(properties, iid):
        """Built in download method"""
        User = get_user_model()
        user = properties.get('user')
        if user and user != str(AnonymousUser()):
            user = User.objects.get(email=user)
        else:
            user = AnonymousUser()

        item = MDR._concept.objects.get_subclass(pk=iid)
        item = get_if_user_can_view(item.__class__, user, iid)

        mem_file = io.StringIO()
        writer = csv.writer(mem_file)
        writer.writerow(['value', 'meaning', 'start date', 'end date', 'role'])
        for v in item.permissibleValues.all():
            writer.writerow(
                [v.value, v.meaning, v.start_date, v.end_date, "permissible"]
            )
        for v in item.supplementaryValues.all():
            writer.writerow(
                [v.value, v.meaning, v.start_date, v.end_date, "supplementary"]
            )
        CSVDownloader.cache_file(CSVDownloader.get_cache_key(user, iid),
                                 (mem_file.getvalue(),
                                  'txt/csv',
                                  {'Content-Disposition': 'attachment; filename="{}.csv"'.format(item.name)}
                                  )
                                 )
        return iid
    def download(properties, iid):
        """Built in download method"""
        User = get_user_model()
        user = properties.get('user')
        if user and user != str(AnonymousUser()):
            user = User.objects.get(email=user)
        else:
            user = AnonymousUser()

        item = MDR._concept.objects.get_subclass(pk=iid)
        item = get_if_user_can_view(item.__class__, user, iid)

        mem_file = io.StringIO()
        writer = csv.writer(mem_file)
        writer.writerow(['value', 'meaning', 'start date', 'end date', 'role'])
        for v in item.permissibleValues.all():
            writer.writerow(
                [v.value, v.meaning, v.start_date, v.end_date, "permissible"])
        for v in item.supplementaryValues.all():
            writer.writerow([
                v.value, v.meaning, v.start_date, v.end_date, "supplementary"
            ])
        CSVDownloader.cache_file(CSVDownloader.get_cache_key(
            user, iid), (mem_file.getvalue(), 'txt/csv', {
                'Content-Disposition':
                'attachment; filename="{}.csv"'.format(item.name)
            }))
        return iid
Example #5
0
def bulk_download(request, download_type, items=None):
    """
    By default, ``aristotle_mdr.views.bulk_download`` is called whenever a URL matches
    the pattern defined in ``aristotle_mdr.urls_aristotle``::

        bulk_download/(?P<download_type>[a-zA-Z0-9\-\.]+)/?

    This is passed into ``bulk_download`` which takes the items GET arguments from the
    request and determines if a user has permission to view the requested items.
    For any items the user can download they are exported in the desired format as
    described in ``aristotle_mdr.views.download``.

    If the requested module is able to be imported, ``downloader.py`` from the given module
    is imported, this file **MUST** have a ``bulk_download`` function defined which returns
    a Django ``HttpResponse`` object of some form.
    """
    items = []

    for iid in request.GET.getlist('items'):
        item = MDR._concept.objects.get_subclass(pk=iid)
        item = get_if_user_can_view(item.__class__, request.user, iid)
        items.append(item)

    downloadOpts = getattr(settings, 'ARISTOTLE_DOWNLOADS', "")
    module_name = ""
    for d in downloadOpts:
        dt = d[0]
        if dt == download_type:
            module_name = d[3]
    if not re.search('^[a-zA-Z0-9\-\.]+$', download_type):  # pragma: no cover
        # Invalid download_type
        raise registry_exceptions.BadDownloadTypeAbbreviation(
            "Download type can only be composed of letters, numbers, hyphens or periods."
        )
    if module_name:
        downloader = get_download_module(module_name)
        try:
            return downloader.bulk_download(request, download_type, items)
        except TemplateDoesNotExist:
            debug = getattr(settings, 'DEBUG')
            if debug:
                raise
            raise Http404

    raise Http404
    def download(properties, iid):
        User = get_user_model()
        user = properties['user']
        if user and user != str(AnonymousUser):
            user = User.objects.get(email=user)
        else:
            user = AnonymousUser()

        item = MDR._concept.objects.get_subclass(pk=iid)
        item = get_if_user_can_view(item.__class__, user, iid)

        template = get_download_template_path_for_item(item, TestTextDownloader.download_type)

        template = select_template([template])
        context = {'item': item}
        txt = template.render(context)
        TestTextDownloader.cache_file(TestTextDownloader.get_cache_key(user, iid), (txt, 'text/plain', {}))
        return item
Example #7
0
def bulk_download(request, download_type, items=None):
    """
    By default, ``aristotle_mdr.views.bulk_download`` is called whenever a URL matches
    the pattern defined in ``aristotle_mdr.urls_aristotle``::

        bulk_download/(?P<download_type>[a-zA-Z0-9\-\.]+)/?

    This is passed into ``bulk_download`` which takes the items GET arguments from the
    request and determines if a user has permission to view the requested items.
    For any items the user can download they are exported in the desired format as
    described in ``aristotle_mdr.views.download``.

    If the requested module is able to be imported, ``downloader.py`` from the given module
    is imported, this file **MUST** have a ``bulk_download`` function defined which returns
    a Django ``HttpResponse`` object of some form.
    """
    items=[]

    for iid in request.GET.getlist('items'):
        item = MDR._concept.objects.get_subclass(pk=iid)
        item = get_if_user_can_view(item.__class__, request.user, iid)
        items.append(item)

    downloadOpts = getattr(settings, 'ARISTOTLE_DOWNLOADS', "")
    module_name = ""
    for d in downloadOpts:
        dt = d[0]
        if dt == download_type:
            module_name = d[3]
    if not re.search('^[a-zA-Z0-9\-\.]+$', download_type):  # pragma: no cover
        # Invalid download_type
        raise registry_exceptions.BadDownloadTypeAbbreviation("Download type can only be composed of letters, numbers, hyphens or periods.")
    if module_name:
        downloader = get_download_module(module_name)
        try:
            return downloader.bulk_download(request, download_type, items)
        except TemplateDoesNotExist:
            debug = getattr(settings, 'DEBUG')
            if debug:
                raise
            raise Http404

    raise Http404
    def download(properties, iid):
        User = get_user_model()
        user = properties['user']
        if user and user != str(AnonymousUser):
            user = User.objects.get(email=user)
        else:
            user = AnonymousUser()

        item = MDR._concept.objects.get_subclass(pk=iid)
        item = get_if_user_can_view(item.__class__, user, iid)

        template = get_download_template_path_for_item(
            item, TestTextDownloader.download_type)

        template = select_template([template])
        context = {'item': item}
        txt = template.render(context)
        TestTextDownloader.cache_file(
            TestTextDownloader.get_cache_key(user, iid),
            (txt, 'text/plain', {}))
        return item
Example #9
0
def download(request, download_type, iid=None):
    """
    By default, ``aristotle_mdr.views.download`` is called whenever a URL matches
    the pattern defined in ``aristotle_mdr.urls_aristotle``::

        download/(?P<download_type>[a-zA-Z0-9\-\.]+)/(?P<iid>\d+)/?

    This is passed into ``download`` which resolves the item id (``iid``), and
    determines if a user has permission to view the requested item with that id. If
    a user is allowed to download this file, ``download`` iterates through each
    download type defined in ``ARISTOTLE_DOWNLOADS``.

    A download option tuple takes the following form form::

        ('file_type','display_name','font_awesome_icon_name','module_name'),

    With ``file_type`` allowing only ASCII alphanumeric and underscores,
    ``display_name`` can be any valid python string,
    ``font_awesome_icon_name`` can be any Font Awesome icon and
    ``module_name`` is the name of the python module that provides a downloader
    for this file type.

    For example, included with Aristotle-MDR is a PDF downloader which has the
    download definition tuple::

            ('pdf','PDF','fa-file-pdf-o','aristotle_mdr'),

    Where a ``file_type`` multiple is defined multiple times, **the last matching
    instance in the tuple is used**.

    Next, the module that is defined for a ``file_type`` is dynamically imported using
    ``exec``, and is wrapped in a ``try: except`` block to catch any exceptions. If
    the ``module_name`` does not match the regex ``^[a-zA-Z0-9\_]+$`` ``download``
    raises an exception.

    If the module is able to be imported, ``downloader.py`` from the given module
    is imported, this file **MUST** have a ``download`` function defined which returns
    a Django ``HttpResponse`` object of some form.
    """
    item = MDR._concept.objects.get_subclass(pk=iid)
    item = get_if_user_can_view(item.__class__, request.user, iid)
    if not item:
        if request.user.is_anonymous():
            return redirect(
                reverse('friendly_login') + '?next=%s' % request.path)
        else:
            raise PermissionDenied

    downloadOpts = getattr(settings, 'ARISTOTLE_DOWNLOADS', "")
    module_name = ""
    for d in downloadOpts:
        dt = d[0]
        if dt == download_type:
            module_name = d[3]
    if not re.search('^[a-zA-Z0-9\-\.]+$', download_type):  # pragma: no cover
        # Invalid download_type
        raise registry_exceptions.BadDownloadTypeAbbreviation(
            "Download type can only be composed of letters, numbers, hyphens or periods."
        )
    if module_name:
        downloader = get_download_module(module_name)
        try:
            return downloader.download(request, download_type, item)
        except TemplateDoesNotExist:
            debug = getattr(settings, 'DEBUG')
            if debug:
                raise
            raise Http404

    raise Http404
def download(request, download_type, iid=None):
    r"""
    By default, ``aristotle_mdr.views.download`` is called whenever a URL matches
    the pattern defined in ``aristotle_mdr.urls_aristotle``::

        download/(?P<download_type>[a-zA-Z0-9\-\.]+)/(?P<iid>\d+)/?

    This is passed into ``download`` which resolves the item id (``iid``), and
    determines if a user has permission to view the requested item with that id. If
    a user is allowed to download this file, ``download`` iterates through each
    download type defined in ``ARISTOTLE_SETTINGS.DOWNLOADERS``.

    A download option tuple takes the following form form::

        ('file_type','display_name','font_awesome_icon_name','module_name'),

    With ``file_type`` allowing only ASCII alphanumeric and underscores,
    ``display_name`` can be any valid python string,
    ``font_awesome_icon_name`` can be any Font Awesome icon and
    ``module_name`` is the name of the python module that provides a downloader
    for this file type.

    For example, the Aristotle-PDF with Aristotle-MDR is a PDF downloader which has the
    download definition tuple::

            ('pdf','PDF','fa-file-pdf-o','aristotle_pdr'),

    Where a ``file_type`` multiple is defined multiple times, **the last matching
    instance in the tuple is used**.

    Next, the module that is defined for a ``file_type`` is dynamically imported using
    ``exec``, and is wrapped in a ``try: except`` block to catch any exceptions. If
    the ``module_name`` does not match the regex ``^[a-zA-Z0-9\_]+$`` ``download``
    raises an exception.

    If the module is able to be imported, ``downloader.py`` from the given module
    is imported, this file **MUST** have a ``download`` function defined which returns
    a Django ``HttpResponse`` object of some form.
    """
    item = MDR._concept.objects.get_subclass(pk=iid)
    item = get_if_user_can_view(item.__class__, request.user, iid)
    if not item:
        if request.user.is_anonymous():
            return redirect(reverse('friendly_login') + '?next=%s' % request.path)
        else:
            raise PermissionDenied
    get_params = request.GET.copy()
    get_params.setdefault('items', iid)
    download_opts = fetch_aristotle_downloaders()
    for kls in download_opts:
        if download_type == kls.download_type:
            try:
                # properties requested for the file requested
                kls.item = item
                properties = kls.get_download_config(request, iid)
                if get_params.get('public', False):
                    properties['user'] = False
                res = kls.download.delay(properties, iid)
                get_params.setdefault('title', properties.get('title', 'Auto-Generated Document'))
                response = redirect('{}?{}'.format(
                    reverse('aristotle:preparing_download', args=[download_type]),
                    urlencode(get_params, True)
                ))
                download_key = request.session.get(download_utils.get_download_session_key(get_params, download_type))
                if download_key:
                    async_result(download_key).forget()
                request.session[download_utils.get_download_session_key(get_params, download_type)] = res.id
                return response
            except TemplateDoesNotExist:
                debug = getattr(settings, 'DEBUG')
                if debug:
                    raise
                # Maybe another downloader can serve this up
                continue

    raise Http404
Example #11
0
def download(request, download_type, iid=None):
    """
    By default, ``aristotle_mdr.views.download`` is called whenever a URL matches
    the pattern defined in ``aristotle_mdr.urls_aristotle``::

        download/(?P<download_type>[a-zA-Z0-9\-\.]+)/(?P<iid>\d+)/?

    This is passed into ``download`` which resolves the item id (``iid``), and
    determines if a user has permission to view the requested item with that id. If
    a user is allowed to download this file, ``download`` iterates through each
    download type defined in ``ARISTOTLE_DOWNLOADS``.

    A download option tuple takes the following form form::

        ('file_type','display_name','font_awesome_icon_name','module_name'),

    With ``file_type`` allowing only ASCII alphanumeric and underscores,
    ``display_name`` can be any valid python string,
    ``font_awesome_icon_name`` can be any Font Awesome icon and
    ``module_name`` is the name of the python module that provides a downloader
    for this file type.

    For example, included with Aristotle-MDR is a PDF downloader which has the
    download definition tuple::

            ('pdf','PDF','fa-file-pdf-o','aristotle_mdr'),

    Where a ``file_type`` multiple is defined multiple times, **the last matching
    instance in the tuple is used**.

    Next, the module that is defined for a ``file_type`` is dynamically imported using
    ``exec``, and is wrapped in a ``try: except`` block to catch any exceptions. If
    the ``module_name`` does not match the regex ``^[a-zA-Z0-9\_]+$`` ``download``
    raises an exception.

    If the module is able to be imported, ``downloader.py`` from the given module
    is imported, this file **MUST** have a ``download`` function defined which returns
    a Django ``HttpResponse`` object of some form.
    """
    item = MDR._concept.objects.get_subclass(pk=iid)
    item = get_if_user_can_view(item.__class__, request.user, iid)
    if not item:
        if request.user.is_anonymous():
            return redirect(reverse('friendly_login') + '?next=%s' % request.path)
        else:
            raise PermissionDenied

    downloadOpts = getattr(settings, 'ARISTOTLE_DOWNLOADS', "")
    module_name = ""
    for d in downloadOpts:
        dt = d[0]
        if dt == download_type:
            module_name = d[3]
    if not re.search('^[a-zA-Z0-9\-\.]+$', download_type):  # pragma: no cover
        # Invalid download_type
        raise registry_exceptions.BadDownloadTypeAbbreviation("Download type can only be composed of letters, numbers, hyphens or periods.")
    if module_name:
        downloader = get_download_module(module_name)
        try:
            return downloader.download(request, download_type, item)
        except TemplateDoesNotExist:
            debug = getattr(settings, 'DEBUG')
            if debug:
                raise
            raise Http404

    raise Http404