Source

django-private-media / private_media / views.py

import os
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import get_callable
from django.http import Http404
from django.views.static import serve
from private_media.conf import settings
from private_media.utils import decode_key


def get_file(request, content_type_id, object_pk, field_name, file_name):
    try:
        content_type = ContentType.objects.get_for_id(content_type_id)
        instance = content_type.get_object_for_this_type(**{
            'pk': object_pk,
            field_name: file_name,
        })
    except Exception, e:
        raise Http404(e if settings.DEBUG else 'File not found.')
    file_field = getattr(instance, field_name)
    if not file_field.condition(request, instance):
        raise PermissionDenied
    if settings.PRIVATE_MEDIA_INSECURE:
        response = serve(request, file_name, document_root=settings.MEDIA_ROOT)
    else:
        handler = get_callable(file_field.handler, True)
        if not callable(handler):
            raise Http404("Error importing '%s'." % file_field.handler
                          if settings.DEBUG else 'File not found.')
        response = handler(request, file_field)
    if file_field.disposition is not None:
        response['Content-Disposition'] = '%s; filename="%s"' % (
            file_field.disposition, os.path.basename(file_field.name))
    return response


def get_file_enc(request, enc_key, file_name):
    try:
        key = decode_key(enc_key)
        content_type_id, object_pk, field_name = key.split('/', 2)
    except Exception, e:
        raise Http404(e if settings.DEBUG else 'File not found.')
    return get_file(request, content_type_id, object_pk, field_name, file_name)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.