def render_to_response(self, context, **response_kwargs): invoice = self.object path = invoice.file and invoice.file.path if not path: return HttpResponseNotFound() response = FileResponse(open(path, 'rb'), content_type='application/pdf') short_date = date_format(invoice.created, format='SHORT_DATE_FORMAT', use_l10n=True) filename = '%s-%s-%s.pdf' % (CosinnusPortal.get_current().name, force_text(_('Invoice')), short_date) # To inspect details for the below code, see http://greenbytes.de/tech/tc2231/ user_agent = self.request.META.get('HTTP_USER_AGENT', []) if u'WebKit' in user_agent: # Safari 3.0 and Chrome 2.0 accepts UTF-8 encoded string directly. filename_header = 'filename=%s' % filename elif u'MSIE' in user_agent: filename_header = '' else: # For others like Firefox, we follow RFC2231 (encoding extension in HTTP headers). filename_header = 'filename*=UTF-8\'\'%s' % filename response['Content-Disposition'] = 'attachment; ' + filename_header return response
def batch_dumps(self, request): downloadToken = 'downloadToken' ids = request.query_params.getlist('ids', []) download_token = request.query_params.get(downloadToken) if not ids: return response.Response(status=status.HTTP_200_OK) queryset = self.queryset.filter(id__in=ids) if not queryset: return response.Response(status=status.HTTP_200_OK) dump_path = dump_task_event(queryset) def file_iterator(file_name, chunk_size=512): with open(file_name, 'rb') as f: while True: c = f.read(chunk_size) if c: yield c else: f.close() os.remove(file_name) break res = FileResponse(file_iterator(dump_path)) res['Content-Length'] = os.path.getsize(dump_path) res['Content-Type'] = 'application/octet-stream' res['Content-Disposition'] = 'attachment;filename="%s"' % os.path.basename( dump_path.encode('utf8')) res.set_cookie(downloadToken, download_token) return res
def download_planning(request): plannings_parsed = download.parse_planning_data() file_path = download.generate_json_file(plannings_parsed) return FileResponse( open(file_path, 'rb'), as_attachment=True, )
def get(self, request, *args, **kwargs): id_libro = self.kwargs.get('id_libro') libroEx = imprimir_diario_mayor(id_libro) # create the HttpResponse object ... #print(libroEx.filename['name']) response = FileResponse(open(libroEx, 'rb')) return response
def get(self, request, *args, **kwargs): id_periodo = self.kwargs.get('id_periodo') cierre(id_periodo) libroEx = imprimir_auxiliar_balance_general(id_periodo) # create the HttpResponse object ... response = FileResponse(open(libroEx, 'rb')) return response
def get_file_view(request): id = request.GET.get('id', None) if id is None: return HttpResponseNotFound() # determine whether user has permission to download private file: perm_private = request.user.has_perm( 'seminar.download_private_file') if request.user is not None else False try: s_file = SeminarFile.objects.get(id=id) if not s_file.seminar.public and not perm_private: return HttpResponseNotFound() s_file.download_count += 1 s_file.save() except SeminarFile.DoesNotExist: return HttpResponseNotFound() else: response = FileResponse(open(s_file.path.path), content_type='application/octet-stream') response[ 'Content-Disposition'] = 'attachment;filename="{filename}"'.format( filename=urllib.quote( s_file.filename.encode(sys.getdefaultencoding()))) return response
def download_csv_file(request, filename): locale = get_language_from_request(request) translation.activate(locale) filepath = os.path.join(conf.KOLIBRI_HOME, "temp", filename) # if the file does not exist on disk, return a 404 if filepath is None or not os.path.exists(filepath): raise Http404("Creation of users export file has failed") # generate a file response response = FileResponse(io.open(filepath, "rb")) # set the content-type by guessing from the filename response["Content-Type"] = "text/csv" # set the content-disposition as attachment to force download exported_filename = (slugify( pgettext( "Default name for the exported CSV file of facility user data. Please keep the underscore between words in the translation", "users_{}", ).format(datetime.now().strftime("%Y%m%d_%H%M%S"))).replace("-", "_") + ".csv") response["Content-Disposition"] = "attachment; filename={}".format( str(exported_filename)) # set the content-length to the file size response["Content-Length"] = os.path.getsize(filepath) translation.deactivate() return response
def attachment_file(file, filename): """return a @file fieldfile and @filename as an http attachment""" response = FileResponse(open(file, "rb")) response['Content-Disposition'] = 'attachment; filename="%s"' % filename response['Content-Length'] = os.stat(file).st_size return response
def get(self, request): file = open(f'{settings.MEDIA_ROOT}/excel/Siswa.xlsx', 'rb') response = FileResponse(file, content_type='application/force-download') response[ 'Content-Disposition'] = 'attachment; filename=Tabel Siswa.xlsx' return response
def download_csv_file(request, log_type): csv_export_filenames = { "session": "content_session_logs.csv", "summary": "content_summary_logs.csv", } if log_type in csv_export_filenames.keys(): filepath = os.path.join(conf.KOLIBRI_HOME, "log_export", csv_export_filenames[log_type]) else: filepath = None # if the file does not exist on disk, return a 404 if filepath is None or not os.path.exists(filepath): raise Http404( "There is no csv export file for {} available".format(log_type)) # generate a file response response = FileResponse(open(filepath, "rb")) # set the content-type by guessing from the filename response["Content-Type"] = "text/csv" # set the content-disposition as attachment to force download response["Content-Disposition"] = "attachment; filename={}".format( csv_export_filenames[log_type]) # set the content-length to the file size response["Content-Length"] = os.path.getsize(filepath) return response
def generate_file_response(file_obj, content_type, force_download=False, name=None): charset = get_charset(file_obj.read(128)) file_obj.seek(0) content_type = u'{}; charset={}'.format(content_type, charset) response = FileResponse(file_obj, content_type=content_type) filename = get_filename_from_file_obj(file_obj, name) if filename: try: filename.encode('ascii') file_expr = u'filename="{}"'.format(filename) except (UnicodeEncodeError, UnicodeDecodeError): file_expr = u"filename*=utf-8''{}".format(quote(filename)) response['Content-Disposition'] = u'inline; {}'.format(file_expr) if force_download or content_type is None: if content_type is None: response['Content-Type'] = 'application/octet-stream' if filename: response['Content-Disposition'] = u'attachment; {}'.format(file_expr) # disable caching, required for Firefox to be able to load large files multiple times # see https://bugzilla.mozilla.org/show_bug.cgi?id=1436593 response["Cache-Control"] = "no-cache, no-store, must-revalidate" # HTTP 1.1. response["Pragma"] = "no-cache" # HTTP 1.0. response["Expires"] = "0" # Proxies. return response
def get(self, request, filename, new_filename): """ Handles GET requests and serves a static file as an attachment. """ # calculate the local file path of the file path = get_content_storage_file_path(filename) # if the file does not exist on disk, return a 404 if not os.path.exists(path): raise Http404('"%(filename)s" does not exist locally' % {'filename': filename}) # generate a file response response = FileResponse(open(path, 'rb')) # set the content-type by guessing from the filename response['Content-Type'] = mimetypes.guess_type(filename)[0] # set the content-disposition as attachment to force download response['Content-Disposition'] = 'attachment;' # set the content-length to the file size response['Content-Length'] = os.path.getsize(path) return response
def post(self, request): data = self._parse_query_params(request.data) dataset_id = data.pop("datasetId", None) if dataset_id is None: return Response(status=status.HTTP_400_BAD_REQUEST) dataset = self.gpf_instance.get_wdae_wrapper(dataset_id) if dataset is None: return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR) user = request.user user = request.user handle_partial_permissions(user, dataset_id, data) download_limit = None if not (user.is_authenticated and user.has_unlimitted_download): download_limit = self.DOWNLOAD_LIMIT data.update({"limit": download_limit}) config = dataset.config.gene_browser freq_col = config.frequency_column variants = dataset.get_gene_view_summary_variants_download( freq_col, **data) response = FileResponse(variants, content_type="text/tsv") response["Content-Disposition"] = \ "attachment; filename=summary_variants.tsv" response["Expires"] = "0" return response
def download(self, request, pk=None): """ Download a file for the current user's hacker application. """ answer_file = get_object_or_404(self.get_queryset(), pk=pk) self.check_object_permissions(self.request, answer_file) return FileResponse(answer_file.file.open())
def contractors_to_xls(request): column_descriptions = [ { 'machine_name': 'id', 'display_name': 'Номер' }, { 'machine_name': 'title', 'display_name': 'Наименование', 'width': 80 }, { 'machine_name': 'category', 'display_name': 'Категория', 'width': 30, 'subs': dict(Contractor.CONTRACTOR_CATEGORY) }, { 'machine_name': 'dt_created', 'display_name': 'Дата создания', 'width': 30 }, { 'machine_name': 'dt_updated', 'display_name': 'Дата изменения', 'width': 30 }, ] xls_data = model_to_xls(Contractor, column_descriptions) return FileResponse( xls_data, content_type= 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', filename='products.xlsx')
def send_file(request, f): f = os.path.join(data_path, f) if os.path.exists(f): return FileResponse(open(f, 'rb')) else: return render(request, 'error.html', {'message': 'File does not exist %s' % os.path.basename(f)})
def retrieve(self, request, *args, **kwargs): instance = File.objects.filter(**kwargs).first() if instance: if instance.account and instance.account.platform == "qiniu": # 获取文件的下载地址 # http还是https scheme = request.META['wsgi.url_scheme'] # Redis缓存 file_download_url = instance.get_download_url(scheme=scheme) if file_download_url: return HttpResponseRedirect(redirect_to=file_download_url, status=302) # 不存在缓存中 # 竟然没返回图片地址,那么就从自身服务器获取 # 没找到,或者没访问权限 # 从服务器返回文件 try: resp = FileResponse(open(instance.file.path, 'rb')) return resp except Exception as e: print(str(e)) return HttpResponse(status=404) else: return HttpResponse(status=404)
def download_csv_file(request, log_type, facility_id): if facility_id: facility_name = Facility.objects.get(pk=facility_id).name else: facility_name = request.user.facility.name facility_id = request.user.facility.id if log_type in CSV_EXPORT_FILENAMES.keys(): filepath = os.path.join( conf.KOLIBRI_HOME, "log_export", CSV_EXPORT_FILENAMES[log_type].format(facility_name, facility_id[:4]), ) else: filepath = None # if the file does not exist on disk, return a 404 if filepath is None or not os.path.exists(filepath): raise Http404( "There is no csv export file for {} available".format(log_type)) # generate a file response response = FileResponse(io.open(filepath, "rb")) # set the content-type by guessing from the filename response["Content-Type"] = "text/csv" # set the content-disposition as attachment to force download response["Content-Disposition"] = "attachment; filename={}".format( CSV_EXPORT_FILENAMES[log_type].format(facility_name, facility_id[:4])) # set the content-length to the file size response["Content-Length"] = os.path.getsize(filepath) return response
def make_file_response(file, file_name): res = FileResponse(file, filename=file_name) # 한글파일명 인코딩 file_name = urllib.parse.quote_plus(file_name) res["Content-Type"] = "application/octet-stream" res["Content-Disposition"] = "attachment;filename={}".format(file_name) return res
def render_submitted_declaration_pdf_for_user(request): from evictionfree.declaration_sending import render_declaration user = request.user if not hasattr(user, "submitted_hardship_declaration"): raise Http404() b = render_declaration(user.submitted_hardship_declaration) return FileResponse(BytesIO(b), filename=hardship_declaration.PDF_NAME)
def file(self, request, *args, **kwargs): submission = self.get_object() filename = request.query_params['filename'] try: return FileResponse(submission.get_file(filename)) except ObjectDoesNotExist: return response.Response('File "{}" not found'.format(filename), status=status.HTTP_404_NOT_FOUND)
def serve_protected_document(request,folder, file): # document = get_object_or_404(File, attachment="converted/" + file) path = MEDIA_ROOT + '/' + folder + '/' +file response = FileResponse(open(path,'rb')) # response["Content-Disposition"] = "attachment; filename=" + file return response
def post(self, request): process = Process(request) video_stream = process.run if video_stream: video = BytesIO(video_stream) return FileResponse(video, filename="video.mp4", as_attachment=True) return MESSAGE_RESPONSE(process.failure)
def download_document(request, id: str): cf = get_object_or_404(ComponentFile, id=id) path = cf.file.path if os.path.exists(path): response = FileResponse(open(path, "rb"), filename=cf.filename, as_attachment=True) return response raise Http404("Datei nicht gefunden")
def get_h5p(zf, embedded_filepath): file_size = 0 if not embedded_filepath: # Get the h5p bootloader, and then run it through our hashi templating code. # return the H5P bootloader code try: h5pdata = load_json_from_zipfile(zf, "h5p.json") contentdata = load_json_from_zipfile(zf, "content/content.json") except KeyError: raise Http404("No valid h5p file was found at this location") jsfiles, cssfiles = recursive_h5p_dependencies(zf, h5pdata) jsfiles = jsfiles.keys() cssfiles = cssfiles.keys() path_includes_version = ( "true" if "-" in [name for name in zf.namelist() if "/" in name][0] else "false") template = loader.get_template("content/h5p.html") main_library_data = [ lib for lib in h5pdata["preloadedDependencies"] if lib["machineName"] == h5pdata["mainLibrary"] ][0] bootstrap_content = template.render( { "jsfiles": jsfiles, "cssfiles": cssfiles, "content": json.dumps( json.dumps(contentdata, separators=(",", ":"), ensure_ascii=False)), "library": "{machineName} {majorVersion}.{minorVersion}".format( **main_library_data), "path_includes_version": path_includes_version, }, None, ) content = parse_html(bootstrap_content) content_type = "text/html" response = HttpResponse(content, content_type=content_type) file_size = len(response.content) elif embedded_filepath.startswith("dist/"): # return static H5P dist resources path = finders.find("assets/h5p-standalone-" + embedded_filepath) if path is None: raise Http404("{} not found".format(embedded_filepath)) # try to guess the MIME type of the embedded file being referenced content_type = (mimetypes.guess_type(embedded_filepath)[0] or "application/octet-stream") response = FileResponse(open(path, "rb"), content_type=content_type) file_size = os.stat(path).st_size if file_size: response["Content-Length"] = file_size return response
def sync_download(request): locks = [] prepared_tables = [] try: request_params = json.loads(request.body) layers = request_params["layers"] # we will ignore bbox for the moment bbox = request_params.get("bbox", None) for layer in layers: #FIXME: maybe we need to specify if we want the layer for reading or writing!!!! Assume we always want to write for the moment lock = add_layer_lock(layer, request.user, lock_type=LayerLock.SYNC_LOCK) locks.append(lock) conn = _get_layer_conn(lock.layer) if not conn: raise HttpResponseBadRequest("Bad request") prepared_tables.append({"layer": lock.layer, "connection": conn}) (fd, file_path) = tempfile.mkstemp(suffix=".sqlite", prefix="syncdwld_") os.close(fd) os.remove(file_path) if len(prepared_tables) > 0: ogr = gdaltools.ogr2ogr() ogr.set_output_mode(layer_mode=ogr.MODE_LAYER_CREATE, data_source_mode=ogr.MODE_DS_CREATE_OR_UPDATE) for table in prepared_tables: if table["connection"].schema: in_tbl_name = table["connection"].schema + "." + table[ "layer"].name else: in_tbl_name = table["layer"].name ogr.set_input(table["connection"], table_name=in_tbl_name).set_output( file_path, table_name=table["layer"].get_qualified_name( )).execute() gdaltools.ogrinfo(file_path, sql="SELECT UpdateLayerStatistics()") locked_layers = [lock.layer for lock in locks] _copy_images(locked_layers, file_path) file = TemporaryFileWrapper(file_path) response = FileResponse(file, content_type='application/spatialite') #response['Content-Disposition'] = 'attachment; filename=db.sqlite' #response['Content-Length'] = os.path.getsize(path) return response else: return HttpResponseBadRequest("Bad request") except Exception as exc: for layer in locks: remove_layer_lock(lock.layer, request.user) logger.exception("sync_download error") return HttpResponseBadRequest("Bad request")
def get(self, request): data, context = self.get_request_obj(request) seri = GetPhotoSerializer(data=data) self.validate_serializer(seri) photo_path = get_specified_photo(**seri.data) real_path = os.path.join(settings.BASE_DIR, photo_path) return FileResponse(open(real_path), content_type='image')
def serve_protected_document(request, folder, file): if not request.user.id: referer_address = request.META.get('HTTP_REFERER') if not referer_address: return '' if not referer_address.endswith('localhost:4200/'): return '' path = MEDIA_ROOT + '/' + folder + '/' + file response = FileResponse(open(path, 'rb')) return response
def download_file(request): file_path = request.GET.get('file_path', '') pk = request.GET.get('id', '') if pk: BSInfo.objects.filter(id=pk).update(is_download=1) file = open(file_path, 'rb') response = FileResponse(file) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename="{0}"'.format( urlquote(file_path.split('/')[-1])) return response
def data(self, request, pk=None): f = self.get_object() if not f.status in status_whitelist: return Response('File has not been successfully virus scanned', status=status.HTTP_400_BAD_REQUEST) stream = retrieve(f.get_url()) download = 'download' in request.query_params return FileResponse(stream, filename=f.name, as_attachment=download)