def get(self, request, identifier, format=None): params = WatermarkQueryStringSerializer(data=request.query_params) if not params.is_valid(): return Response(status=400, data={"validation_error": params.errors}) try: image_record = Image.objects.get(identifier=identifier) except Image.DoesNotExist: return Response(status=404, data='Not Found') image_url = str(image_record.url) image_info = { 'title': image_record.title, 'creator': image_record.creator, 'license': image_record.license, 'license_version': image_record.license_version } # Create the actual watermarked image. watermarked, exif = watermark(image_url, image_info, params.data['watermark']) # Re-insert EXIF metadata. if exif: exif_bytes = piexif.dump(exif) else: exif_bytes = None img_bytes = io.BytesIO() _save_wrapper(watermarked, exif_bytes, img_bytes) if params.data['embed_metadata']: # Embed ccREL metadata with XMP. work_properties = { 'creator': image_record.creator, 'license_url': image_record.license_url, 'attribution': image_record.attribution, 'work_landing_page': image_record.foreign_landing_url, 'identifier': str(image_record.identifier) } try: with_xmp = ccrel.embed_xmp_bytes(img_bytes, work_properties) return FileResponse(with_xmp, content_type='image/jpeg') except (libxmp.XMPError, AttributeError) as e: # Just send the EXIF-ified file if libxmp fails to add metadata. log.error('Failed to add XMP metadata to {}'.format( image_record.identifier)) log.error(e) response = HttpResponse(content_type='image/jpeg') _save_wrapper(watermarked, exif_bytes, response) return response else: response = HttpResponse(img_bytes, content_type='image/jpeg') _save_wrapper(watermarked, exif_bytes, response) return response
def get(self, request, *args, **kwargs): # 找到问卷调查的对应的唯一码 codes = models.SurveyCode.objects.filter(middle_survey_id=kwargs.get("pk")) # 写入到 excel 文件, 下载 xls = xlwt.Workbook(encoding="utf-8", style_compression=2) sheet = xls.add_sheet("sheet1", cell_overwrite_ok=True) sheet.write(0, 0, '号码') for index, code in enumerate(codes.iterator(), 1): sheet.write(index, 0, code.unique_code) xls.save("唯一码.xls") return FileResponse(open(os.path.join(settings.BASE_DIR, "唯一码.xls"), "rb"), as_attachment=True)
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 h5pdata = json.loads(zf.open(zf.getinfo("h5p.json")).read()) jsfiles, cssfiles = recursive_h5p_dependencies(zf, h5pdata) jsfiles = jsfiles.keys() cssfiles = cssfiles.keys() contentdata = zf.open(zf.getinfo("content/content.json")).read() 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": contentdata, "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) # 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 get(self, request, zipped_filename, embedded_filepath): """ Handles GET requests and serves a static file from within the zip file. """ # calculate the local file path to the zip file zipped_path = get_content_storage_file_path(zipped_filename) # if the zipfile doesn't not exist on disk, return a 404 if not os.path.exists(zipped_path): raise Http404('"%(filename)s" does not exist locally' % {'filename': zipped_filename}) # if client has a cached version, use that (we can safely assume nothing has changed, due to MD5) if request.META.get('HTTP_IF_MODIFIED_SINCE'): return HttpResponseNotModified() with zipfile.ZipFile(zipped_path) as zf: # get the details about the embedded file, and ensure it exists try: info = zf.getinfo(embedded_filepath) except KeyError: raise Http404('"{}" does not exist inside "{}"'.format( embedded_filepath, zipped_filename)) # try to guess the MIME type of the embedded file being referenced content_type = mimetypes.guess_type( embedded_filepath)[0] or 'application/octet-stream' # generate a streaming response object, pulling data from within the zip file response = FileResponse(zf.open(info), content_type=content_type) # set the last-modified header to the date marked on the embedded file if info.date_time: response["Last-Modified"] = http_date( float(datetime.datetime(*info.date_time).strftime("%s"))) # cache these resources forever; this is safe due to the MD5-naming used on content files response["Expires"] = "Sun, 17-Jan-2038 19:14:07 GMT" # set the content-length header to the size of the embedded file if info.file_size: response["Content-Length"] = info.file_size # ensure the browser knows not to try byte-range requests, as we don't support them here response["Accept-Ranges"] = "none" return response
def get(request, name): if name == 'vfwVM': file_path = '/data/VBox_VFORWaTer.zip' # file_path = '/home/marcus/tmp/customs.shp' if Path(file_path).exists(): with open(file_path, 'rb') as fh: response = FileResponse(open(file_path, 'rb')) print('response: ', response) return response else: print('no file at: ', file_path) error_404_view(request, 'not available') else: error_404_view(request, 'not available')
def retrieve(self, request, *args, **kwargs): bucket_object = self.get_object() content_format = request.query_params.get('format') # TODO: This is a bit ugly, since ideally, only the renderer # should be aware of the format if content_format == "binary": response = FileResponse( streaming_content=bucket_object.iter_content(), content_type='application/octet-stream') response['Content-Disposition'] = ('attachment; filename="%s"' % bucket_object.name) return response else: serializer = self.get_serializer(bucket_object) return Response(serializer.data)
def xfilesend_response(request, filename, disposition='attachment', download_name=None, content_type='application/octet-stream'): ''' xfilesend_response is a helper function to use xsendfile if available VIP_MANAGE_SERVER should be set by manage.py to indicate XSendFile is disabled. This is only via the os.environ, Arguments --------- filename - Full path to the file where it exists on disk Optional Arguments ------------------ disposition - Content-Disposition Value, see [here](http://www.iana.org/assignments/cont-disp/cont-disp.xhtml). Default is attachment, but None will result in the field not being set download_name - The name the webbrowser will default to if saved. Default is None, indicating do not use this feature. An empty string '' will indicate to use the basename of the filename instead. You can specify any string to set the default to that name content_type - The MIME type. Default is application/octet-stream. Using application/force-download is considered hackish and ill advised ''' if os.environ.get('VIP_MANAGE_SERVER', '0') != '1': response = HttpResponse(content_type=content_type) response['X-Accel-Redirect'] = smart_str(filename) else: response = FileResponse(open(filename, 'rb'), content_type=content_type) response['Content-Length'] = os.stat(filename).st_size if disposition: response['Content-Disposition'] = disposition if download_name is not None: if download_name: response[ 'Content-Disposition'] += '; filename="%s"' % download_name else: response['Content-Disposition'] += '; filename="%s"' % \ os.path.basename(filename) return response
def file_download(request): file_name = request.query_params.get('file_name') if not file_name: raise ValidateException().add_message("error:params error", "缺少文件名") file_path = os.path.join(settings.MEDIA_ROOT, file_name) if not os.path.exists(file_path): raise ValidateException().add_message("error:file not found", "未找到对应文件") file_info = FileUpload.objects.filter(file=file_name).first() if file_info: file_name = file_info.file_name # fw = FileWrapper(open(file_path, 'rb')) response = FileResponse(open(file_path, 'rb'), as_attachment=True, filename=file_name) return response
def photo(request): if not auth.check_login(request): return HttpResponse("error") sid = request.REQUEST.get('id') if None == sid: return HttpResponseNotFound("not found") file_path = data.photo_path(sid) if not os.path.exists(file_path): return HttpResponseNotFound('not found') response = FileResponse(open(file_path, 'rb')) response['Content-Type'] = 'image/jpeg' return response
def retrieve_zip(self, request, spine_uuid=None): path = self.check_spine_uuid(spine_uuid) f = BytesIO() with ZipFile(f, 'w') as zipfile: for fn in os.listdir(path): if fn.endswith('.skel') or fn.endswith('.png') or fn.endswith( '.atlas'): zipfile.write(os.path.join(path, fn), fn) zipfile.writestr('data.json', data=json.dumps( skel2json.Handler( open(os.path.join(path, 'data.skel'), 'rb')).handle())) f.seek(0) # when being closed , it goes to end return FileResponse(f, as_attachment=True, filename=spine_uuid + '.zip')
def get(self, request): semester = active_semester() qs = list(Siswa.objects.select_related('kelas').all().values()) if not qs: messages.error(request, 'Tidak ada data siswa yang dapat di ekspor') return redirect('list-siswa') cols = [] for col in [field.name for field in Siswa._meta.fields]: if col in ['id']: continue if col in ['nis', 'nisn']: col = col.upper() else: col = col.title() col = col.replace('_', ' ') cols.append(col) cols.append('Kelas') for siswa in qs: try: siswa['kelas_id'] = Siswa.objects.get( nis=siswa['nis']).kelas.get( tahun_pelajaran=semester.tahun_pelajaran).nama.replace( '-', ' ') except Kelas.DoesNotExist: siswa['kelas_id'] = None siswa['tanggal_lahir'] = siswa['tanggal_lahir'].strftime( '%Y-%m-%d') if siswa['gender'] == 'P': siswa['gender'] = 'Pria' else: siswa['gender'] = 'Wanita' file = f'{settings.MEDIA_ROOT}/excel/Export Siswa.xlsx' json_string = json.dumps(qs) df = pandas.read_json(json_string, dtype={'nis': str, 'nisn': str}) df = df.drop(columns='id') df.columns = cols append_df_to_excel(file, df) file = open(file, 'rb') response = FileResponse(file, content_type='application/force-download') response[ 'Content-Disposition'] = f'attachment; filename=Siswa {semester}.xlsx' return response
def get_file_view(request): id = request.GET.get('id', None) if id is None: return HttpResponseNotFound() try: s_file = SeminarFile.objects.get(id=id) 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=s_file.filename ) return response
def logs(self, request, **kwargs): start = safe_str2int(request.query_params.get("start", 0)) end = safe_str2int(request.query_params.get("end", None)) try: if start == 0 and end is None: data = logs_instance.open(self.get_object()) response = FileResponse(data, content_type="application/yaml") else: data = logs_instance.read(self.get_object(), start, end) response = HttpResponse(data, content_type="application/yaml") if not data: raise NotFound() response["Content-Disposition"] = ( "attachment; filename=job_%d.yaml" % self.get_object().id) return response except FileNotFoundError: raise NotFound()
def render_file(request, file, filename): """For a given @file path and @filename, pretty print the contents of the file as an HTML page using pygments""" mime = guess_type(filename, True) if mime[0] is None or mime[0].split('/')[0] != 'text': response = FileResponse(open(file, "rb")) response['Content-Type'] = str(guess_type(filename, False)[0]) return response with open(file, mode="r", encoding="utf-8", errors='ignore') as open_file: content = open_file.read() lexermime = 'text/x-java' if mime[0] == 'text/x-java-source' else mime[0] lexer = pygments.lexers.get_lexer_for_mimetype(lexermime) detail = { "content": pyghi(content, lexer, pygform.HtmlFormatter(encoding='utf-8',linenos='table')), "filename": filename } return render(request, 'file_viewer/pretty_file.html', detail)
def ConstructOfficeTabletPdf(data): buffer = io.BytesIO() doc = SimpleDocTemplate(buffer, pagesize=A4, rightMargin=30,leftMargin=30, topMargin=30,bottomMargin=18) doc.pagesize = landscape(A4) elements = [Spacer(1,2*inch)] dt = [ ["Beneficiar", "Tip Programare", "Status", "Locatie Centru de Vaccinare","Data Programarii","Ora Programarii"], # [data['person']['name']+" "+data['person']['last_name'], data['kind'], data['status'], data['office']['name']+", "+data['office']['city']['name']+", "+data['office']['county']['name'],data['date'],str(data['time'])], ] for x in data: if x['status'] != "anulata": s = [x['person']['name']+" "+x['person']['last_name'], x['kind'], x['status'], x['office']['name']+", "+x['office']['city']['name']+", "+x['office']['county']['name'],x['date'],str(x['time'])] dt.append(s) #TODO: Get this line right instead of just copying it from the docs style = TableStyle([('ALIGN',(1,1),(-2,-2),'RIGHT'), ('TEXTCOLOR',(1,1),(-2,-2),colors.red), ('VALIGN',(0,0),(0,-1),'TOP'), ('TEXTCOLOR',(0,0),(0,-1),colors.blue), ('ALIGN',(0,-1),(-1,-1),'CENTER'), ('VALIGN',(0,-1),(-1,-1),'MIDDLE'), ('TEXTCOLOR',(0,-1),(-1,-1),colors.green), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ]) #Configure style and word wrap s = getSampleStyleSheet() s = s["BodyText"] s.wordWrap = 'CJK' data2 = [[Paragraph(cell, s) for cell in row] for row in dt] t=Table(data2) t.setStyle(style) #Send the data and build the file elements.append(t) doc.build(elements,onFirstPage=myFirstPage) buffer.seek(0) return FileResponse(buffer, as_attachment=True, filename='hello.pdf')
def xfilesend_response(request, filename, disposition='attachment', download_name=None, content_type='application/octet-stream'): ''' xfilesend_response is a helper function to use xsendfile if available The httpd.conf files should have SetEnv VIP_XSENDFILE 1 to indicate XSendFile is enabled. This is only accessible via the request.environ, not the os environ [link](https://modwsgi.readthedocs.org/en/develop/user-guides/configuration-guidelines.html#application-configuration). Arguments --------- filename - Full path to the file where it exists on disk Optional Arguments ------------------ disposition - Content-Disposition Value, see [here](http://www.iana.org/assignments/cont-disp/cont-disp.xhtml). Default is attachment, but None will result in the field not being set download_name - The name the webbrowser will default to if saved. Default is None, indicating do not use this feature. An empty string '' will indicate to use the basename of the filename instead. You can specify any string to set the default to that name content_type - The MIME type. Default is application/octet-stream. Using application/force-download is considered hackish and ill advised ''' if request.environ.get('VIP_XSENDFILE', '0') == '1': response = HttpResponse(content_type=content_type) response['X-Sendfile'] = smart_str(filename) else: response = FileResponse(open(filename, 'rb'), content_type=content_type) response['Content-Length'] = os.stat(filename).st_size if disposition: response['Content-Disposition'] = disposition if download_name is not None: if download_name: response['Content-Disposition'] += '; filename="%s"' % download_name else: response['Content-Disposition'] += '; filename="%s"' % \ os.path.basename(filename) return response
def get(self, request, *args, **kwargs): tipo = self.kwargs.get('tipo') id_libro = self.kwargs.get('id_libro') libro = Libro.objects.get(id=id_libro) if tipo == 1: tipol = "Consumidor" libroEx = export_libroCF(id_libro) elif tipo == 2: tipol = "Contibuyente" libroEx = export_libroct(id_libro) elif tipo == 3: tipol = "Compras" libroEx = export_librocm(id_libro) print(libro) # create the HttpResponse object ... response = FileResponse(open(libroEx, 'rb')) return response
def download_from_archive(release, entry): archive_ident = entry["archive_ident"] # Do not use ReleaseFileCache here, we view download as a singular event archive_file = ReleaseFile.objects.get(release_id=release.id, ident=archive_ident) archive = ZipFile(archive_file.file.getfile()) fp = archive.open(entry["filename"]) headers = entry.get("headers", {}) response = FileResponse( fp, content_type=headers.get("content-type", "application/octet-stream"), ) response["Content-Length"] = entry["size"] response["Content-Disposition"] = 'attachment; filename="%s"' % posixpath.basename( " ".join(entry["filename"].split()) ) return response
def get_embedded_file(request, zf, zipped_filename, embedded_filepath): # if no path, or a directory, is being referenced, look for an index.html file if not embedded_filepath or embedded_filepath.endswith("/"): embedded_filepath += "index.html" # get the details about the embedded file, and ensure it exists try: info = zf.getinfo(embedded_filepath) except KeyError: raise Http404('"{}" does not exist inside "{}"'.format( embedded_filepath, zipped_filename)) # file size file_size = 0 # try to guess the MIME type of the embedded file being referenced content_type = (mimetypes.guess_type(embedded_filepath)[0] or "application/octet-stream") if zipped_filename.endswith("zip") and ( embedded_filepath.endswith("htm") or embedded_filepath.endswith("html")): content = zf.open(info).read() html = parse_html(content) response = HttpResponse(html, content_type=content_type) file_size = len(response.content) elif not os.path.splitext(embedded_filepath)[1] == ".json": # generate a streaming response object, pulling data from within the zip file response = FileResponse(zf.open(info), content_type=content_type) file_size = info.file_size else: image_prefix_url = generate_image_prefix_url(request, zipped_filename) # load the stream from json file into memory, replace the path_place_holder. content = zf.open(info).read() str_to_be_replaced = ("$" + exercises.IMG_PLACEHOLDER).encode() content_with_path = content.replace(str_to_be_replaced, image_prefix_url) response = HttpResponse(content_with_path, content_type=content_type) file_size = len(response.content) # set the content-length header to the size of the embedded file if file_size: response["Content-Length"] = file_size return response
def get_embedded_file( request, zf, zipped_filename, embedded_filepath, skip_hashi=False ): # if no path, or a directory, is being referenced, look for an index.html file if not embedded_filepath or embedded_filepath.endswith("/"): embedded_filepath += "index.html" skip_hashi = skip_hashi or request.GET.get("SKIP_HASHI") # get the details about the embedded file, and ensure it exists try: info = zf.getinfo(embedded_filepath) except KeyError: raise Http404( '"{}" does not exist inside "{}"'.format(embedded_filepath, zipped_filename) ) # file size file_size = 0 # try to guess the MIME type of the embedded file being referenced content_type = ( mimetypes.guess_type(embedded_filepath)[0] or "application/octet-stream" ) if ( zipped_filename.endswith("zip") and (embedded_filepath.endswith("htm") or embedded_filepath.endswith("html")) and not skip_hashi ): content = zf.open(info).read() html = parse_html(content) response = HttpResponse(html, content_type=content_type) file_size = len(response.content) else: # generate a streaming response object, pulling data from within the zip file response = FileResponse(zf.open(info), content_type=content_type) file_size = info.file_size # set the content-length header to the size of the embedded file if file_size: response["Content-Length"] = file_size return response
def ConstructAppointmentPdf(data): d = datetime.datetime.today().strftime('%d-%m-%Y') buffer = io.BytesIO() p = canvas.Canvas(buffer,pagesize=A4) p.setFont("Helvetica",15,leading=None) p.drawString(260,800,"Programare") p.line(0,780,1000,780) p.line(0,778,1000,778) x1 = 20 y1=750 print(data) p.drawString(x1,y1-30,"Beneficiar") p.drawString(x1+100,y1-30,"Beneficiar") p.setTitle(f'Progamare') p.showPage() p.save() buffer.seek(0) return FileResponse(buffer, as_attachment=True, filename='hello.pdf')
def download_file(request): """ File Download API - Query - path: string, existing file's path - Response - 200: File - 400: Results if query is missing or invalid """ missing, data = extract_data(request.GET, ['path']) if len(missing) > 0: return missing_keys(DataType.QUERY, missing) path = data.get('path') if not os.path.isfile(path): return wrong_keys(DataType.QUERY, ['path']) return FileResponse(open(path, 'rb'))
def download_csv_file(request, filename, facility_id): if facility_id: facility_name = Facility.objects.get(pk=facility_id).name else: facility_name = request.user.facility.name 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" ) # Append the facility name to the beginning of the filename filename_with_facility = "{}_{}".format(facility_name, str(exported_filename)) response["Content-Disposition"] = "attachment; filename={}".format( filename_with_facility ) # set the content-length to the file size response["Content-Length"] = os.path.getsize(filepath) translation.deactivate() return response
def download_csv_file(request, filename): 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 response[ "Content-Disposition"] = "attachment; filename=users_{}.csv".format( datetime.now().strftime("%Y%m%d_%H%M%S")) # set the content-length to the file size response["Content-Length"] = os.path.getsize(filepath) return response
def get_embedded_file(zipped_path, zipped_filename, embedded_filepath): with zipfile.ZipFile(zipped_path) as zf: # handle H5P files if zipped_path.endswith("h5p") and not embedded_filepath: return get_h5p(zf) # if no path, or a directory, is being referenced, look for an index.html file if not embedded_filepath or embedded_filepath.endswith("/"): embedded_filepath += "index.html" # get the details about the embedded file, and ensure it exists try: info = zf.getinfo(embedded_filepath) except KeyError: return HttpResponseNotFound( '"{}" does not exist inside "{}"'.format( embedded_filepath, zipped_filename)) # file size file_size = 0 # try to guess the MIME type of the embedded file being referenced content_type = (mimetypes.guess_type(embedded_filepath)[0] or "application/octet-stream") if zipped_filename.endswith("zip") and ( embedded_filepath.endswith("htm") or embedded_filepath.endswith("html")): content = zf.open(info).read() html = parse_html(content) response = HttpResponse(html, content_type=content_type) file_size = len(response.content) else: # generate a streaming response object, pulling data from within the zip file response = FileResponse(zf.open(info), content_type=content_type) file_size = info.file_size # set the content-length header to the size of the embedded file if file_size: response["Content-Length"] = file_size return response
def animation_download(request, pk): user = request.user try: animation = Animation.objects.get(pk=pk) except Animation.DoesNotExist: logger.error("Animation to download doesn't exist. User: %s", user.username) return Http404 if user in animation.users_purchased.all(): f = open(os.path.join(settings.MEDIA_ROOT, animation.caff_file.name), "rb") res = FileResponse(f) res["Content-Length"] = animation.caff_file.size res["Content-Disposition"] = f"attachment; filename={animation.id}.caff" else: logger.error("Animation to download isn't owned by user. User: %s", user.username) res = Response(status=HTTP_401_UNAUTHORIZED) return res
def get(self, request, *args, **kwargs): image = self.get_object() dim = request.GET.get('dim', None) if dim: try: width, height = parse_dimension_string(dim) except ValueError as verr: return HttpResponseBadRequest(str(verr)) else: width = height = None if not width: out_image = image.image filename = image.image.name else: try: out_image = get_thumbnailer(image.image).get_thumbnail({ 'size': (width, height), 'box': image.cropping, 'crop': True, 'detail': True, }) filename = "%s-%dx%d%s" % (image.image.name, width, height, os.path.splitext(out_image.name)[1]) except: return HttpResponseBadRequest() # FIXME: Use SendFile headers instead of Django output when not in debug mode out_image.seek(0) resp = FileResponse(out_image, content_type=guess_type(filename, False)[0]) resp[ "Content-Disposition"] = "attachment; filename=%s" % os.path.basename( filename) return resp
def image(self, request, pk=None): qs = self.get_queryset() obj = get_object_or_404(qs, pk=pk) height = request.GET.get('height', None) width = request.GET.get('width', None) image = obj.image if image is None: raise Http404 if height or width: try: dim = determine_image_dim(image, width, height) except ValueError as verr: return HttpResponseBadRequest(str(verr)) else: dim = None if not dim: out_image = obj.image filename = out_image.name else: out_image = get_thumbnailer(obj.image).get_thumbnail({ 'size': dim, 'box': obj.image_cropping, 'crop': True, 'detail': True, }) filename = "%s-%dx%d%s" % (obj.image.name, dim[0], dim[1], os.path.splitext(out_image.name)[1]) # FIXME: Use SendFile headers instead of Django output when not in debug mode out_image.seek(0) resp = FileResponse(out_image, content_type=guess_type(filename, False)[0]) return resp
def changeData(request): if request.POST: post_msg = request.POST.get("data") msg = eval(post_msg)["msg"] msg_id = eval(post_msg)["id"].split("_")[1] file = FileUpload.objects.get(id=msg_id) if msg == "delete": file.file.delete() file.delete() return HttpResponse() elif request.GET: id = request.GET['url'].split("_")[1] file = FileUpload.objects.get(id=id) try: file_route = file.file.path except: file_route = file.file_full_route response = FileResponse(file_iterator(file_route)) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename="{}"'.format( file.filename) return response
def detail_response_get(request, pk, Model, Serializer): obj = get_object(Model, pk) ## download media download = request.GET.get('download') if download: if hasattr(obj, download): media = obj.__getattribute__(download) if not isinstance(media, File): raise NotFound(detail="AttributeNotMedia attr:%s Model:%s" % (download, Model.__name__)) ## TODO: if manually delete the file from media and call the below line : FileNotFoundError raised response = FileResponse(media) response[ "Content-Disposition"] = "attachment; filename=" + os.path.split( media.name)[1] return response else: raise NotFound(detail="AttributeNotExists attr:%s Model:%s" % (download, Model.__name__)) serialized = Serializer(obj) return Response(serialized.data)