def admin_download_version(request,entryid,version): entry = get_object_or_404(Entry,id=entryid) if request.user.has_perm("entry.admin") or request.user.has_perm("compo.admin"): if version == str(0): #download all versions packfile = tempfile.NamedTemporaryFile(delete=False) pack = zipfile.ZipFile(packfile.name,"w",zipfile.ZIP_DEFLATED) for version in entry.versions(): if version.is_file: lfile = get_entry_file(version.data) pack.write(lfile.name,entry.get_publish_filename("_v%s" % version.version)) os.unlink(lfile.name) pack.close() dfile = django.core.files.File(packfile) return serve_file(request,dfile,None,entry.get_publish_filename("_all.zip",False),"application/octet-stream") else: try: eversion = entry.versions().get(version=version) if eversion.data: return serve_file(request,eversion.data,None,entry.get_publish_filename("_v%s" % version),"application/octet-stream") except EntryVersion.DoesNotExist: pass return HttpResponseNotFound()
def download_file(request, file_id=None): upload = get_object_or_None(FileUpload, pk=file_id) if upload: if upload.public: return serve_file(request, upload.file) else: if request.user.get_profile().personnel_type in upload.allowed_personnels.all() or request.user.get_profile().office in upload.allowed_offices.all() or request.user in upload.allowed_users.all(): return serve_file(request, upload.file) return reverse_redirect('home')
def get_document_image(request, document_id, size=PREVIEW_SIZE, quality=QUALITY_DEFAULT): check_permissions(request.user, "documents", [PERMISSION_DOCUMENT_VIEW]) document = get_object_or_404(Document, pk=document_id) page = int(request.GET.get("page", 1)) transformation_list = [] try: # Catch invalid or non existing pages document_page = DocumentPage.objects.get(document=document, page_number=page) for page_transformation in document_page.documentpagetransformation_set.all(): try: if page_transformation.transformation in TRANFORMATION_CHOICES: output = TRANFORMATION_CHOICES[page_transformation.transformation] % eval( page_transformation.arguments ) transformation_list.append(output) except Exception, e: if request.user.is_staff: messages.warning( request, _(u"Error for transformation %(transformation)s:, %(error)s") % {"transformation": page_transformation.get_transformation_display(), "error": e}, ) else: pass except ObjectDoesNotExist: pass tranformation_string = " ".join(transformation_list) try: filepath = in_image_cache( document.checksum, size=size, quality=quality, extra_options=tranformation_string, page=page - 1 ) if filepath: return serve_file(request, File(file=open(filepath, "r")), content_type="image/jpeg") # Save to a temporary location filepath = document_save_to_temp_dir(document, filename=document.checksum) output_file = convert( filepath, size=size, format="jpg", quality=quality, extra_options=tranformation_string, page=page - 1 ) return serve_file(request, File(file=open(output_file, "r")), content_type="image/jpeg") except UnkownConvertError, e: if request.user.is_staff or request.user.is_superuser: messages.error(request, e) if size == THUMBNAIL_SIZE: return serve_file(request, File(file=open("%simages/%s" % (settings.MEDIA_ROOT, PICTURE_ERROR_SMALL), "r"))) else: return serve_file( request, File(file=open("%simages/%s" % (settings.MEDIA_ROOT, PICTURE_ERROR_MEDIUM), "r")) )
def image(request): wealth = request.session['wealth'] try: receipt = Receipt.objects.get(wealth=wealth, id=request.GET['id']) return serve_file(request, receipt.image) except ObjectDoesNotExist: return rc.NOT_FOUND
def download_handler(request, pk): if request.user.is_authenticated(): upload = get_object_or_404(UploadModel, pk=pk) return serve_file(request, upload.file, save_as=False) else: view_url = reverse('books.views.hello') return HttpResponseRedirect(view_url)
def download(request, material_id): download=Download.objects.create(material=Material.objects.get(id=material_id)) if request.user.is_authenticated(): download.user=request.user.profile download.save() object = get_object_or_404(Material, pk=material_id) return serve_file(request, object.doc)
def retrieve(self, request, *args, **kwargs): instance = self.get_object() return serve_file(request, instance.file, save_as='"%s"' % instance.document.label, content_type=instance.mimetype if instance.mimetype else 'application/octet-stream')
def inserted_file(request, site_short_name, filepath=""): """ Get image from local dropbox and serve. """ from filetransfers.views import can_access data_folder_root = get_data_folder_path(site_short_name) filename = path.join(data_folder_root,filepath) # can this location be served regularly (e.g. it is in public folder)? serve_allowed = can_access(request.user,filepath,site_short_name) # if not, linking to anywhere should be possible because it is convenient # and the security risk is not too great. TODO (is it not?) if not serve_allowed: serve_allowed = can_access(request.user, filepath, site_short_name, override_permission=ComicSiteModel.REGISTERED_ONLY) if serve_allowed: try: file = open(filename,"rb") except Exception: raise Http404 django_file = File(file) return serve_file(request,django_file) else: return HttpResponseForbidden("This file is not available without " "credentials")
def get_avatar(request, **kw): profile = get_object_or_404(Profile, user__exact=ZI(kw.get('id'))) if profile.avatar: # blob_key = str(greeting.avatar.file.blobstore_info._BlobInfo__key) return serve_file(request, profile.avatar) else: return HttpResponseRedirect('/media/img/anon.png')
def download_as_txt_handler(request,pk): file = UploadModel.objects.get(id=pk) response = HttpResponse(mimetype='text/conf') response['Content-Disposition'] = 'attachment; filename='+file.description file_content = serve_file(request, file.file).content response.write(file_content) return response
def download_as_xls_handler(request,pk): file = UploadModel.objects.get(id=pk) response = HttpResponse(mimetype='application/ms-excel') response['Content-Disposition'] = 'attachment; filename='+file.description+'.xls' file_content = serve_file(request, file.file).content response.write(file_content) return response
def document_signature_download(request, document_pk): document = get_object_or_404(Document, pk=document_pk) try: Permission.check_permissions( request.user, (permission_signature_download,) ) except PermissionDenied: AccessControlList.objects.check_access( permission_signature_download, request.user, document ) try: if DocumentVersionSignature.objects.has_detached_signature(document.latest_version): signature = DocumentVersionSignature.objects.detached_signature( document.latest_version ) return serve_file( request, signature, save_as='"%s.sig"' % document.filename, content_type='application/octet-stream' ) except Exception as exception: messages.error(request, exception) return HttpResponseRedirect(request.META['HTTP_REFERER']) return HttpResponseRedirect(request.META['HTTP_REFERER'])
def download_handler_file(request, filepath): """offer file for download based on filepath relative to django root""" f = open(filepath, 'r') file = File(f) # create django file object return serve_file(request, file, save_as=True)
def get(self, request, pk): obj = self.get_object() if request.user.is_staff: f = obj.registration.file file_name = os.path.basename(f. name) return serve_file(request, f, save_as=file_name) return HttpResponseForbidden()
def serve(request, project_name, path, document_root=None,override_permission=""): """ Serve static file for a given project. This is meant as a replacement for the inefficient debug only 'django.views.static.serve' way of serving files under /media urls. """ if document_root == None: document_root = settings.MEDIA_ROOT path = posixpath.normpath(unquote(path)) path = path.lstrip('/') newpath = '' for part in path.split('/'): if not part: # Strip empty path components. continue drive, part = os.path.splitdrive(part) head, part = os.path.split(part) if part in (os.curdir, os.pardir): # Strip '.' and '..' in path. continue newpath = os.path.join(newpath, part).replace('\\', '/') if newpath and path != newpath: return HttpResponseRedirect(newpath) fullpath = os.path.join(document_root,project_name, newpath) storage = DefaultStorage() if not storage.exists(fullpath): # On case sensitive filesystems you can have problems if the project # nameurl in the url is not exactly the same case as the filepath. # find the correct case for projectname then. # Also case sensitive file systems are weird. # who would ever want to have a folder 'data' and 'Data' contain # different files? projectlist = ComicSite.objects.filter(short_name=project_name) if projectlist == []: raise Http404(_("project '%s' does not exist" % project_name )) project_name = projectlist[0].short_name fullpath = os.path.join(document_root,project_name, newpath) if not storage.exists(fullpath): raise Http404(_('"%(path)s" does not exist') % {'path': fullpath}) if can_access(request.user,path,project_name,override_permission): f = storage.open(fullpath, 'rb') file = File(f) # create django file object # Do not offer to save images, but show them directly return serve_file(request, file, save_as=True) else: return HttpResponseForbidden("This file is not available without " "credentials")
def retrieve(self, request, *args, **kwargs): instance = self.get_object() return serve_file( request, instance.file, save_as='"%s"' % instance.document.label, content_type=instance.mimetype if instance.mimetype else 'application/octet-stream' )
def download(request, material_id): download = Download.objects.create(material=Material.objects.get( id=material_id)) if request.user.is_authenticated(): download.user = request.user.profile download.save() object = get_object_or_404(Material, pk=material_id) return serve_file(request, object.doc)
def bg_image(request, bg_image_id): bg_image = get_object_or_404(BackgroundImage, id=bg_image_id) return serve_file(request, bg_image.image) key = 'bg_image_serve' + '-' + bg_image_id #### bg_image_serve = memcache.get(key) if bg_image_serve is not None: response = bg_image_serve else: bg_image = get_object_or_404(BackgroundImage, id=bg_image_id) response = serve_file(request, bg_image.image) #### memcache.add(key, response, 360000) response['Cache-Control'] = 'max-age=360000, must-revalidate' return response
def uploadedfileserve_handler(request, pk): """ Serve a file through django, for displaying images etc. """ upload = get_object_or_404(UploadModel, pk=pk) #if request.user.has_perm("comicmodels.view_ComicSiteModel"): if upload.can_be_viewed_by(request.user): return serve_file(request, upload.file, save_as=False) else: return HttpResponse("You do not have permission to view this.")
def retrieve(self, *args, **kwargs): """Return the file of the selected document.""" document = self.get_object() return serve_file( self.request, document.file, save_as=document.label, content_type=document.file_mimetype )
def get(self, request, *args, **kwargs): obj = self.get_object() if request.user.is_staff: f = obj.registration.file file_name = os.path.basename(f.name) return serve_file(request, f, save_as=file_name) return HttpResponseForbidden()
def folder_export_csv(request, folder_id): previous = request.POST.get( 'previous', request.GET.get('previous', request.META.get('HTTP_REFERER', '/'))) folder = get_object_or_404(Folder, pk=folder_id) try: Permission.objects.check_permissions(request.user, [PERMISSION_FOLDER_VIEW]) except PermissionDenied: AccessEntry.objects.check_access(PERMISSION_FOLDER_VIEW, request.user, folder) if request.method == 'POST': form = FolderExportMetadataForm(request.POST) if form.is_valid(): folder_documents = list(folder.documents.all()) metadata_dict = {} for doc in folder_documents: docs_metadata = DocumentMetadata.objects.filter(document=doc) docs_metadata_dict = {} for doc_metadata in docs_metadata: docs_metadata_dict[unicode( doc_metadata.metadata_type.name)] = unicode( doc_metadata.value) metadata_dict[doc.filename] = docs_metadata_dict csv_file_content = tempfile.TemporaryFile() csv_file_content.write(csv_file.generate_csv_str(metadata_dict)) csv_file_content.seek(0) csv_file_to_upload = SimpleUploadedFile( name=unicode(form.cleaned_data['csv_filename']), content=csv_file_content.read(), content_type='text/csv') return serve_file(request, csv_file_to_upload, save_as=u'"%s"' % form.cleaned_data['csv_filename'], content_type='text/csv') else: form = FolderExportMetadataForm() context = { 'form': form, 'title': _(u'Download folders metadata for ') + folder.title, 'submit_label': _(u'Download'), 'previous': previous, 'cancel_label': _(u'Return'), #'disable_auto_focus': True, } return render_to_response('generic_form.html', context, context_instance=RequestContext(request))
def download(request, id): uploaded_file = get_object_or_404(UploadedFile, pk=id) #Modificando o contador de downloads uploaded_file.downloads += 1 uploaded_file.save() filename = uploaded_file.file.name return serve_file(request, uploaded_file.file, save_as=True, content_type=get_mime_type(filename))
def download_handler_dataset_file(request, project_name, dataset_title,filename): """offer file for download based on filename and dataset""" dataset = FileSystemDataset.objects.get(comicsite__short_name=project_name,title=dataset_title) filefolder = dataset.get_full_folder_path() filepath = os.path.join(filefolder,filename) f = open(filepath, 'r') file = File(f) # create django file object return serve_file(request, file, save_as=True)
def download_handler(request, id): u""" Загрузка ключевого файла на носитель авторизованного пользователя """ upload = get_object_or_404(Key, pk=id) # get real name filename = upload.attach.name.rsplit('/')[-1] # get upload name filename = filename[LEN_SALT:] return serve_file(request, upload.attach, None, filename)
def get(self, request, content_type, pk): type = ContentType.objects.get(pk=content_type) type_class = type.model_class() try: file = type_class.objects.get(pk=pk) except type_class.DoesNotExist: return HttpResponseNotFound() if file.author == request.user or request.user.is_staff: file_name = os.path.basename(file.file.name) return serve_file(request, file.file, save_as=file_name) return HttpResponseForbidden()
def download(request,id): f= get_object_or_404(Objeto, pk=id) gruposobj = f.repositorio.grupos.all() gruposu = request.user.groups.all() puededescargar=False for go in gruposobj: for gu in gruposu: if go == gu: puededescargar=True if request.user.is_authenticated(): if puededescargar: return serve_file(request, f.archivo, save_as=f.espec_lom.lc1_titulo) elif f.repositorio.publico & f.publicado: return serve_file(request, f.archivo, save_as=f.espec_lom.lc1_titulo) else: return HttpResponseRedirect('/') elif f.repositorio.publico & f.publicado: return serve_file(request, f.archivo, save_as=f.espec_lom.lc1_titulo) else: return HttpResponseRedirect('/')
def document_download(request, document_id): check_permissions(request.user, "documents", [PERMISSION_DOCUMENT_DOWNLOAD]) document = get_object_or_404(Document, pk=document_id) try: # Test permissions and trigger exception document.open() return serve_file(request, document.file, save_as="%s" % document.get_fullname()) except Exception, e: messages.error(request, e) return HttpResponseRedirect(request.META["HTTP_REFERER"])
def get(self, request, *args, **kwargs): file = None fcode = kwargs["fcode"] match_patent = Patent.objects.filter(Q(apply_code=fcode)|Q(authorize_code=fcode)) if match_patent and len(match_patent)==1: patent = match_patent[0] if fcode == patent.apply_code: file = patent.apply_file elif fcode == patent.authorize_code: file = patent.authorize_file return serve_file(request, file, save_as=False)
def get(self, request, *args, **kwargs): file = None fcode = kwargs["fcode"] match_scr = Software.objects.filter(Q(apply_code=fcode)|Q(authorize_code=fcode)) if match_scr and len(match_scr)==1: scr = match_scr[0] if fcode == scr.apply_code: file = scr.apply_file elif fcode == scr.authorize_code: file = scr.authorize_file return serve_file(request, file, save_as=False)
def document_download(request, document_id): check_permissions(request.user, 'documents', [PERMISSION_DOCUMENT_DOWNLOAD]) document = get_object_or_404(Document, pk=document_id) try: #Test permissions and trigger exception document.open() return serve_file(request, document.file, save_as='%s' % document.get_fullname()) except Exception, e: messages.error(request, e) return HttpResponseRedirect(request.META['HTTP_REFERER'])
def download(request,id): f= get_object_or_404(Objeto, pk=id) gruposobj = f.repositorio.grupos.all() gruposu = request.user.groups.all() puededescargar=False for go in gruposobj: for gu in gruposu: if go == gu: puededescargar=True if request.user.is_authenticated(): if puededescargar: return serve_file(request, f.archivo, save_as=opc.set_download_filename(f.espec_lom.lc1_titulo)) elif f.repositorio.publico & f.publicado: return serve_file(request, f.archivo, save_as=opc.set_download_filename(f.espec_lom.lc1_titulo)) else: return HttpResponseRedirect('/') elif f.repositorio.publico & f.publicado: return serve_file(request, f.archivo, save_as=opc.set_download_filename(f.espec_lom.lc1_titulo)) else: return HttpResponseRedirect('/')
def get_document_image(request, document_id, size=PREVIEW_SIZE, quality=QUALITY_DEFAULT): check_permissions(request.user, 'documents', [PERMISSION_DOCUMENT_VIEW]) document = get_object_or_404(Document, pk=document_id) page = int(request.GET.get('page', 1)) transformation_list = [] try: #Catch invalid or non existing pages document_page = DocumentPage.objects.get(document=document, page_number=page) for page_transformation in document_page.documentpagetransformation_set.all(): try: if page_transformation.transformation in TRANFORMATION_CHOICES: output = TRANFORMATION_CHOICES[page_transformation.transformation] % eval(page_transformation.arguments) transformation_list.append(output) except Exception, e: if request.user.is_staff: messages.warning(request, _(u'Error for transformation %(transformation)s:, %(error)s') % {'transformation':page_transformation.get_transformation_display(), 'error':e}) else: pass except ObjectDoesNotExist: pass tranformation_string = ' '.join(transformation_list) try: filepath = in_image_cache(document.checksum, size=size, quality=quality, extra_options=tranformation_string, page=page-1) if filepath: return serve_file(request, File(file=open(filepath, 'r')), content_type='image/jpeg') #Save to a temporary location filepath = document_save_to_temp_dir(document, filename=document.checksum) output_file = convert(filepath, size=size, format='jpg', quality=quality, extra_options=tranformation_string, page=page-1) return serve_file(request, File(file=open(output_file, 'r')), content_type='image/jpeg') except UnkownConvertError, e: if request.user.is_staff or request.user.is_superuser: messages.error(request, e) if size == THUMBNAIL_SIZE: return serve_file(request, File(file=open('%simages/picture_error.png' % settings.MEDIA_ROOT, 'r'))) else: return serve_file(request, File(file=open('%simages/1297211435_error.png' % settings.MEDIA_ROOT, 'r')))
def get_document_image(request, document_id, size=PREVIEW_SIZE, quality=QUALITY_DEFAULT): check_permissions(request.user, 'documents', [PERMISSION_DOCUMENT_VIEW]) document = get_object_or_404(Document, pk=document_id) page = int(request.GET.get('page', 1)) transformation_list = [] try: #Catch invalid or non existing pages document_page = DocumentPage.objects.get(document=document, page_number=page) for page_transformation in document_page.documentpagetransformation_set.all(): try: if page_transformation.transformation in TRANFORMATION_CHOICES: output = TRANFORMATION_CHOICES[page_transformation.transformation] % eval(page_transformation.arguments) transformation_list.append(output) except Exception, e: if request.user.is_staff: messages.warning(request, _(u'Error for transformation %(transformation)s:, %(error)s') % {'transformation':page_transformation.get_transformation_display(), 'error':e}) else: pass except ObjectDoesNotExist: pass tranformation_string = ' '.join(transformation_list) try: filepath = in_image_cache(document.checksum, size=size, quality=quality, extra_options=tranformation_string, page=page-1) if filepath: return serve_file(request, File(file=open(filepath, 'r')), content_type='image/jpeg') #Save to a temporary location filepath = document_save_to_temp_dir(document, filename=document.checksum) output_file = convert(filepath, size=size, format='jpg', quality=quality, extra_options=tranformation_string, page=page-1) return serve_file(request, File(file=open(output_file, 'r')), content_type='image/jpeg') except UnkownConvertError, e: if request.user.is_staff or request.user.is_superuser: messages.error(request, e) if size == THUMBNAIL_SIZE: return serve_file(request, File(file=open('%simages/%s' % (settings.MEDIA_ROOT, PICTURE_ERROR_SMALL), 'r'))) else: return serve_file(request, File(file=open('%simages/%s' % (settings.MEDIA_ROOT, PICTURE_ERROR_MEDIUM), 'r')))
def downloadEdit(request, id): codigo_espec_archivo=int(id.split('.')[0].split('_')[1])#toma el id (nombre del archivo) y toma la parte que corresponde al pk del espec del archivo f= get_object_or_404(Objeto, espec_lom=codigo_espec_archivo) gruposobj = f.repositorio.grupos.all() gruposu = request.user.groups.all() puededescargar=False for go in gruposobj: for gu in gruposu: if go == gu: puededescargar=True if request.user.is_authenticated(): if puededescargar: return serve_file(request, f.archivo, save_as=opc.set_download_filename(f.espec_lom.lc1_titulo)) elif f.repositorio.publico & f.publicado: return serve_file(request, f.archivo, save_as=opc.set_download_filename(f.espec_lom.lc1_titulo)) else: return HttpResponseRedirect('/') elif f.repositorio.publico & f.publicado: return serve_file(request, f.archivo, save_as=opc.set_download_filename(f.espec_lom.lc1_titulo)) else: return HttpResponseRedirect('/')
def admin_download_entries(request, compo): party = get_party(request) try: try: compo = Competition.objects.get(slug=compo, party=party) except Competition.DoesNotExist: raise InvalidCompetition() except InvalidCompetition: messages.add_message(request, messages.ERROR, "Invalid competition") return HttpResponseRedirect(reverse("compo.views.index", args=[request.party])) if request.user.has_perm("entry.admin") or request.user.has_perm("compo.admin"): limit = request.GET.get("limit", None) if not limit: return render_to_response( "compo_admin_download_entries.html", {"compo": compo}, context_instance=RequestContext(request) ) else: if limit == "all": entries = compo.get_entries().filter(hidden=False) elif limit == "juryed": entries = compo.get_entries().filter(hidden=False).filter(~Q(qualification=Qualification.Waiting)) elif limit == "qualified": entries = compo.get_entries().filter(hidden=False).filter(qualification=Qualification.Qualified) elif limit == "publish": entries = ( compo.get_entries() .filter(hidden=False) .filter(~Q(qualification=Qualification.Waiting)) .filter(~Q(qualification=Qualification.Disqualified)) ) packfile = tempfile.NamedTemporaryFile(delete=False) pack = zipfile.ZipFile(packfile.name, "w", zipfile.ZIP_DEFLATED) for entry in entries: version = entry.get_latest_version() if version and version.is_file: lfile = get_entry_file(version.data) pack.write(lfile.name, entry.get_publish_filename()) os.unlink(lfile.name) else: pack.writestr(entry.get_publish_filename(), "") pack.close() dfile = django.core.files.File(packfile) return serve_file( request, dfile, None, "%s_entries_%s.zip" % (compo.slug, limit), "application/octet-stream" ) return HttpResponseNotFound()
def downloadEdit(request, id): codigo_espec_archivo=int(id.split('.')[0].split('_')[1])#toma el id (nombre del archivo) y toma la parte que corresponde al pk del espec del archivo #f=Objeto.objects.get(archivo=miarchivo.file) f= get_object_or_404(Objeto, espec_lom=codigo_espec_archivo) gruposobj = f.repositorio.grupos.all() gruposu = request.user.groups.all() puededescargar=False for go in gruposobj: for gu in gruposu: if go == gu: puededescargar=True if request.user.is_authenticated(): if puededescargar: return serve_file(request, f.archivo, save_as=f.espec_lom.lc1_titulo) elif f.repositorio.publico & f.publicado: return serve_file(request, f.archivo, save_as=f.espec_lom.lc1_titulo) else: return HttpResponseRedirect('/') elif f.repositorio.publico & f.publicado: return serve_file(request, f.archivo, save_as=f.espec_lom.lc1_titulo) else: return HttpResponseRedirect('/')
def document_signature_download(request, document_pk): check_permissions(request.user, [PERMISSION_SIGNATURE_DOWNLOAD]) document = get_object_or_404(Document, pk=document_pk) try: if document.has_detached_signature(): signature = document.detached_signature() return serve_file(request, signature, save_as=u'"%s.sig"' % document.filename, content_type=u'application/octet-stream') except Exception, e: messages.error(request, e) return HttpResponseRedirect(request.META['HTTP_REFERER'])
def download(request,entryid): entry = get_object_or_404(Entry,id=entryid) if entry.compo.entries_public or request.user.has_perm("entry.admin") or request.user.has_perm("compo.admin"): version = entry.get_latest_version() if version and version.data: return serve_file(request,version.data,None,entry.get_publish_filename()) return HttpResponseNotFound() # response = HttpResponse(mimetype="application/octet-stream") # response['Content-Disposition']="filename=%s" % entry.get_publish_filename() # return response else: return HttpResponseNotFound()
def get(self, request, *args, **kwargs): fcode = kwargs["fcode"] file = None for ext in self.ext_list: filename = self.root_dir + self.base_dir + fcode + "." + ext if os.path.exists(filename): file = File(None, filename) file.open('r') print "OK: %s" % filename break else: print "Failed: %s" % filename if not file: raise Http404 return serve_file(request, file, save_as=False)
def get(self, request, id): try: id = int(id) query = Q(active=True, end_date__gte=datetime.datetime.now(), start_date__lte=datetime.datetime.now()) active_assets = Asset.objects.filter(query).order_by( 'changed_time') lst = [] for i in active_assets: lst.append(i.id) if id in lst: upload = get_object_or_404(Asset, pk=id) return serve_file(request, upload.source, save_as=True) except Exception as p: print(p) return JsonResponse({'success': False})
def download(request, **kwargs):#id object = PIA.objects.get(id=kwargs['pk']) if object.project.organization != Profile.objects.get(user=request.user).organization: object.deny_if_not_owner(request.user) RI = [] ri = RiesgoInherente.objects.filter(PIA=kwargs['pk']) if ri: for r in ri: RI.append({'Family':"essential",'Thread':str(r.risk.thread), 'likely':r.probability, 'A': r.disModImpact/100, 'I':r.integModImpact/100, 'C': r.confModImpact/100, 'Auth':r.noRepInhRisk/100}) tsv = TSV(kwargs['pk']).file(RI) result_obj,created = Results.objects.update_or_create(PIA = PIA.objects.get(id=kwargs['pk']), defaults={'tsv': tsv}) return serve_file(request, result_obj.tsv, save_as="tsv_pia"+result_obj.date.strftime('%m/%d/%Y-%H%M%S'))
def document_signature_download(request, document_pk): document = get_object_or_404(Document, pk=document_pk) try: Permission.objects.check_permissions(request.user, [PERMISSION_SIGNATURE_DOWNLOAD]) except PermissionDenied: AccessEntry.objects.check_access(PERMISSION_SIGNATURE_DOWNLOAD, request.user, document) try: if DocumentVersionSignature.objects.has_detached_signature(document): signature = DocumentVersionSignature.objects.detached_signature( document) return serve_file(request, signature, save_as=u'"%s.sig"' % document.filename, content_type=u'application/octet-stream') except Exception, e: messages.error(request, e) return HttpResponseRedirect(request.META['HTTP_REFERER'])
def get(self, request, pk=None, max_width=None, max_height=None): # find the blobfield/imagefield log = logging.getLogger(__name__) instance = get_object_or_404(self.container, pk=pk) if not self.image_field: for field in self.container._meta.fields: if isinstance(field, ImageField): self.image_field = field.name self.image_field_type = type(field) break if not self.image_field: raise Exception('No ImageField found') if hasattr(instance, 'views'): self.container.objects.filter(pk=pk).update(views=F('views')+1) log.debug('image view: %s Referer: %s'%(instance, request.META.get('HTTP_REFERER', ''))) field_data = getattr(instance, self.image_field) if self.image_field_type == ImageField: return serve_file(request, field_data) elif self.image_field_type == CharField: return HttpResponseRedirect(field_data) else: raise Exception('Unsupported Image Field')
def image(request, image_id, width=None, height=None): image = get_object_or_404(ImageModel, pk=image_id) width = int(width) height = int(height) if width or height: img = images.Image(blob_key=image.file.file.blobstore_info._BlobInfo__key) if height: img.resize(width=int(width),height=int(height)) else: img.resize(width=int(width),height=int(width)) img.im_feeling_lucky() img_out = img.execute_transforms(output_encoding=images.JPEG) response = HttpResponse(img_out) response['Content-Type'] = "image/JPEG" response['Cache-Control'] = "max-age=36000" return response else: return serve_file(request, image.file)
def download_handler(request, pk): upload = get_object_or_404(IMGSource, pk=pk) return serve_file(request, upload.file, save_as=True)
if filepath: return serve_file(request, File(file=open(filepath, 'r')), content_type='image/jpeg') #Save to a temporary location filepath = document_save_to_temp_dir(document, filename=document.checksum) output_file = convert(filepath, size=size, format='jpg', quality=quality, extra_options=tranformation_string, page=page-1) return serve_file(request, File(file=open(output_file, 'r')), content_type='image/jpeg') except UnkownConvertError, e: if request.user.is_staff or request.user.is_superuser: messages.error(request, e) if size == THUMBNAIL_SIZE: return serve_file(request, File(file=open('%simages/%s' % (settings.MEDIA_ROOT, PICTURE_ERROR_SMALL), 'r'))) else: return serve_file(request, File(file=open('%simages/%s' % (settings.MEDIA_ROOT, PICTURE_ERROR_MEDIUM), 'r'))) except UnknownFormat: if size == THUMBNAIL_SIZE: return serve_file(request, File(file=open('%simages/%s' % (settings.MEDIA_ROOT, PICTURE_UNKNOWN_SMALL), 'r'))) else: return serve_file(request, File(file=open('%simages/%s' % (settings.MEDIA_ROOT, PICTURE_UNKNOWN_MEDIUM), 'r'))) except Exception, e: if request.user.is_staff or request.user.is_superuser: messages.error(request, e) if size == THUMBNAIL_SIZE: return serve_file(request, File(file=open('%simages/%s' % (settings.MEDIA_ROOT, PICTURE_ERROR_SMALL), 'r'))) else: return serve_file(request, File(file=open('%simages/%s' % (settings.MEDIA_ROOT, PICTURE_ERROR_MEDIUM), 'r'))) def document_download(request, document_id): check_permissions(request.user, 'documents', [PERMISSION_DOCUMENT_DOWNLOAD]) document = get_object_or_404(Document, pk=document_id)
def download_handler(request, file): uploads = UploadModel.objects.filter(file=file) return serve_file(request, uploads[0].file, save_as=True)
def download_handler(request, pk): upload = get_object_or_404(UploadModel, pk=pk) return serve_file(request, upload.file)
def document_download(request, document_id=None, document_id_list=None, document_version_pk=None): previous = request.POST.get( 'previous', request.GET.get( 'previous', request.META.get('HTTP_REFERER', reverse(settings.LOGIN_REDIRECT_URL)))) if document_id: documents = Document.objects.filter(pk=document_id) elif document_id_list: documents = Document.objects.filter(pk__in=document_id_list) elif document_version_pk: documents = Document.objects.filter(pk=get_object_or_404( DocumentVersion, pk=document_version_pk).document.pk) try: Permission.check_permissions(request.user, (permission_document_download, )) except PermissionDenied: documents = AccessControlList.objects.filter_by_access( permission_document_download, request.user, documents) if not documents: messages.error(request, _('Must provide at least one document or version.')) return HttpResponseRedirect( request.META.get('HTTP_REFERER', reverse(settings.LOGIN_REDIRECT_URL))) if document_version_pk: queryset = DocumentVersion.objects.filter(pk=document_version_pk) else: queryset = DocumentVersion.objects.filter( pk__in=[document.latest_version.pk for document in documents]) subtemplates_list = [] subtemplates_list.append({ 'name': 'appearance/generic_list_subtemplate.html', 'context': { 'title': _('Documents to be downloaded'), 'object_list': queryset, 'hide_link': True, 'hide_object': True, 'hide_links': True, 'scrollable_content': True, 'scrollable_content_height': '200px', 'extra_columns': ( { 'name': _('Document'), 'attribute': 'document' }, { 'name': _('Date and time'), 'attribute': 'timestamp' }, { 'name': _('MIME type'), 'attribute': 'mimetype' }, { 'name': _('Encoding'), 'attribute': 'encoding' }, ), } }) if request.method == 'POST': form = DocumentDownloadForm(request.POST, queryset=queryset) if form.is_valid(): if form.cleaned_data['compressed'] or queryset.count() > 1: try: compressed_file = CompressedFile() for document_version in queryset: descriptor = document_version.open() compressed_file.add_file( descriptor, arcname=document_version.document.label) descriptor.close() compressed_file.close() return serve_file(request, compressed_file.as_file( form.cleaned_data['zip_filename']), save_as='"%s"' % form.cleaned_data['zip_filename'], content_type='application/zip') except Exception as exception: if settings.DEBUG: raise else: messages.error(request, exception) return HttpResponseRedirect( request.META['HTTP_REFERER']) else: try: # Test permissions and trigger exception fd = queryset.first().open() fd.close() return serve_file(request, queryset.first().file, save_as='"%s"' % queryset.first().document.label, content_type=queryset.first().mimetype if queryset.first().mimetype else 'application/octet-stream') except Exception as exception: if settings.DEBUG: raise else: messages.error(request, exception) return HttpResponseRedirect( request.META['HTTP_REFERER']) else: form = DocumentDownloadForm(queryset=queryset) context = { 'form': form, 'previous': previous, 'submit_label': _('Download'), 'subtemplates_list': subtemplates_list, 'title': _('Download documents'), } if queryset.count() == 1: context['object'] = queryset.first().document return render_to_response('appearance/generic_form.html', context, context_instance=RequestContext(request))
def video_get(request, video, mime): _video = get_object_or_404(models.VideoData, video=video, mimetype=mime) return serve_file(request, _video.data, content_type='video/%s'%_video.mimetype)
def download(request, pk): upload = get_object_or_404(UploadModel, pk=pk) return serve_file(request, upload.file, save_as=False)
def download_handler(request, pk): file = UploadModel.objects.get( id=pk) return serve_file(request, file.file)
def downloadExperimentScriptFile(request,exp_id): exp = Experiment.objects.get(pk = exp_id) return serve_file(request, exp.scriptFile)
def get_avatar(request, **kw): profile = get_object_or_404(Profile, user__exact=ZI(kw.get('id'))) if profile.avatar: return serve_file(request, profile.avatar) else: return HttpResponseRedirect('/static/img/anon.png')
def descargarPot(request): if request.user.is_authenticated(): nombre = 'siinst.exe' ruta = settings.EXE_ROOT+'\\'+nombre return serve_file(request, ruta, save_as = nombre)