Python django.http.StreamingHttpResponse() Examples
The following are 30
code examples of django.http.StreamingHttpResponse().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.http
, or try the search function
.
Example #1
Source File: views.py From OMS with Apache License 2.0 | 8 votes |
def salt_file_download(request, file_name): import sys reload(sys) sys.setdefaultencoding('utf-8') #解决中文字符默认使用ascii编码问题,不用管得示not find,reload后自然就有了 def file_iterator(file, chunk_size=512): with open(file) as f: while True: c = f.read(chunk_size) if c: yield c else: break f.close() response = StreamingHttpResponse(file_iterator(file_name)) #为了可以下载任意类型文件 response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename="{0}"'.format(file_name) return response
Example #2
Source File: files.py From janeway with GNU Affero General Public License v3.0 | 6 votes |
def serve_press_cover(request, file_to_serve): """Serve a file to the user using a StreamingHttpResponse. :param request: the active request :param file_to_serve: the file to serve :return: a StreamingHttpResponse object with the requested file or an HttpResponseRedirect if there is an IO or permission error """ file_path = os.path.join(settings.BASE_DIR, 'files', 'press', str(file_to_serve.uuid_filename)) try: response = serve_file_to_browser(file_path, file_to_serve) return response except IOError: messages.add_message(request, messages.ERROR, 'File not found. {0}'.format(file_path)) return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Example #3
Source File: views.py From coursys with GNU General Public License v3.0 | 6 votes |
def submitted_file(request: HttpRequest, course_slug: str, activity_slug: str, userid: str, answer_id: str, secret: str) -> StreamingHttpResponse: offering = get_object_or_404(CourseOffering, slug=course_slug) activity = get_object_or_404(Activity, slug=activity_slug, offering=offering, group=False) member = get_object_or_404(Member, ~Q(role='DROP'), find_member(userid), offering__slug=course_slug) answer = get_object_or_404(QuestionAnswer, question__quiz__activity=activity, student=member, id=answer_id) real_secret = answer.answer['data'].get('secret', '?') if real_secret != '?' and secret == real_secret: return _return_submitted_file(answer.answer['data'], answer.file.open('rb')) else: # It's not the current submission, but an instructor looking at history might be trying to find an old one... submissions = QuizSubmission.objects.filter(quiz__activity=activity, student=member) for qs in submissions: for answer_config in qs.config['answers']: version_id, answer_id, a = answer_config if not isinstance(a['data'], dict): continue real_secret = a['data'].get('secret', '?') if answer.question_version_id == version_id and answer.id == answer_id and real_secret != '?' and secret == real_secret: # aha! Temporarily replace answer.file with the old version (without saving) so we can return it answer.file = a['filepath'] return _return_submitted_file(a['data'], answer.file.open('rb')) raise Http404()
Example #4
Source File: views.py From coursys with GNU General Public License v3.0 | 6 votes |
def download_attachment(request, userid, event_slug, attach_slug): person, member_units = _get_faculty_or_404(request.units, userid) event = _get_event_or_404(units=request.units, slug=event_slug, person=person) viewer = get_object_or_404(Person, userid=request.user.username) attachment = get_object_or_404(event.attachments.all(), slug=attach_slug) handler = event.get_handler() if not handler.can_view(viewer): raise PermissionDenied("Not allowed to download this attachment") filename = attachment.contents.name.rsplit('/')[-1] resp = StreamingHttpResponse(attachment.contents.chunks(), content_type=attachment.mediatype) resp['Content-Disposition'] = 'attachment; filename="' + filename + '"' resp['Content-Length'] = attachment.contents.size return resp
Example #5
Source File: views.py From coursys with GNU General Public License v3.0 | 6 votes |
def view_attachment(request, userid, event_slug, attach_slug): person, member_units = _get_faculty_or_404(request.units, userid) event = _get_event_or_404(units=request.units, slug=event_slug, person=person) viewer = get_object_or_404(Person, userid=request.user.username) attachment = get_object_or_404(event.attachments.all(), slug=attach_slug) handler = event.get_handler() if not handler.can_view(viewer): raise PermissionDenied("Not allowed to view this attachment") filename = attachment.contents.name.rsplit('/')[-1] resp = StreamingHttpResponse(attachment.contents.chunks(), content_type=attachment.mediatype) resp['Content-Disposition'] = 'inline; filename="' + filename + '"' resp['Content-Length'] = attachment.contents.size return resp
Example #6
Source File: igv_api.py From seqr with GNU Affero General Public License v3.0 | 6 votes |
def _stream_file(request, path): # based on https://gist.github.com/dcwatson/cb5d8157a8fa5a4a046e content_type = 'application/octet-stream' range_header = request.META.get('HTTP_RANGE', None) if range_header: range_match = re.compile(r'bytes\s*=\s*(\d+)\s*-\s*(\d*)', re.I).match(range_header) first_byte, last_byte = range_match.groups() first_byte = int(first_byte) if first_byte else 0 last_byte = int(last_byte) length = last_byte - first_byte + 1 resp = StreamingHttpResponse( file_iter(path, byte_range=(first_byte, last_byte)), status=206, content_type=content_type) resp['Content-Length'] = str(length) resp['Content-Range'] = 'bytes %s-%s' % (first_byte, last_byte) else: resp = StreamingHttpResponse(file_iter(path), content_type=content_type) resp['Accept-Ranges'] = 'bytes' return resp
Example #7
Source File: export_pages.py From texta with GNU General Public License v3.0 | 6 votes |
def export_pages(request): es_params = request.session.get('export_args') if es_params is not None: if es_params['num_examples'] == '*': response = StreamingHttpResponse(get_all_rows(es_params, request), content_type='text/csv') else: response = StreamingHttpResponse(get_rows(es_params, request), content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="%s"' % (es_params['filename']) return response logger = LogManager(__name__, 'SEARCH CORPUS') logger.set_context('user_name', request.user.username) logger.error('export pages failed, parameters empty') return HttpResponse()
Example #8
Source File: views.py From texta with GNU General Public License v3.0 | 6 votes |
def export_matched_data(request): search_id = request.GET['search_id'] inclusive_metaquery = json.loads(request.GET['inclusive_grammar']) ds = Datasets().activate_dataset(request.session) component_query = ElasticGrammarQuery(inclusive_metaquery, None).generate() es_m = ds.build_manager(ES_Manager) if search_id == '-1': # Full search es_m.combined_query = component_query else: saved_query = json.loads(Search.objects.get(pk=search_id).query) es_m.load_combined_query(saved_query) es_m.merge_combined_query_with_query_dict(component_query) inclusive_instructions = generate_instructions(inclusive_metaquery) response = StreamingHttpResponse(get_all_matched_rows(es_m.combined_query['main'], request, inclusive_instructions), content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="%s"' % ('extracted.csv') return response
Example #9
Source File: csv.py From sal with Apache License 2.0 | 6 votes |
def get_csv_response(queryset: QuerySet, fields: dict, title: str) -> StreamingHttpResponse: writer = csv.writer(PassthroughIO()) # Nest field names into an iterable of 1 so it can be chained. # Add in our two foreign key traversals by name. headers = [fields.keys()] data = (row_helper(item, fields) for item in queryset) # Chain the headers and the data into a single iterator. generator = (writer.writerow(row) for row in itertools.chain(headers, data)) # Streaming responses require a generator; which is good, as it can # process machines one by one rather than shoving the entire output # into memory. response = StreamingHttpResponse(generator, content_type="text/csv") # If DEBUG_CSV is enabled, just print output rather than download. if not server.utils.get_django_setting('DEBUG_CSV', False): response['Content-Disposition'] = 'attachment; filename="%s.csv"' % title return response
Example #10
Source File: views.py From mooder with GNU Lesser General Public License v3.0 | 6 votes |
def get(self, request, *args, **kwargs): post = get_object_or_404(self.get_queryset(), pk=self.kwargs['pk']) if request.user.is_superuser or request.user.has_perm('archives.change_post') or post.author_id == request.user.id: pass elif post.visible == 'private' or post.visible == 'sell' and not post.buyers.filter(id=request.user.id).exists(): raise Http404 chunk_size = 8192 response = StreamingHttpResponse(FileWrapper(open(post.attachment.path, 'rb'), chunk_size), content_type='application/octet-stream') response['Content-Length'] = post.attachment.size filename = post.attachment_filename if post.attachment_filename else 'attachment' response["Content-Disposition"] = \ "attachment; " \ "filenane={ascii_filename};" \ "filename*=UTF-8''{utf_filename}".format( ascii_filename=quote(filename), utf_filename=quote(filename) ) return response
Example #11
Source File: views.py From django-seeker with BSD 2-Clause "Simplified" License | 6 votes |
def export(self): """ A helper method called when ``_export`` is present in ``request.GET``. Returns a ``StreamingHttpResponse`` that yields CSV data for all matching results. """ keywords = self.get_keywords() facets = self.get_facet_data() search = self.get_search(keywords, facets, aggregate=False) columns = self.get_columns() def csv_escape(value): if isinstance(value, (list, tuple)): value = '; '.join(force_text(v) for v in value) return '"%s"' % force_text(value).replace('"', '""') def csv_generator(): yield ','.join('"%s"' % c.label for c in columns if c.visible and c.export) + '\n' for result in search.scan(): yield ','.join(csv_escape(c.export_value(result)) for c in columns if c.visible and c.export) + '\n' export_timestamp = ('_' + timezone.now().strftime('%m-%d-%Y_%H-%M-%S')) if self.export_timestamp else '' export_name = '%s%s.csv' % (self.export_name, export_timestamp) resp = StreamingHttpResponse(csv_generator(), content_type='text/csv; charset=utf-8') resp['Content-Disposition'] = 'attachment; filename=%s' % export_name return resp
Example #12
Source File: views.py From sfm-ui with MIT License | 6 votes |
def export_file(request, pk, file_name): """ Allows authorized user to export a file. Adapted from https://github.com/ASKBOT/django-directory """ export = get_object_or_404(Export, pk=pk) if (request.user == export.user) or request.user.is_superuser: filepath = os.path.join(export.path, file_name) log.debug("Exporting %s", filepath) if os.path.exists(filepath): response = StreamingHttpResponse() response['Content-Disposition'] = 'attachment; filename=%s' % file_name response['Content-Type'] = 'application/octet-stream' file_obj = open(filepath, 'rb') response.streaming_content = _read_file_chunkwise(file_obj) return response else: raise Http404 else: raise PermissionDenied
Example #13
Source File: views.py From tom_base with GNU General Public License v3.0 | 6 votes |
def render_to_response(self, context, **response_kwargs): """ Returns a response containing the exported CSV of selected targets. :param context: Context object for this view :type context: dict :returns: response class with CSV :rtype: StreamingHttpResponse """ qs = context['filter'].qs.values() file_buffer = export_targets(qs) file_buffer.seek(0) # goto the beginning of the buffer response = StreamingHttpResponse(file_buffer, content_type="text/csv") filename = "targets-{}.csv".format(slugify(datetime.utcnow())) response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename) return response
Example #14
Source File: views.py From BioQueue with Apache License 2.0 | 6 votes |
def export_protocol(request): if request.method == 'GET': if 'id' in request.GET: pname, protocol_text = build_plain_protocol(request, request.GET['id']) if protocol_text == 1: return error('Cannot find the protocol.') elif protocol_text == 2: return error('You are not owner of the protocol.') else: from django.http import StreamingHttpResponse response = StreamingHttpResponse(protocol_text) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename="{0}"'.format(str(pname + '.txt')) return response else: return error('Unknown parameter.') else: return error('Method error.')
Example #15
Source File: helpers.py From InvenTree with MIT License | 6 votes |
def DownloadFile(data, filename, content_type='application/text'): """ Create a dynamic file for the user to download. Args: data: Raw file data (string or bytes) filename: Filename for the file download content_type: Content type for the download Return: A StreamingHttpResponse object wrapping the supplied data """ filename = WrapWithQuotes(filename) if type(data) == str: wrapper = FileWrapper(io.StringIO(data)) else: wrapper = FileWrapper(io.BytesIO(data)) response = StreamingHttpResponse(wrapper, content_type=content_type) response['Content-Length'] = len(data) response['Content-Disposition'] = 'attachment; filename={f}'.format(f=filename) return response
Example #16
Source File: files.py From janeway with GNU Affero General Public License v3.0 | 6 votes |
def serve_file(request, file_to_serve, article, public=False, hide_name=False): """Serve a file to the user using a StreamingHttpResponse. :param request: the active request :param file_to_serve: the file object to retrieve and serve :param article: the associated article :param public: boolean :param hide_name: boolean :return: a StreamingHttpResponse object with the requested file or an HttpResponseRedirect if there is an IO or permission error """ path_parts = ('articles', article.pk) return serve_any_file( request, file_to_serve, public, hide_name=hide_name, path_parts=path_parts )
Example #17
Source File: base.py From davvy with MIT License | 6 votes |
def get(self, request, user, resource_name): resource = self.get_resource(request, user, resource_name) if resource.collection: return HttpResponseForbidden() response = StreamingHttpResponse( self.storage.retrieve( self, request, resource ), content_type=resource.content_type ) response['Content-Length'] = resource.size response[ 'Content-Disposition'] = "attachment; filename=%s" % resource.name return response
Example #18
Source File: files.py From janeway with GNU Affero General Public License v3.0 | 6 votes |
def serve_journal_cover(request, file_to_serve): """Serve a file to the user using a StreamingHttpResponse. :param request: the active request :param file_to_serve: the file object to retrieve and serve :return: a StreamingHttpResponse object with the requested file or an HttpResponseRedirect if there is an IO or permission error """ file_path = os.path.join(settings.BASE_DIR, 'files', 'journals', str(request.journal.id), str(file_to_serve.uuid_filename)) try: response = serve_file_to_browser(file_path, file_to_serve) return response except IOError: messages.add_message(request, messages.ERROR, 'File not found. {0}'.format(file_path)) return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Example #19
Source File: views.py From coldfront with GNU General Public License v3.0 | 5 votes |
def get(self, request): header = [ 'Grant Title', 'Project PI', 'Faculty Role', 'Grant PI', 'Total Amount Awarded', 'Funding Agency', 'Grant Number', 'Start Date', 'End Date', 'Percent Credit', 'Direct Funding', ] rows = [] grants = Grant.objects.prefetch_related('project', 'project__pi').all().order_by('-total_amount_awarded') for grant in grants: row = [ grant.title, ' '.join((grant.project.pi.first_name, grant.project.pi.last_name)), grant.role, grant.grant_pi_full_name, grant.total_amount_awarded, grant.funding_agency, grant.grant_number, grant.grant_start, grant.grant_end, grant.percent_credit, grant.direct_funding, ] rows.append(row) rows.insert(0, header) pseudo_buffer = Echo() writer = csv.writer(pseudo_buffer) response = StreamingHttpResponse((writer.writerow(row) for row in rows), content_type="text/csv") response['Content-Disposition'] = 'attachment; filename="grants.csv"' return response
Example #20
Source File: views.py From hummer with Apache License 2.0 | 5 votes |
def download(self, request, *args, **kwargs): """ Download the volume data. """ volume = self.get_object() # Check whether project is corresponding to the user user = request.user if not check_member_in_project(volume.project, user): raise PermissionDenied(detail="User {} is not in project {}." .format(user.username, volume.project.name)) logger.info("User {} download the data of volume {}-{}.".format( request.user.username, volume.project.name, volume.name)) # Copy file to local first volume_dir = get_volume_direction_on_nfs(volume) filename = get_upload_volume_filename(volume, request.user) client = NFSLocalClient() client.tar_and_copy_to_local(volume_dir, filename) response = StreamingHttpResponse(big_file_iterator(filename)) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename="{}"'.format( os.path.basename(filename)) return response
Example #21
Source File: views.py From webterminal with GNU General Public License v3.0 | 5 votes |
def _do_read(request, cache_key): pending_read_request.set() def content(): with sockets_lock: client = sockets[cache_key] with read_lock: pending_read_request.clear() while True: instruction = client.receive() if instruction: yield instruction else: break if pending_read_request.is_set(): logger.info('Letting another request take over.') break # End-of-instruction marker yield '0.;' response = StreamingHttpResponse(content(), content_type='application/octet-stream') response['Cache-Control'] = 'no-cache' return response
Example #22
Source File: sendfile_streaming_backend.py From wagtail with BSD 3-Clause "New" or "Revised" License | 5 votes |
def sendfile(request, filename, **kwargs): # Respect the If-Modified-Since header. statobj = os.stat(filename) if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'), statobj[stat.ST_MTIME], statobj[stat.ST_SIZE]): return HttpResponseNotModified() response = StreamingHttpResponse(FileWrapper(open(filename, 'rb'))) response["Last-Modified"] = http_date(statobj[stat.ST_MTIME]) return response
Example #23
Source File: reports.py From wagtail with BSD 3-Clause "New" or "Revised" License | 5 votes |
def write_csv_response(self, queryset): stream = self.stream_csv(queryset) response = StreamingHttpResponse(stream, content_type="text/csv") response["Content-Disposition"] = 'attachment; filename="{}.csv"'.format( self.get_filename() ) return response
Example #24
Source File: serve.py From wagtail with BSD 3-Clause "New" or "Revised" License | 5 votes |
def serve(self, rendition): # Open and serve the file rendition.file.open('rb') image_format = imghdr.what(rendition.file) return StreamingHttpResponse(FileWrapper(rendition.file), content_type='image/' + image_format)
Example #25
Source File: admin.py From OnlineJudge with MIT License | 5 votes |
def get(self, request): problem_id = request.GET.get("problem_id") if not problem_id: return self.error("Parameter error, problem_id is required") try: problem = Problem.objects.get(id=problem_id) except Problem.DoesNotExist: return self.error("Problem does not exists") if problem.contest: ensure_created_by(problem.contest, request.user) else: ensure_created_by(problem, request.user) test_case_dir = os.path.join(settings.TEST_CASE_DIR, problem.test_case_id) if not os.path.isdir(test_case_dir): return self.error("Test case does not exists") name_list = self.filter_name_list(os.listdir(test_case_dir), problem.spj) name_list.append("info") file_name = os.path.join(test_case_dir, problem.test_case_id + ".zip") with zipfile.ZipFile(file_name, "w") as file: for test_case in name_list: file.write(f"{test_case_dir}/{test_case}", test_case) response = StreamingHttpResponse(FileWrapper(open(file_name, "rb")), content_type="application/octet-stream") response["Content-Disposition"] = f"attachment; filename=problem_{problem.id}_test_cases.zip" response["Content-Length"] = os.path.getsize(file_name) return response
Example #26
Source File: views.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def streaming(request): return StreamingHttpResponse([b"streaming", b" ", b"content"])
Example #27
Source File: views.py From django-freeze with MIT License | 5 votes |
def download_zip(path = settings.FREEZE_ZIP_PATH, name = settings.FREEZE_ZIP_NAME): #http://stackoverflow.com/questions/8600843/serving-large-files-with-high-loads-in-django response = StreamingHttpResponse(FileWrapper(open(path), 8192), content_type = 'application/zip') response['Content-Length'] = os.path.getsize(path) response['Content-Disposition'] = 'attachment; filename=%s' % (name, ) return response
Example #28
Source File: views.py From docker-box with MIT License | 5 votes |
def host_stats(request): return StreamingHttpResponse(stream_host_stats())
Example #29
Source File: catalogs.py From course-discovery with GNU Affero General Public License v3.0 | 5 votes |
def csv(self, request, id=None): # pylint: disable=redefined-builtin """ Retrieve a CSV containing the course runs contained within this catalog. Only active course runs are returned. A course run is considered active if it is currently open for enrollment, or will be open for enrollment in the future. --- serializer: serializers.FlattenedCourseRunWithCourseSerializer """ catalog = self.get_object() courses = catalog.courses() course_runs = CourseRun.objects.filter(course__in=courses).active().marketable() # We use select_related and prefetch_related to decrease our database query count course_runs = course_runs.select_related(*serializers.SELECT_RELATED_FIELDS['course_run']) prefetch_fields = ['course__' + field for field in serializers.PREFETCH_FIELDS['course']] prefetch_fields += serializers.PREFETCH_FIELDS['course_run'] course_runs = course_runs.prefetch_related(*prefetch_fields) serializer = serializers.FlattenedCourseRunWithCourseSerializer( course_runs, many=True, context={'request': request} ) data = CourseRunCSVRenderer().render(serializer.data) response = StreamingHttpResponse(data, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="catalog_{id}_{date}.csv"'.format( id=id, date=datetime.datetime.utcnow().strftime('%Y-%m-%d-%H-%M') ) return response
Example #30
Source File: views.py From docker-box with MIT License | 5 votes |
def container_stats(request, container_id): container = Container.objects.get_container(container_id, request.user) if container: return StreamingHttpResponse(stream_response_generator(container)) return render(request, 'no_access.html')