Exemplo n.º 1
0
 def __init__(self, filelike, start, end, blksize = 131072):
     """
     Call our parent's initialize. Then set our start/end/curr pointers and
     seek the file to that position.
     """
     if start > end:
         raise NameError("request end must be greater or equal to start. Start: %d, end: %d" % (start, end))
     
     FileWrapper.__init__(self, filelike, blksize)
     self.start = start
     self.curr = start
     self.end = end
     self.filelike.seek(self.start, 0)
Exemplo n.º 2
0
 def __init__(self, item, *args, **kwargs):
     self._item = item
     self._counter = 0
     self._stale = 0
     self._throttle = kwargs.get("throttle", 100)
     self._stale_limit = kwargs.get("stale_limit", 10000)
     return FileWrapper.__init__(self, *args, **kwargs)
Exemplo n.º 3
0
def downloadHardinfo(request):
    try:
        (fd, pipe) = tempfile.mkstemp()

        file_name2 = ctypes.create_string_buffer(4096)
        file_name2.value = pipe
        LIBMCOSLBASER.create_host_info_file(file_name2)

        f = open(pipe)
        os.remove(pipe)
        response = HttpResponse(FileWrapper(f), content_type='text/plain')
        response['Content-Disposition'] = 'attachment; filename=hardinfo'
        return response
    except Exception as e:
        logger.error(traceback.format_exc())
        return HttpResponse('')
Exemplo n.º 4
0
def download_resume(request, volunteer_id):
    user = request.user
    if int(user.volunteer.id) == int(volunteer_id):
        if request.method == 'POST':
            basename = get_volunteer_resume_file_url(volunteer_id)
            if basename:
                filename = settings.MEDIA_ROOT + basename
                wrapper = FileWrapper(file(filename))
                response = HttpResponse(wrapper)
                response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(filename)
                response['Content-Length'] = os.path.getsize(filename)
                return response
            else:
                raise Http404
    else:
        return HttpResponse(status=403)
Exemplo n.º 5
0
    def render_to_response(self, context, **response_kwargs):
        object = context['object']

        if not object.period_start or object.pub_state == 'draft':
            return HttpResponseNotFound(
                _('The event is private or does not have start time.'))
        cal = generate_ical(object)
        file = io.BytesIO(cal.to_ical())
        # テストの際に、closeされてしまうため
        # HttpResponseの代わりにStreamingHttpResponseを使っている
        # http://stackoverflow.com/questions/19359451/django-test-file-download-valueerror-i-o-operation-on-closed-file
        response = StreamingHttpResponse(FileWrapper(file),
                                         content_type=self.MIMETYPE)
        response['Content-Disposition'] = 'attachment; filename={}.ics'.format(
            object.pk)
        return response
Exemplo n.º 6
0
def get_file(request):
    "Return a response with the content of the file mentioned in ?path=fname"
    path = request.GET.get("path")
    filename = request.GET.get("filename", path)

    #     print "path: ",path
    #     print "filename: ",filename

    if not os.path.exists(path):
        return HttpResponseNotFound('Path not found: %s' % path)

    response = HttpResponse(FileWrapper(open(path)),
                            content_type=mimetypes.guess_type(path)[0])
    response['Content-Length'] = os.path.getsize(path)
    response['Content-Disposition'] = 'attachment; filename=%s' % filename
    return response
Exemplo n.º 7
0
def android_download(request):
    args = {}
    try:
        from django.core.servers.basehttp import FileWrapper
        from pinloveweb.settings import STATIC_ROOT
        file_name = 'pinlove_android_app.apk'
        response = HttpResponse(
            FileWrapper(file(('%s/download/%s' % (STATIC_ROOT, file_name)))),
            content_type='application/vnd.android.package-archive')
        response['Content-Disposition'] = 'attachment; filename=%s' % (
            file_name)
        return response
    except Exception as e:
        logger.exception('检查是否有新未读消息,出错')
        args = {'result': 'error', 'error_message': e.message}
        return render(request, 'error.html', args)
Exemplo n.º 8
0
def get_file(request):

    import os, tempfile, zipfile
    from django.core.servers.basehttp import FileWrapper
    from django.conf import settings
    from django.http import HttpResponse
    import mimetypes

    filename = "getscript/result_script.txt"
    download_name = "result_script.txt"
    wrapper = FileWrapper(open(filename))
    content_type = mimetypes.guess_type(filename)[0]
    response = HttpResponse(wrapper, content_type=content_type)
    response['Content-Length'] = os.path.getsize(filename)
    response['Content-Disposition'] = "attachment; filename=%s" % download_name
    return response
Exemplo n.º 9
0
    def download(self, request, pk):
        from django.core.servers.basehttp import FileWrapper
        import mimetypes
        try:
            entity = Archivo.objects.get(id=pk)
        except Archivo.DoesNotExist:
            return ""

        absPath = str(entity.ruta)
        content_type = entity.tipo
        archivo = FileWrapper(
            open(os.path.join(settings.MEDIA_ROOT, absPath), 'rb'))
        response = HttpResponse(archivo, content_type=content_type)
        response['Content-Disposition'] = 'attachment; filename="{0}"'.format(
            entity.nombre)
        return response
Exemplo n.º 10
0
def downloadFile(request):
    priority = str(request.GET.get('priority'))
    if priority == "private":
        username = request.GET.get('username')
        path = settings.FILEPATH + "/private/" + username + "/"
    else:
        path = settings.FILEPATH + "/share/"
    filename = str(request.GET.get('filename'))
    filename = urllib.unquote(filename)
    tmpname = filename
    filename = path + filename
    wrapper = FileWrapper(file(filename))
    response = HttpResponse(wrapper, content_type='text/plain')
    response['Content-Disposition'] = 'attachment; filename=%s' % tmpname
    response['Content-Length'] = os.path.getsize(filename)
    return response
    def get(self, request):
        file_name = request.query_params.get('file_name')
        if file_name:
            full_path = os.path.join('/tmp/tw_campaign_excels', file_name)
            if os.path.isfile(full_path):
                excel_file = open(full_path, 'rb')
                response = HttpResponse(
                    FileWrapper(excel_file),
                    content_type=
                    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                )
                response[
                    'Content-Disposition'] = 'attachment; filename="%s"' % file_name
                return response

        raise Http404
Exemplo n.º 12
0
def download(request, project_id):
    p = get_object_or_404(Project, pk=project_id)
    if p.filename:
        dir = 'projects/' + request.user.username
        filename = MEDIA_ROOT + '/' + str(p.filename)
        if os.path.exists(filename):
            proj_file = file(filename, 'rb')
            from django.core.servers.basehttp import FileWrapper
            response = HttpResponse(FileWrapper(proj_file),
                                    content_type='application/octet-stream')
            response['Content-Length'] = os.path.getsize(filename)
            response[
                'Content-Disposition'] = 'attachment; filename=' + p.projectname + strftime(
                    ' %Y-%m-%d %H%M%S') + '.proj'
            return response
    return HttpResponse('Sorry, file is not available.')
Exemplo n.º 13
0
def download_project_file(request, project_id=0, server_idx=0):
    if request.GET:
        file_path = request.GET.get('file_path')
        file_name = request.GET.get('file_name')
        project = Project.objects.get(pk=project_id)
        local_path = get_file_from_ftp(file_path=file_path,
                                       project=project,
                                       server_idx=server_idx)
        if local_path:
            wrapper = FileWrapper(file(local_path), blksize=1048576)
            response = HttpResponse(wrapper, content_type='text/plain')
            response['Content-Length'] = os.path.getsize(local_path)
            response[
                'Content-Disposition'] = 'attachment; filename=' + file_name
            return response
    return HttpResponse('')
Exemplo n.º 14
0
def send_file(request, id):
    """
    https://www.djangosnippets.org/snippets/365/
    Send a file through Django without loading the whole file into
    memory at once. The FileWrapper will turn the file object into an
    iterator for chunks of 8KB.
    """
    requested_file = get_object_or_404(UploadedFile, id=id)
    filename = str(requested_file.supporting_document.name)
    wrapper = FileWrapper(open(filename, 'rb'))
    content_type = mimetypes.MimeTypes().guess_type(filename)[0]
    response = HttpResponse(wrapper, content_type=content_type)
    response['Content-Length'] = os.path.getsize(filename)
    response['Content-Disposition'] = 'attachment; filename="{}"'.format(
        os.path.basename(filename))
    return response
Exemplo n.º 15
0
def get_swi_product_zip(request, timeslot):
    ts = dt.datetime.strptime(timeslot, '%Y%m%d%H%M')
    area = ss.Area.objects.get(name='.*')
    settings = ss.Package.objects.get(code_class__className='SWIDistributor')
    pack = SWIDistributor(settings, ts, area, logger=logger)
    the_zip = pack.run_main()
    pack.clean_up()
    if the_zip is not None:
        response = HttpResponse(FileWrapper(open(the_zip)),
                                content_type='application/zip')
        response['Content-Disposition'] = 'attachment; filename=%s' \
                                          % os.path.basename(the_zip)
        result = response
    else:
        raise Http404
    return result
Exemplo n.º 16
0
    def GET(self, request, spot_id, image_id):
        img = SpotImage.objects.get(pk=image_id)
        spot = img.spot

        if int(spot.pk) != int(spot_id):
            raise RESTException("Image Spot ID doesn't match spot id in url",
                                404)

        response = HttpResponse(FileWrapper(img.image))
        response["ETag"] = img.etag

        # 7 day timeout?
        response['Expires'] = http_date(time.time() + 60 * 60 * 24 * 7)
        response["Content-length"] = img.image.size
        response["Content-type"] = img.content_type
        return response
Exemplo n.º 17
0
    def toHttpResponse(self):
        if self.use_transfer:
            response = TransferHttpResponse(self.filename,
                                            content_type=self.content_type)
        else:
            response = StreamingHttpResponse(FileWrapper(
                open(self.filename), CHUNK_SIZE),
                                             content_type=self.content_type)

        response['Content-Length'] = os.path.getsize(self.filename)
        response['Content-Disposition'] = self.content_disposition
        if self.transfer_encoding is not None:
            response['Transfer-Encoding'] = self.transfer_encoding
        for k, v in self.extras.items():
            response[k] = v
        return response
Exemplo n.º 18
0
def pdf_dl_view(request, pk):
    invoice = get_object_or_404(Invoice, pk=pk)

    if invoice.is_pdf_generated():
        # Serving file is not Django's job
        # If this need an optimisation, see X-sendfile mod (Apache/nginx)
        wrapper = FileWrapper(file(invoice.pdf_path()))
        response = HttpResponse(wrapper, content_type='text/plain')
        response['Content-Disposition'] = 'attachment; filename="%s"' %\
            invoice.file_name()
        response['Content-Length'] = getsize(invoice.pdf_path())
        return response
    else:
        messages.add_message(request, messages.ERROR,
                             _(u"You have to generate the PDF before!"))
    return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Exemplo n.º 19
0
    def get(self, request, id, format=None):
        """
        to download YAML
        """
        switch = Switch.objects.get(pk=id)

        path = os.path.join(REPO_PATH, str(switch.id) + ".yml")

        try:
            wrapper = FileWrapper(file(path))
        except IOError:
            raise IgniteException(ERR_YML_NOT_FOUND)

        response = HttpResponse(wrapper, content_type='text/plain')
        response['Content-Length'] = os.path.getsize(path)
        return response
Exemplo n.º 20
0
def income(request):
    import os
    import tempfile
    import zipfile
    from django.core.servers.basehttp import FileWrapper
    from django.conf import settings
    import mimetypes
    filename = os.path.abspath(os.path.join(
        os.path.dirname(__file__))) + "/static/mysite/income.csv"
    download_name = "income.csv"
    wrapper = FileWrapper(open(filename))
    content_type = mimetypes.guess_type(filename)[0]
    response = HttpResponse(wrapper, content_type=content_type)
    response['Content-Length'] = os.path.getsize(filename)
    response['Content-Disposition'] = "attachment; filename=%s" % download_name
    return response
Exemplo n.º 21
0
def send_mail_file(request):
    if not validate_key(request):
        raise Http404
    date_id = request.GET.get('id', '')
    date, id = date_id.split('_')
    if id and date:
        mail_obj = get_mail_model(date).objects.get(id=id)
        filename = mail_obj.get_mail_path()
        if not os.path.exists(filename):
            filename = mail_obj.get_mail_path_old()
        if os.path.exists(filename):
            wrapper = FileWrapper(file(filename))
            response = HttpResponse(wrapper, content_type='text/plain')
            response['Content-Length'] = os.path.getsize(filename)
            return response
    return HttpResponse('')
Exemplo n.º 22
0
def item(request, **kwargs):
    check_user_rights(request, 'download', kwargs)

    ddlocation = pyfaf.config.config['dumpdir.cachedirectory']
    if not os.path.exists(ddlocation):
        logging.error("Missing dump location '{0}'".format(ddlocation))

    all_items = None
    if kwargs['dumpdir_name'] == 'all':
        all_items = os.listdir(ddlocation)
    else:
        all_items = kwargs['dumpdir_name'].split(',')

    # Can't be 0
    if len(all_items) == 1:
        item = all_items[0]
        ddpath = os.path.join(ddlocation, os.path.basename(item))

        if not os.path.exists(ddpath) or not os.path.isfile(ddpath):
            return HttpResponse(
                "The requested dump directory '{0}' was not found".format(
                    item),
                status=404)

        ddfw = FileWrapper(file(ddpath))

        response = HttpResponse(ddfw, content_type='application/octet-stream')
        response['Content-length'] = os.path.getsize(ddpath)
        return response
    else:
        response = HttpResponse(content_type='application/octet-stream')
        dwnld_nm = 'fafdds-{0}.tar.gz'.format(datetime.now().isoformat())
        response['Content-Disposition'] = 'attachment; filename=' + dwnld_nm
        tarred = tarfile.open(fileobj=response, mode='w')
        for item in all_items:
            ddpath = os.path.join(ddlocation, os.path.basename(item))

            if not os.path.exists(ddpath) or not os.path.isfile(ddpath):
                return HttpResponse(
                    "The requested dump directory '{0}' was not found".format(
                        item),
                    status=404)

            # arcname -> to remove full path
            tarred.add(ddpath, arcname=item)
        tarred.close()
        return response
    def download_detail(self, request, **kwargs):
        self.is_authenticated(request)
        self.throttle_check(request)

        pk = kwargs.pop('pk', None)
        course = self._meta.queryset.get(pk=pk)

        file_to_download = course.getAbsPath()
        schedule = course.get_default_schedule()
        has_completed_trackers = Tracker.has_completed_trackers(
            course, request.user)
        cohort = Cohort.member_now(course, request.user)
        if cohort:
            if cohort.schedule:
                schedule = cohort.schedule

        # add scheduling XML file
        if schedule or has_completed_trackers:
            file_to_download = settings.COURSE_UPLOAD_DIR + "temp/" + str(
                request.user.id) + "-" + course.filename
            shutil.copy2(course.getAbsPath(), file_to_download)
            zip = zipfile.ZipFile(file_to_download, 'a')
            if schedule:
                zip.writestr(course.shortname + "/schedule.xml",
                             schedule.to_xml_string())
            if has_completed_trackers:
                zip.writestr(course.shortname + "/tracker.xml",
                             Tracker.to_xml_string(course, request.user))
            zip.close()

        wrapper = FileWrapper(file(file_to_download))
        response = HttpResponse(wrapper, content_type='application/zip')
        response['Content-Length'] = os.path.getsize(file_to_download)
        response['Content-Disposition'] = 'attachment; filename="%s"' % (
            course.filename)

        md = CourseDownload()
        md.user = request.user
        md.course = course
        md.course_version = course.version
        md.ip = request.META.get('REMOTE_ADDR', '0.0.0.0')
        md.agent = request.META.get('HTTP_USER_AGENT', 'unknown')
        md.save()

        course_downloaded.send(sender=self, course=course, user=request.user)

        return response
Exemplo n.º 24
0
def pdf(request, database, citation_key, username):
    u"""Retrieves the PDF of a reference.

    :Parameters:
      - `request`: the current HTTP Request object
      - `database`: the name of the RefDB database
      - `citation_key`: the citation key of the reference
      - `username`: the name of the user whose private PDF should be retrieved;
        if the *global* PDF should be retrieved, this is ``None``

    :type request: ``HttpRequest``
    :type database: unicode
    :type citation_key: unicode
    :type username: unicode

    :Returns:
      the HTTP response object

    :rtype: ``HttpResponse``
    """
    # FixMe: Eventually, this function should use something like
    # <http://code.djangoproject.com/ticket/2131>.
    connection = refdb.get_connection(request.user, database)
    try:
        reference = connection.get_references(":CK:=" + citation_key)[0]
    except IndexError:
        raise Http404("Citation key \"%s\" not found." % citation_key)
    utils.fetch(reference, ["global_pdf_available", "pdf_is_private"],
                connection, request.user.id)
    if username:
        user_id = request.user.id
        if username != request.user.username:
            raise PermissionDenied()
        if not reference.pdf_is_private[user_id]:
            raise Http404("You have no private PDF for this reference.")
    else:
        user_id = None
        if not reference.global_pdf_available:
            raise Http404("No public PDF available for this reference.")
    filename = pdf_filepath(database, reference, user_id)
    wrapper = FileWrapper(open(filename, "rb"))
    response = HttpResponse(wrapper, content_type="application/pdf")
    response["Content-Length"] = os.path.getsize(filename)
    response[
        "Content-Disposition"] = "attachment; filename=%s.pdf" % utils.slugify_reference(
            reference)
    return response
Exemplo n.º 25
0
def get_file(request, file_slug=None, file_name=None):
    """
    Sends a file to the browser for download.
        
    :Return: HttpResponse
    """

    if file_slug:
        file_obj = get_object_or_404(File, slug=file_slug)

        if not file_name:
            return HttpResponseRedirect(
                reverse('file',
                        kwargs={
                            'file_slug':
                            file_slug,
                            'file_name':
                            os.path.basename(file_obj.file_upload.name)
                        }))
        elif file_name != os.path.basename(file_obj.file_upload.name):
            raise Http404

        submission = Submission.objects.get(pk=file_obj.submission.pk)

        mimetype, encoding = mimetypes.guess_type(file_name)
        mimetype = mimetype or 'application/force-download'

        response = HttpResponse(FileWrapper(file_obj.file_upload),
                                mimetype=mimetype)

        response['Content-Length'] = file_obj.file_upload.size
        response["Content-Disposition"] = "attachment"
        if encoding:
            response["Content-Encoding"] = encoding

        if submission.password:
            session_slug = request.session.get('bft_auth', '')

            if session_slug in submission.slug:
                return response
            else:
                return HttpResponseRedirect(
                    reverse('files', args=[submission.slug]))
        else:
            return response
    else:
        raise Http404
Exemplo n.º 26
0
def scheduler_target_rgb_image(request, id=0):
    base = posixpath.join("/tmp/fweb/targets", str(id))

    try:
        os.makedirs(base)
    except:
        pass

    rgbname = posixpath.join(base, "rgb.jpg")

    if not posixpath.isfile(rgbname):
        # No cached file
        try:
            target = SchedulerTargets.objects.get(id=id)
            images = Images.objects.raw(
                "select *,get_filter_name(filter) as filter_string from images where keywords->'TARGET UUID'='%s' and q3c_radial_query(ra0, dec0, %s, %s, 2.0) order by channel_id"
                % (target.uuid, target.ra, target.dec))

            files_b, files_v, files_r = [], [], []

            for image in images:
                filename = posixpath.join(settings.BASE, image.filename)
                filename = fix_remote_path(filename, image.channel_id)

                if image.filter_string == 'B':
                    files_b.append(filename)
                if image.filter_string == 'V':
                    files_v.append(filename)
                if image.filter_string == 'R':
                    files_r.append(filename)

            if len(files_b) and len(files_v) and len(files_r):
                print files_b[0], files_v[0], files_r[0]
                coadd_rgb(name_blue=files_b[0],
                          name_green=files_v[0],
                          name_red=files_r[0],
                          out=rgbname)
        except:
            pass

    if not posixpath.isfile(rgbname):
        return HttpResponse("Can't create RGB image for target %s" % str(id))

    response = HttpResponse(FileWrapper(file(rgbname)),
                            content_type='image/jpeg')
    response['Content-Length'] = posixpath.getsize(rgbname)
    return response
Exemplo n.º 27
0
def _create_download_response(request, datafile_id, disposition='attachment'):
    #import ipdb; ipdb.set_trace()
    # Get datafile (and return 404 if absent)
    try:
        datafile = Dataset_File.objects.get(pk=datafile_id)
    except Dataset_File.DoesNotExist:
        return return_response_not_found(request)
    # Check users has access to datafile
    if not has_datafile_download_access(request=request,
                                        dataset_file_id=datafile.id):
        return return_response_error(request)
    # Send an image that can be seen in the browser
    if disposition == 'inline' and datafile.is_image():
        from tardis.tardis_portal.iiif import download_image
        args = (request, datafile.id, 'full', 'full', '0', 'native')
        # Send unconverted image if web-compatible
        if datafile.get_mimetype() in ('image/gif', 'image/jpeg', 'image/png'):
            return download_image(*args)
        # Send converted image
        return download_image(*args, format='png')
    # Send local file
    try:
        # Get file object for datafile
        file_obj = datafile.get_file()
        if not file_obj:
            # If file path doesn't resolve, return not found
            return return_response_not_found(request)
        wrapper = FileWrapper(file_obj, blksize=65535)
        response = StreamingHttpResponse(wrapper,
                                         mimetype=datafile.get_mimetype())
        response['Content-Disposition'] = \
            '%s; filename="%s"' % (disposition, datafile.filename)
        return response
    except IOError:
        # If we can't read the file, return not found
        return return_response_not_found(request)
    except ValueError:  # raised when replica not verified TODO: custom excptn
        redirect = request.META.get('HTTP_REFERER',
                                    'http://%s/' %
                                    request.META.get('HTTP_HOST'))
        message = """The file you are trying to access has not yet been
                     verified. Verification is an automated background process.
                     Please try again later or contact the system
                     administrator if the issue persists."""
        message = ' '.join(message.split())  # removes spaces
        redirect = redirect + '#error:' + message
        return HttpResponseRedirect(redirect)
Exemplo n.º 28
0
def downlolad_attachment(request):
    filedetails = request.GET.get("filedata")
    # print filedetails
    fileinfo = filedetails.split()
    tool = fileinfo[0]
    job_id = fileinfo[1]
    patch_file = fileinfo[2]
    job_dir = JOB_ROOT_PATH + str(job_id) + '/' + tool + '/'
    original_filename = job_dir + patch_file
    # print original_filename
    chunk_size = 8192
    downloadfile = patch_file
    response = StreamingHttpResponse(
        FileWrapper(open(original_filename), chunk_size))

    type, encoding = mimetypes.guess_type(original_filename)
    # print type
    if type is None:
        type = 'application/octet-stream'
    response['Content-Type'] = type
    response['Content-Length'] = str(os.stat(original_filename).st_size)
    if encoding is not None:
        response['Content-Encoding'] = encoding

    # To inspect details for the below code, see http://greenbytes.de/tech/tc2231/
    if u'WebKit' in request.META['HTTP_USER_AGENT']:
        # Safari 3.0 and Chrome 2.0 accepts UTF-8 encoded string directly.
        filename_header = 'filename=%s' % original_filename.encode('utf-8')
    elif u'MSIE' in request.META['HTTP_USER_AGENT']:
        # IE does not support internationalized filename at all.
        # It can only recognize internationalized URL, so we do the trick via routing rules.
        filename_header = ''
    else:
        # For others like Firefox, we follow RFC2231 (encoding extension in HTTP headers).
        filename_header = 'filename*=UTF-8\'\'%s' % urllib.quote(
            original_filename.encode('utf-8'))
    # print filename_header
    response['Content-Disposition'] = 'inline; ' + filename_header
    # response['Content-Disposition'] = 'inline; ' + 'filename=' + downloadfile + "/n/n/"
    # response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(downloadfile)
    response['X-Sendfile'] = smart_str(downloadfile)
    # pprint.pprint(response)str(
    print response['Content-Disposition']
    print response['Content-Type']
    print response['Content-Length']
    # print response['Content-Encoding']
    return response
Exemplo n.º 29
0
 def create_excel_response_with_media(self, submission_type, query_params):
     columns, search_results = self.get_columns_and_search_results(
         query_params, submission_type)
     submission_ids = self.get_submission_ids(query_params)
     file_name, workbook_file = self._create_excel_workbook(
         columns, search_results, submission_type)
     media_folder = self._create_images_folder(submission_ids)
     folder_name = export_media_folder_name(submission_type,
                                            self.project_name)
     file_name_normalized, zip_file = self._archive_images_and_workbook(
         workbook_file, file_name, folder_name, media_folder)
     response = HttpResponse(FileWrapper(zip_file, blksize=8192000),
                             content_type='application/zip')
     response[
         'Content-Disposition'] = 'attachment; filename="%s.zip"' % file_name_normalized
     zip_file.seek(0)
     return response
def index(request):
    # Get the request parameters
    window_size = float(request.POST.get('window_size', '8192'))
    print "window_size=%f" % window_size

    hop_size = float(request.POST.get('hop_size', '8192'))
    print "hop_size=%f" % hop_size

    gain = float(request.POST.get('gain', '64'))
    print "gain=%f" % gain

    max_frequency = float(request.POST.get('max_frequency', '8000'))
    print "max_frequency=%f" % max_frequency

    start = float(request.POST.get('start', '15'))
    print "start=%f" % start

    length = float(request.POST.get('length', '30'))
    print "length=%f" % length

    # The temporary filename to create
    lt = time.localtime(time.time())
    output_filename = "/tmp/orchive_spectrogram_%02d_%02d_%04d_%02d_%02d_%02d.png" % (
        lt[2], lt[1], lt[0], lt[3], lt[4], lt[5])
    print output_filename

    # Generate the file
    #input_filename = "/home/sness/nDEV/venus_orchive/public/assets/recordings/1007/H2/2010/01/01/1/audio.wav"
    #input_filename = "/home/sness/wavfiles/tiny.wav"
    #input_filename = "/home/sness/nDEV/venus_orchive-assets/recordings/1007/H2/2010/01/01/1/audio.wav"
    input_filename = "/home/sness/wavfiles/audio.wav"

    print "Generating file in=%s out=%s" % (input_filename, output_filename)
    command = "/home/sness/marsyas/release/bin/sound2png %s -m neptune -ws %f -hs %f -g %f -mf %f -s %f -l %f %s" % (
        input_filename, window_size, hop_size, gain, max_frequency, start,
        length, output_filename)
    print "command=%s" % command
    a = commands.getoutput(command)
    print a

    # Send the file to the user
    print "Sending file to user"
    sendfile = open(output_filename, "r")
    response = HttpResponse(FileWrapper(sendfile), content_type='image/png')
    response['Content-Disposition'] = 'attachment; filename=file.png'
    return response
Exemplo n.º 31
0
 def next(self):
     try:
         data = FileWrapper.next(self)
         self._counter += len(data)
         if len(data) > 0:
             self._stale = 0
         return data
     except StopIteration:
         if self._counter >= self._item.size_total:
             raise StopIteration
         if self._stale_limit and self._stale >= self._stale_limit:
             raise StopIteration
         start = time.time()
         time.sleep(self._throttle/1000)
         end = time.time()
         self._stale += (end - start)*1000
         return ""
Exemplo n.º 32
0
def list_dir(request, path):
    abspath = os.path.abspath(os.path.join(settings.LIST_DIR_ROOT, path))

    if not path_inside_root(abspath, settings.LIST_DIR_ROOT):
        raise Http404

    if os.path.isfile(abspath):
        mimetype = mimetypes.guess_type(abspath)[0]
        response = HttpResponse(FileWrapper(open(abspath)),
                                content_type=mimetype)
        response['Content-Length'] = os.path.getsize(abspath)
        response['Content-Disposition'] = 'attachment'
        return response
    return render(request, "list_dir/list_base.html", {
        "list": _list_dir(abspath),
        "path": path,
    })
Exemplo n.º 33
0
 def next(self):
     try:
         data = FileWrapper.next(self)
         self._counter += len(data)
         if len(data) > 0:
             self._stale = 0
         return data
     except StopIteration:
         if self._counter >= self._item.size_total:
             raise StopIteration
         if self._stale_limit and self._stale >= self._stale_limit:
             raise StopIteration
         start = time.time()
         time.sleep(self._throttle / 1000)
         end = time.time()
         self._stale += (end - start) * 1000
         return ""
Exemplo n.º 34
0
 def __init__(self, fileName, chunkSize=16*1024, deleteAfter=False):
     self.fileName = fileName
     self.deleteAfter = deleteAfter
     self.fileHandler = open(self.fileName, "rb")
     FileWrapper.__init__(self, self.fileHandler, chunkSize)