Python django.http 模块,FileResponse() 实例源码

我们从Python开源项目中,提取了以下21个代码示例,用于说明如何使用django.http.FileResponse()

项目:pdf-server    作者:nathanielove    | 项目源码 | 文件源码
def read(self, request, pk, from_=None, to=None):
        book = self.get_object()

        if from_ is None and to is None:
            page_from = 1
            page_to = book.pages
        else:
            page_from = int(from_) if from_ else 1
            page_to = int(to) if to else page_from

        if not book.page_numbers_in_range(page_from, page_to):
            raise Http404

        if page_from == 1 and page_to == book.pages:
            stream = open(book.pdf_path, 'rb')
        else:
            data = extractor.pdf.get_pages(book.pdf_path, page_from, page_to)
            stream = BytesIO(data)
        response = FileResponse(stream, content_type='application/pdf')
        response['Content-Disposition'] = 'inline; filename={title} (pg. {from_}-{to}).pdf'.format(
            title=book.title,
            from_=page_from,
            to=page_to)
        return response
项目:MyFirstWebApp    作者:loyal888    | 项目源码 | 文件源码
def Dowmload(request,File_Id):
    if request.method == 'GET':
        fileinfo = FileInfo.objects.filter(File_Id = File_Id)[0];

        def file_iterator(downloadName, chunk_size=512):
            f = open(downloadName, "rb")
            while True:  # ????
                c = f.read(chunk_size)
                if c:
                    yield c;
                else:
                    break;
            f.close()

        filepath = os.path.join(".\upload", fileinfo.File_saveName).replace('\\','/');
        # ??????????????????????????????????????

        response = FileResponse(file_iterator(filepath))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="{0}"'.format(fileinfo.File_realName.encode('utf-8'));
        response['Content-Length'] = os.path.getsize(filepath)  # ???????????
        return response;
项目:ecs    作者:ecs-org    | 项目源码 | 文件源码
def download_once(request, ref_key=None):
    cache_key = 'document-ref-{}'.format(ref_key)
    doc_id = cache.get(cache_key)

    if not doc_id:
        raise Http404()

    cache.delete(cache_key)

    doc = get_object_or_404(Document, pk=doc_id)
    response = FileResponse(doc.retrieve(request.user, 'view'),
        content_type=doc.mimetype)

    # Disable browser caching, so the PDF won't end up on the users hard disk.
    response['Cache-Control'] = 'no-cache, no-store, must-revalidate'
    response['Pragma'] = 'no-cache'
    response['Expires'] = '0'
    response['Vary'] = '*'
    return response
项目:django-daiquiri    作者:aipescience    | 项目源码 | 文件源码
def stream(self, request, pk=None, format_key=None):
        try:
            job = self.get_queryset().get(pk=pk)
        except QueryJob.DoesNotExist:
            raise NotFound

        try:
            format_config = get_format_config(format_key)
        except IndexError:
            raise ValidationError({'format': "Not supported."})

        try:
            download_job = DownloadJob.objects.get(job=job, format_key=format_key)
            return sendfile(request, download_job.file_path, attachment=True)
        except DownloadJob.DoesNotExist:
            file_name = '%s.%s' % (job.table_name, format_config['extension'])
            response = FileResponse(job.stream(format_key), content_type=format_config['content_type'])
            response['Content-Disposition'] = "attachment; filename=%s" % file_name
            return response
项目:storagl    作者:zenwalker    | 项目源码 | 文件源码
def download(request, asset_slug):
    force_download = bool(request.GET.get('download', False))
    asset = get_object_or_404(Asset, slug=asset_slug)
    asset.update_last_access()

    if not DEBUG:
        response = HttpResponse()
        response['X-Accel-Redirect'] = asset.file.url
        response['Content-Type'] = ''  # let nginx guess the mimetype
    else:
        response = FileResponse(asset.file,
            content_type=asset.content_type)

    if asset.file_name:
        disposition = 'attachment' if force_download else 'inline'
        response['Content-Disposition'] = '{}; filename="{}"'.format(disposition, asset.file_name)

    return response
项目:cavedbmanager    作者:masneyb    | 项目源码 | 文件源码
def do_show_bulletin_attachment(request, bulletin_id, localfile, remotefile):
    #pylint: disable=unused-argument
    if not cavedb.perms.is_bulletin_allowed(bulletin_id):
        raise Http404

    if not isfile(localfile):
        raise Http404

    mimetype = guess_type(localfile)[0]
    if mimetype is None:
        mimetype = "application/octet-stream"

    try:
        wrapper = FileWrapper(open(localfile, 'rb'))
        response = FileResponse(wrapper, content_type=mimetype)

        if remotefile and (mimetype is None or not mimetype.startswith('image')):
            response['Content-Disposition'] = 'attachment; filename=' + remotefile

        response['Content-Length'] = getsize(localfile)
    except IOError:
        print('Cannot find %s\n' % (localfile), file=sys.stderr)
        raise Http404

    return response
项目:ccdb5-api    作者:cfpb    | 项目源码 | 文件源码
def swagger(request):
    from django.http import FileResponse
    import os

    thisDir = os.path.dirname(os.path.abspath(__file__))

    swagger_yml_path = os.path.join(
        thisDir,
        'swagger.yml',
    )

    swagger_yml = open(swagger_yml_path, 'rb')

    return FileResponse(
        swagger_yml,
        content_type='text/yaml'
    )
项目:BioQueue    作者:liyao001    | 项目源码 | 文件源码
def download(file_path):
    try:
        response = FileResponse(open(file_path, 'rb'))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="{0}"'.format(os.path.basename(file_path))
        response['Content-Length'] = os.path.getsize(file_path)
        return response
    except Exception as e:
        return error(e)
项目:polyglot-server    作者:MontrealCorpusTools    | 项目源码 | 文件源码
def sound_file(request, corpus, utterance_id):
    corpus = Corpus.objects.get(name=corpus)
    with CorpusContext(corpus.config) as c:
        fname = c.utterance_sound_file(utterance_id, 'consonant')

    response = FileResponse(open(fname, "rb"))
        # response['Content-Type'] = 'audio/wav'
    # response['Content-Length'] = os.path.getsize(fname)
    return response
项目:Django-Web-Development-with-Python    作者:PacktPublishing    | 项目源码 | 文件源码
def download_quote_picture(request, quote_id):
    quote = get_object_or_404(InspirationalQuote, pk=quote_id)
    file_name, file_extension = os.path.splitext(quote.picture.file.name)
    file_extension = file_extension[1:]  # remove the dot
    response = FileResponse(quote.picture.file, content_type="image/%s" % file_extension)
    response['Content-Disposition'] = "attachment; filename=%s---%s.%s" % (
        slugify(quote.author)[:100],
        slugify(quote.quote)[:100],
        file_extension
    )
    return response
项目:presentationTool    作者:longfangsong    | 项目源码 | 文件源码
def download(request, presentation_id):
    if DEBUG:
        base_path = './'
    else:
        base_path = '/usr/src/app/'
    user_file_path = base_path + 'user-file/' + str(presentation_id)
    archive_path = base_path + 'user-archive/'
    the_presentation = Presentation.objects.get(id=presentation_id)
    web_page_src = render_impress_content_to_string(request, the_presentation, release=True)
    makedirs(user_file_path, exist_ok=True)
    makedirs(user_file_path + '/static/script', exist_ok=True)
    makedirs(user_file_path + '/static/stylesheet', exist_ok=True)
    makedirs(archive_path, exist_ok=True)
    with open(user_file_path + '/index.html', 'w') as file:
        file.write(web_page_src)
    copy(base_path + '/impressGenerator/static/script/impress.min.js',
         user_file_path + '/static/script/impress.min.js')
    copy(base_path + '/impressGenerator/static/stylesheet/impress_js_style.css',
         user_file_path + '/static/stylesheet/impress_js_style.css')
    make_archive(archive_path + str(the_presentation.id), 'zip',
                 user_file_path)
    response = FileResponse(open(archive_path + str(the_presentation.id) + '.zip', 'rb'))
    response['Content-Type'] = 'application/zip'
    response['Content-Disposition'] = 'attachment; filename=' + str(the_presentation.name) + '.zip'
    rmtree(user_file_path)
    remove(archive_path + str(the_presentation.id) + '.zip')
    return response
项目:ecs    作者:ecs-org    | 项目源码 | 文件源码
def download_zipped_documents(request, meeting_pk=None, submission_pk=None):
    meeting = get_object_or_404(Meeting, pk=meeting_pk)

    if not submission_pk:
        if not meeting.documents_zip:
            raise Http404()

        doc = meeting.documents_zip
        response = FileResponse(doc.retrieve_raw(), content_type=doc.mimetype)
        response['Content-Disposition'] = \
            'attachment; filename="{}.zip"'.format(slugify(meeting.title))
        return response

    submission = get_object_or_404(meeting.submissions(manager='unfiltered'),
        pk=submission_pk)
    sf = submission.current_submission_form

    docs = []
    if sf.pdf_document:
        docs.append(sf.pdf_document)
    docs += sf.documents.filter(doctype__identifier='patientinformation')
    docs += Document.objects.filter(
        content_type=ContentType.objects.get_for_model(Checklist),
        object_id__in=submission.checklists.filter(status='review_ok'),
    )

    zip_buf = io.BytesIO()
    with zipfile.ZipFile(zip_buf, 'w', compression=zipfile.ZIP_DEFLATED) as zf:
        path = [submission.get_filename_slice()]
        for doc in docs:
            zf.writestr('/'.join(path + [doc.get_filename()]),
                doc.retrieve(request.user, 'meeting-zip').read())

    response = HttpResponse(zip_buf.getvalue(), content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename="{}_{}.zip"'.format(
        slugify(meeting.title), submission.get_filename_slice())
    return response
项目:ecs    作者:ecs-org    | 项目源码 | 文件源码
def protocol_pdf(request, meeting_pk=None):
    meeting = get_object_or_404(Meeting, protocol__isnull=False, pk=meeting_pk)

    response = FileResponse(meeting.protocol.retrieve_raw(),
        content_type=meeting.protocol.mimetype)
    response['Content-Disposition'] = \
        'attachment;filename={}'.format(meeting.protocol.original_file_name)
    return response
项目:ecs    作者:ecs-org    | 项目源码 | 文件源码
def xls_export_download(request, shasum=None):
    cache_file = os.path.join(settings.ECS_DOWNLOAD_CACHE_DIR,
        '{}.xls'.format(shasum))
    response = FileResponse(open(cache_file, 'rb'),
        content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment;filename=submission-export.xls'
    return response
项目:ecs    作者:ecs-org    | 项目源码 | 文件源码
def handle_download(request, doc, view=False):
    if view:
        return handle_view(request, doc)

    if (not doc.doctype.is_downloadable and
        not request.user.profile.is_internal):
        raise PermissionDenied()

    response = FileResponse(doc.retrieve(request.user, 'download'),
        content_type=doc.mimetype)
    response['Content-Disposition'] = \
        'attachment;filename={}'.format(doc.get_filename())
    return response
项目:django-express    作者:bluekvirus    | 项目源码 | 文件源码
def file(self, path, *args, **kwargs):
        '''
        path is relevant to project root (django.conf.settings.BASE_DIR)
        '''
        self._res = FileResponse(open(path, 'rb'), *args, **kwargs)
项目:borgcube    作者:enkore    | 项目源码 | 文件源码
def staticfiles(request, file):
    """
    Simple view for serving static files directly from STATICFILES_DIRS.

    Does not allow subdirectories. Does do If-Modified-Since, though.

    Based on `django.views.static.serve`.
    """
    if '/..\\' in file:
        raise Http404
    if posixpath.normpath(file) != file:
        raise Http404

    for static_file_dir in settings.STATICFILES_DIRS:
        fullpath = os.path.abspath(os.path.join(static_file_dir, file))
        if not fullpath.startswith(static_file_dir):
            raise Http404
        try:
            st = os.stat(fullpath)
        except FileNotFoundError:
            continue
        break
    else:
        raise Http404

    if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
                              st.st_mtime, st.st_size):
        return HttpResponseNotModified()
    content_type, encoding = mimetypes.guess_type(fullpath)
    content_type = content_type or 'application/octet-stream'
    response = FileResponse(open(fullpath, 'rb'), content_type=content_type)
    response['Last-Modified'] = http_date(st.st_mtime)
    if stat.S_ISREG(st.st_mode):
        response['Content-Length'] = st.st_size
    if encoding:
        response['Content-Encoding'] = encoding
    return response
项目:infiblog    作者:RajuKoushik    | 项目源码 | 文件源码
def serve(self, static_file, request):
        response = static_file.get_response(request.method, request.META)
        status = int(response.status)
        http_response = FileResponse(response.file or (), status=status)
        # Remove default content-type
        del http_response['content-type']
        for key, value in response.headers:
            http_response[key] = value
        return http_response
项目:django-private-storage    作者:edoburu    | 项目源码 | 文件源码
def serve(private_file):
        # Support If-Last-Modified
        mtime = private_file.modified_time.timestamp()
        size = private_file.size
        if not was_modified_since(private_file.request.META.get('HTTP_IF_MODIFIED_SINCE'), mtime, size):
            return HttpResponseNotModified()

        # As of Django 1.8, FileResponse triggers 'wsgi.file_wrapper' in Django's WSGIHandler.
        # This uses efficient file streaming, such as sendfile() in uWSGI.
        # When the WSGI container doesn't provide 'wsgi.file_wrapper', it submits the file in 4KB chunks.
        response = FileResponse(private_file.open())
        response['Content-Type'] = private_file.content_type
        response['Content-Length'] = size
        response["Last-Modified"] = http_date(mtime)
        return response
项目:djangomini    作者:djangomini    | 项目源码 | 文件源码
def file(self, filename):
        """
        Send file to user.

        Used to send any file: image, document (PDF, DOC), etc.

        Args:
        - filename: Path to file that we need to send
        """
        return FileResponse(open(filename, 'rb'))
项目:omb-eregs    作者:18F    | 项目源码 | 文件源码
def raw_pdf(request, pdf):
    return FileResponse(as_path(pdf).open('rb'),
                        content_type='application/pdf')