Exemple #1
0
    def _sendfile(self, env, start_response, filename):
        from wsgiref.util import FileWrapper
        status = '200 OK'
        _log.debug('SENDING FILE: {}'.format(filename))
        guess = mimetypes.guess_type(filename)[0]
        _log.debug('MIME GUESS: {}'.format(guess))

        if not os.path.exists(filename):
            start_response('404 Not Found', [('Content-Type', 'text/html')])
            return [b'<h1>Not Found</h1>']

        if not guess:
            guess = 'text/plain'

        response_headers = [
            ('Content-type', guess),
        ]
        start_response(status, response_headers)

        return FileWrapper(open(filename, 'r'))
 def get(self, request, id, *args):
     try:
         query = get_object_or_404(DetectedFile, id=id)
         file_path = query.file.path
         document = open(file_path, 'rb')
         response = HttpResponse(FileWrapper(document),
                                 content_type='image/png')
         response[
             'Content-Disposition'] = 'attachment; filename="%s"' % query.file.name
         # print("file path", file.path)
         return response
     except Exception as e:
         error = api_error_handler.PrintException()
         return Response(
             {
                 'data': error,
                 'error': True,
                 'message': 'Something went wrong'
             },
             status=500)
def download_result(request, filename):
    try:
        zipped_output = os.path.join(settings.MEDIA_ROOT,
                                     filename + "-output.zip")
        file_wrapper = FileWrapper(file(zipped_output, 'rb'))
    except:
        return JsonResponse({
            "error": {
                "message": "The specified result could not be found.",
                "code": 404
            }
        })
    file_mimetype = mimetypes.guess_type(zipped_output)
    response = HttpResponse(file_wrapper, content_type=file_mimetype)
    response['X-Sendfile'] = zipped_output
    response['Content-Length'] = os.stat(zipped_output).st_size
    response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(
        zipped_output)
    run_delete_all()
    return response
Exemple #4
0
def exportBasic(request):
    rootpath = "tmp/"

    exportBasicFileName = createfile_singlequery(getBasicRequestFilters(request), rootpath)
    exportBasicFilePath = rootpath + exportBasicFileName

    os.makedirs(exportBasicFilePath[:-4])
    shutil.move(exportBasicFilePath, exportBasicFilePath[:-4])

    shutil.make_archive(exportBasicFilePath[:-4], 'zip', exportBasicFilePath[:-4])

    f = open(settings.BASE_DIR+"/"+exportBasicFilePath[:-4]+".zip", "rb")
    wrapper = FileWrapper(f)

    shutil.rmtree(exportBasicFilePath[:-4])
    os.remove(exportBasicFilePath[:-4] + ".zip")

    response = HttpResponse(wrapper,content_type='text/plain')
    response['Content-Disposition'] = 'attachment; filename="'+exportBasicFileName[:-4]+'.zip'+'"'
    return response
Exemple #5
0
    def toHttpResponse(self):
        if self.download_id.startswith(self.new_id_prefix):
            blob_key = self.download_id
        else:
            # legacy key; remove after all legacy blob downloads have expired
            blob_key = "_default/" + self.identifier
        blob_db = get_blob_db()
        file_obj = blob_db.get(key=blob_key)
        blob_size = blob_db.size(key=blob_key)

        response = StreamingHttpResponse(
            FileWrapper(file_obj, CHUNK_SIZE),
            content_type=self.content_type
        )

        response['Content-Length'] = blob_size
        response['Content-Disposition'] = self.content_disposition
        for k, v in self.extras.items():
            response[k] = v
        return response
Exemple #6
0
def work_download(request, lesson, index, user_id, workfile_id):
    lesson_dict = OrderedDict()
    for unit in lesson_list[int(lesson) - 1][1]:
        for assignment in unit[1]:
            lesson_dict[assignment[2]] = assignment[0]
    workfile = WorkFile.objects.get(id=workfile_id)
    username = User.objects.get(id=user_id).first_name
    reload(sys)
    sys.setdefaultencoding('utf8')
    filename = username + "_" + lesson_dict[int(index)].encode("utf8") + ".sb2"
    download = settings.BASE_DIR + "/static/work/" + str(
        user_id) + "/" + workfile.filename
    wrapper = FileWrapper(file(download, "rb"))
    response = HttpResponse(wrapper, content_type='application/force-download')
    #response = HttpResponse(content_type='application/force-download')
    response['Content-Disposition'] = 'attachment; filename={0}'.format(
        filename.encode('utf8'))
    # It's usually a good idea to set the 'Content-Length' header too.
    # You can also set any other required headers: Cache-Control, etc.
    return response
Exemple #7
0
def stream_video(request, file_name):
    if request.session.get('is_logged_in'):
        print("here")
        range_header = request.META.get('HTTP_RANGE', '').strip()
        range_match = range_re.match(range_header)
        path = "E:\\" + file_name

        if os.path.exists(path):
            size = os.path.getsize(path)
            print(path)
            print(size)
            content_type, encoding = mimetypes.guess_type(path)
            content_type = content_type or 'application/octet-stream'
            print(content_type)
            if range_match:
                print("range_match")
                first_byte, last_byte = range_match.groups()
                first_byte = int(first_byte) if first_byte else 0
                last_byte = int(last_byte) if last_byte else size - 1
                if last_byte >= size:
                    last_byte = size - 1
                length = last_byte - first_byte + 1
                resp = StreamingHttpResponse(RangeFileWrapper(
                    open(path, 'rb'), offset=first_byte, length=length),
                                             status=206,
                                             content_type=content_type)
                resp['Content-Length'] = str(length)
                resp['Content-Range'] = 'bytes %s-%s/%s' % (first_byte,
                                                            last_byte, size)
            else:
                print("not range_match")
                resp = StreamingHttpResponse(FileWrapper(open(path, 'rb')),
                                             content_type=content_type)
                resp['Content-Length'] = str(size)
            resp['Accept-Ranges'] = 'bytes'
            print("at the end")
            return resp
        else:
            raise Http404
    else:
        return redirect("http://127.0.0.1:8000/user/login")
    def get(self, request, *args, **kwargs):
        slug = kwargs.get('slug')
        pk = kwargs.get('pk')
        downloads_qs = ProductFile.objects.filter(pk=pk, product__slug=slug)
        if downloads_qs.count() != 1:
            raise Http404("Download not found")
        download_obj = downloads_qs.first()

        can_download = False
        user_ready = True
        if download_obj.user_required:
            if not request.user.is_authenticated():
                user_ready = False
        purchased_products = Product.objects.none()
        if download_obj.free:
            can_download = True
            user_ready = True
        else:
            purchased_products = ProductPurchase.objects.products_by_request(
                request)
            if download_obj.product in purchased_products:
                can_download = True
        if not can_download or not user_ready:
            messages.error(request,
                           "You do not have access to download this item")
            return redirect(download_obj.get_default_url())

        file_root = settings.PROTECTED_ROOT
        filepath = download_obj.file.path
        final_filepath = os.path.join(file_root, filepath)
        with open(final_filepath, 'rb') as f:
            wrapper = FileWrapper(f)
            mimetype = 'application/force-download'
            gussed_mimetype = guess_type(filepath)[0]
            if gussed_mimetype:
                mimetype = gussed_mimetype
            response = HttpResponse(wrapper, content_type=mimetype)
            response['Content-Disposition'] = "attachment;filename=%s" % (
                download_obj.name)
            response["X-SendFile"] = str(download_obj.name)
            return response
Exemple #9
0
def download_file_from_efs(asset_path, solution_id):
    context = tracer.get_context(request_id=str(uuid4()), log_level="INFO")
    context.start_span(component=__name__)
    try:
        req_data = {"solution_id": solution_id, "file_path": asset_path}
        gateway_download_url = os.path.join(API_GATEWAY_POST_JOB_URI,
                                            "download/")
        data = requests.post(gateway_download_url,
                             stream=True,
                             data=json.dumps(req_data))
        idx = asset_path.rindex("/")
        directory = asset_path[0:idx] if (idx > -1) else ''
        file_name = asset_path[idx +
                               1:len(asset_path)] if (idx > -1) else asset_path
        file_path = MEDIA_ROOT + str(directory)
        if not os.path.exists(file_path):
            os.makedirs(file_path)
        with open(file_path + '/' + file_name, 'wb+') as outfile:
            data.raw.decode_content = True
            shutil.copyfileobj(data.raw, outfile)
            outfile.close()

        # Streaming data to download
        chunk_size = 8192
        file_path = file_path + '/' + file_name
        response = StreamingHttpResponse(
            FileWrapper(open(file_path, 'rb'), chunk_size),
            content_type=mimetypes.guess_type(file_path)[0])
        response['Content-Length'] = os.path.getsize(file_path)
        response['Content-Disposition'] = "attachment; filename=%s" % file_name
        delete_files()
        return response
    except Exception as e:
        context.log(message=str(e), obj={"tb": traceback.format_exc()})
        return JsonResponse({
            "status": "failure",
            "msg": "failed to download file " + str(e),
            "file_path": asset_path
        })
    finally:
        context.end_span()
Exemple #10
0
 def get(self,request,format=None):
     try:
         http_status = status.HTTP_200_OK
         #parse and validate data
         report = None
         data = {
             "start":request.GET.get('start'),
             "end":request.GET.get('end'),
             "banked_start":request.GET.get('banked_start',None),
             "banked_end":request.GET.get('banked_end',None),
             "system":request.GET.get('system'),
             "items": request.GET.get('items', False),
             "region": request.GET.get('region'),
             "district": request.GET.get('district')
         }
         serializer = ReportSerializer(data=data)
         serializer.is_valid(raise_exception=True)
         filename = 'report-{}-{}'.format(str(serializer.validated_data['start']),str(serializer.validated_data['end']))
         # Generate Report
         if serializer.validated_data['items']:
             report = generate_items_csv(systemid_check(serializer.validated_data['system']),
                                         serializer.validated_data['start'],
                                         serializer.validated_data['end'],
                                         serializer.validated_data['banked_start'],
                                         serializer.validated_data['banked_end'])
         else:
             report = generate_trans_csv(systemid_check(serializer.validated_data['system'])
                                         ,serializer.validated_data['start'],
                                         serializer.validated_data['end'],
                                         district = serializer.validated_data['district'])
         if report:
             response = HttpResponse(FileWrapper(report), content_type='text/csv')
             response['Content-Disposition'] = 'attachment; filename={}.csv'.format(filename)
             return response
         else:
             raise serializers.ValidationError('No report was generated.')
     except serializers.ValidationError:
         raise
     except Exception as e:
         traceback.print_exc()
         raise serializers.ValidationError(str(e))
Exemple #11
0
 def cmd(self, request, *args, **kwargs):
     data = self.parse_query(self.request.data or self.request.query_params)
     serializer = self.get_cmd_serializer(data=data)
     if serializer.is_valid():
         cmd = serializer.validated_data
         try:
             # FILE #
             if cmd['cmd'] == 'file':
                 if cmd.get('download'):
                     response = HttpResponse(
                         FileWrapper(cmd['target'].open()),
                         content_type=cmd['target'].mime)
                     response['Content-Disposition'] = (
                         'attachment; filename=%s' % cmd['target'].name)
                     return response
                 else:
                     return redirect(cmd['target'])
             # PING #
             elif cmd['cmd'] == 'ping':
                 response = HttpResponse()
                 response['Connection'] = 'close'
                 return response
             # UPLOAD #
             elif cmd['cmd'] == 'upload':
                 return self.upload(request, *args, **kwargs)
             else:
                 return self.retrieve(request, *args, **kwargs)
         except PermissionError as e:
             return Response({'error': ['errPerm']})
         except PermissionDenied as e:
             return Response({'error': ['errPerm']})
         except FileNotFoundError as e:
             return Response({'error': ['errFileNotFound']})
         except Http404 as e:
             return Response({'error': ['errFileNotFound']})
     else:
         return Response({
             'error':
             self.get_cmd_serializer_errors(serializer),
         })
     return Response({'error': ['errUnknownCmd']})
def download_badge(request, award_id):    
    try:
        award = get_award(award_id)
        version = request.GET.get('v', '2.0')
                     
        # Fetch copy of badge image to tempfile
        temp_filepath, content_type = file_util.fetch_image(award.badge_image.url)

        if content_type == file_util.MIME_TYPE_PNG:
            suffix = 'png'
        else:
            suffix = 'svg'

        baked_filename, ext = os.path.splitext(os.path.basename(award.badge_image.url))
        baked_filename = '%s_baked%s.%s' % (baked_filename, award.id, suffix)
            
        baked_filepath = os.path.join(settings.LOCAL_MEDIA_ROOT, baked_filename)

        assertion_string = json.dumps(get_assertion_json(request, award, version))

        # Bake it
        with open(temp_filepath, 'rb') as src:
            with open(baked_filepath, 'wb') as dst:
                if content_type == file_util.MIME_TYPE_PNG:
                    png_bakery.bake(src, assertion_string, dst)
                else:
                    _bake_svg(src, assertion_string, dst)

        # Delete tempfile
        os.remove(temp_filepath)

        # Return image as attachment
        response_filename = '%s_%s.%s' % (
            award.badge_name.replace(' ', '_'), award.issued_date.isoformat(), suffix)

        wrapper = FileWrapper(file(baked_filepath))
        response = HttpResponse(wrapper, content_type=content_type)
        response['Content-Disposition'] = 'attachment; filename='+response_filename
        return response
    except Award.DoesNotExist:
        raise Http404()
Exemple #13
0
def get_bill(request):
    """download bill
    """
    req_inf = RequestInfo()
    try:
        bill = Factura.objects.get(_id=request.GET.get('bill'))
        name = 'bill-{}{}.xml'.format(request.user.username, bill.id)
        with open(name, 'wb') as f:
            f.write(
                dicttoxml(FacturaDetailSerializer(bill).data, attr_type=False))
        bill_file = open('{}/{}'.format(settings.BASE_DIR, name), 'rb')
        response = HttpResponse(FileWrapper(bill_file),
                                content_type='application/xml')
        response['Content-Disposition'] = 'attachment; filename="{}"'.format(
            name)
        os.remove('{}/{}'.format(settings.BASE_DIR, name))
        return response
    except ObjectDoesNotExist as e:
        return req_inf.status(e.args[0], status.HTTP_404_NOT_FOUND)
    except Exception as e:
        return req_inf.status(e.args[0], status.HTTP_400_BAD_REQUEST)
Exemple #14
0
def _csv_table(request, filename):
    if filename not in [x[1] for xs in get_tables_allowed_to_export().values() for x in xs] and \
            filename not in [x for xs in get_custom_exports().values() for x in xs.keys()]:
        response = {"error": "the requested file '%s' is not valid" % filename}
        return render_json(request,
                           response,
                           status=400,
                           template='common_json.html')
    download_file = settings.DATA_DIR + '/' + filename + ".csv"
    if not os.path.exists(download_file):
        response = {"error": "there is no data for the given table"}
        return render_json(request,
                           response,
                           status=204,
                           template='common_json.html')
    response = HttpResponse(FileWrapper(open(download_file)),
                            content_type='application/csv')
    response['Content-Length'] = os.path.getsize(download_file)
    response[
        'Content-Disposition'] = 'attachment; filename=' + filename + '.csv'
    return response
Exemple #15
0
    def post(self, request, *args, **kwargs):
        _class = self.category.document_class()
        form_data = self.request.POST
        qs = Document.objects.filter(category=self.category)
        form = _class.get_document_download_form(form_data, queryset=qs)
        if form.is_valid():
            data = form.cleaned_data
        else:
            raise Http404('Invalid parameters to download files.')

        # Generates the temporary zip file
        zip_filename = _class.compress_documents(data['document_ids'], **data)
        file_size = zip_filename.tell()
        zip_filename.seek(0)
        wrapper = FileWrapper(zip_filename)

        # Returns the zip file for download
        response = HttpResponse(wrapper, content_type='application/zip')
        response['Content-Disposition'] = 'attachment; filename=download.zip'
        response['Content-Length'] = file_size
        return response
Exemple #16
0
def export_manual_lineup(request):
    ds = request.session.get('ds')
    lidx = request.GET.getlist('lidx')
    path = "/tmp/.fantasy_nba_{}.csv".format(ds.lower())
    csv_fields = CSV_FIELDS[ds]

    with open(path, 'w') as f:
        f.write(','.join(csv_fields)+'\n')
        for idx in lidx:
            key = '{}_lineup_{}'.format(ds, idx)
            lineup = request.session.get(key)
            players = [Player.objects.get(id=ii['player']) for ii in lineup]
            f.write(','.join([_get_export_cell(ii, ds) for ii in players])+'\n')
        
    wrapper = FileWrapper( open( path, "r" ) )
    content_type = mimetypes.guess_type( path )[0]

    response = HttpResponse(wrapper, content_type = content_type)
    response['Content-Length'] = os.path.getsize( path )
    response['Content-Disposition'] = 'attachment; filename=%s' % smart_str( os.path.basename( path ) )
    return response
Exemple #17
0
    def get(self, request, *args, **kwargs):
        post = get_object_or_404(self.get_queryset(), pk=self.kwargs['pk'])
        if request.user.is_superuser or post.author_id == request.user.id:
            pass
        elif post.visible == 'private' or post.visible == 'sell' and not post.buyers.filter(id=request.user.id).exists():
            raise Http404

        chunk_size = 8192
        response = StreamingHttpResponse(FileWrapper(open(post.attachment.path, 'rb'), chunk_size),
                                         content_type='application/octet-stream')
        response['Content-Length'] = post.attachment.size

        filename = post.attachment_filename if post.attachment_filename else 'attachment'
        response["Content-Disposition"] = \
            "attachment; " \
            "filenane={ascii_filename};" \
            "filename*=UTF-8''{utf_filename}".format(
                ascii_filename=quote(filename),
                utf_filename=quote(filename)
            )
        return response
Exemple #18
0
def downloadfile(request, m, r):
    """
    Download File returns an KML filename as petition. The files have the
    following format: IBRI[m]R[r].kml where the m is the mission id and the
    r is the route id.

    @param request: Request petition that is handled by Django
    @param m: Represents the mission id
    @param r: Represents the route id
    @see FileWrapper
    @see Content-Disposition
    """

    filename = os.path.join(KML_DIR, 'IBRI' + m, 'IBRI' + m + 'R' + r + '.kml')
    wrapper = FileWrapper(file(filename))
    ct = 'application/vnd.google-earth.kml+xml'
    response = HttpResponse(wrapper, content_type=ct)
    cd = 'attachment; filename=%s' % os.path.basename(filename)
    response['Content-Disposition'] = cd
    response['Content-Length'] = os.path.getsize(filename)
    return response
Exemple #19
0
def uploadpage(request):
    # Handle file upload
    if request.method == 'POST':

        docxfile = request.FILES['docxin']
        try:
            cw = docx2cwtex(docxfile)
        except:
            return HttpResponse(docxfile.name + " 這檔案業障太深,淨化不來。")
        cwTexfile = ContentFile(cw)

        filename = '/home/cloud/Github/lalay/media/README.md'
        wrapper = FileWrapper(File(cwTexfile))
        response = HttpResponse(wrapper, content_type='text/plain')
        response[
            'Content-Disposition'] = 'attachment; filename=' + docxfile.name + '.txt'
        # response['Content-Length'] = getsize(filename)
        return response

    # Render list page with the documents and the form
    return render(request, 'uploadpage.html', {})
Exemple #20
0
def get_warc_stream(link):
    filename = "%s.warc.gz" % link.guid

    warcinfo = make_detailed_warcinfo(
        filename=filename,
        guid=link.guid,
        coll_title='Perma Archive, %s' % link.submitted_title,
        coll_desc=link.submitted_description,
        rec_title='Perma Archive of %s' % link.submitted_title,
        pages=[{
            'title': link.submitted_title,
            'url': link.submitted_url
        }])

    warc_stream = FileWrapper(default_storage.open(link.warc_storage_file()))
    warc_stream = itertools.chain([warcinfo], warc_stream)
    response = StreamingHttpResponse(warc_stream,
                                     content_type="application/gzip")
    response['Content-Disposition'] = 'attachment; filename="%s"' % filename

    return response
Exemple #21
0
 def get(self,
         request,
         path,
         document_root=getattr(settings, "DOWNLOAD_ROOT")):
     """
     download the file
     """
     #import ipdb;ipdb.set_trace()
     file_name = os.path.join(document_root, path)
     if os.path.exists(file_name):
         mime_type = mimetypes.guess_type(file_name)
         response = HttpResponse(FileWrapper(open(file_name)),
                                 content_type=mime_type)
         response[
             "Content-Disposition"] = 'attachment; filename="{0}"'.format(
                 os.path.split(file_name)[1])
         file_size = os.path.getsize(file_name)
         response["Content-Length"] = file_size
         return response
     else:
         raise Http404
Exemple #22
0
 def get(self, request):
     submitID = request.GET.get('id', None)
     if submitID:
         try:
             submit = SubmitModel.objects.get(pk=submitID)
         except SubmitModel.DoesNotExist:
             return Response({
                 'status': -1,
                 'message': 'Report does not exist'
             })
         try:
             submitFile = open(submit.fileSubmitted.path, 'rb')
         except FileNotFoundError:
             return Response({'status': -1, 'message': "File not found"})
         response = HttpResponse(FileWrapper(submitFile),
                                 content_type='application/zip')
         response[
             'Content-Disposition'] = 'attachment; filename="{}"'.format(
                 submit.fileSubmitted.name + '.zip')
         return response
     return Response({'status': -1, 'message': "Report not found"})
Exemple #23
0
    def get(self, request, *args, **kwargs):
        job = self.get_job()
        auditor.record(event_type=JOB_LOGS_VIEWED,
                       instance=self.job,
                       actor_id=request.user.id,
                       actor_name=request.user.username)
        log_path = get_job_logs_path(job.unique_name)

        filename = os.path.basename(log_path)
        chunk_size = 8192
        try:
            wrapped_file = FileWrapper(open(log_path, 'rb'), chunk_size)
            response = StreamingHttpResponse(wrapped_file,
                                             content_type=mimetypes.guess_type(log_path)[0])
            response['Content-Length'] = os.path.getsize(log_path)
            response['Content-Disposition'] = "attachment; filename={}".format(filename)
            return response
        except FileNotFoundError:
            _logger.warning('Log file not found: log_path=%s', log_path)
            return Response(status=status.HTTP_404_NOT_FOUND,
                            data='Log file not found: log_path={}'.format(log_path))
Exemple #24
0
    def get(self, request, *args, **kwargs):
        obj = self.get_object()
        if obj in request.user.myproducts.products.all():
            filepath = os.path.join(settings.PROTECTED_ROOT, obj.media.path)
            guessed_type = guess_type(filepath)[0]
            wrapper = FileWrapper(open(filepath, 'rb'))
            mimetype = 'application/force-download'

            if guessed_type:
                mimetype = guessed_type
            response = HttpResponse(wrapper, content_type=mimetype)

            if not request.GET.get("preview"):
                response[
                    "Content-Disposition"] = "attachement; filename = %s" % (
                        obj.media.name)

            response["X-SendFile"] = str(obj.media.name)
            return response
        else:
            raise Http404
def homepage(request):
	if request.method=="GET":
		return render(request,'mainapp/index.html')
	if request.method == 'POST' and request.FILES['myfile']:
	    myfile = request.FILES['myfile']
	    fs = FileSystemStorage()
	    filename = fs.save(myfile.name, myfile)
	    uploaded_file_url = fs.url(filename)

	    file_path = settings.MEDIA_ROOT +'/'+ filename
	    dataset=pd.read_csv('mainapp/employee_data_modified.csv')
	    run_machine_learning(file_path,dataset)
	    file_path = settings.MEDIA_ROOT +'/'+ "result.xlsx"
	    file_wrapper = FileWrapper(open(file_path,'rb'))
	    file_mimetype = mimetypes.guess_type(file_path)
	    response = HttpResponse(file_wrapper, content_type=file_mimetype )
	    response['X-Sendfile'] = file_path
	    response['Content-Length'] = os.stat(file_path).st_size
	    response['Content-Disposition'] = 'attachment; filename=%s' % smart_str("result.xlsx") 

	    return response
Exemple #26
0
def download(request):
    """Download from MobSF Route."""
    msg = 'Error Downloading File '
    if request.method == 'GET':
        allowed_exts = settings.ALLOWED_EXTENSIONS
        filename = request.path.replace('/download/', '', 1)
        # Security Checks
        if '../' in filename:
            msg = 'Path Traversal Attack Detected'
            return print_n_send_error_response(request, msg)
        ext = os.path.splitext(filename)[1]
        if ext in allowed_exts:
            dwd_file = os.path.join(settings.DWD_DIR, filename)
            if os.path.isfile(dwd_file):
                wrapper = FileWrapper(open(dwd_file, 'rb'))
                response = HttpResponse(wrapper,
                                        content_type=allowed_exts[ext])
                response['Content-Length'] = os.path.getsize(dwd_file)
                return response
    msg += filename
    return print_n_send_error_response(request, msg)
Exemple #27
0
 def get(self, request):
     project_id = request.query_params.get('project_id', None)
     project = al_project.objects.get(pk=project_id)
     self.check_object_permissions(
         request, project)
     base_d = '/'.join(project.texts.path.split('/')[:-1])
     t = TaskResult.objects.filter(
         status='SUCCESS',
         result__icontains='"project": {}}}'.format(project_id)).order_by('-id')
     if t.count() > 0:
         c = json.loads(t[0].result)
         model_name = c['folder'].split('/')[-1]
         ts = datetime.datetime.now().strftime('%Y-%m-%d_%H_%M_%S')
         filename = "{}_{}_{}".format(project.name, model_name, ts)
         export_file = make_archive(os.path.join(base_d, filename), 'zip',
                                    base_d, model_name)
         response = HttpResponse(FileWrapper(open(export_file, 'rb')),
                                 content_type='application/zip')
         response['Content-Disposition'] = 'attachment; filename="{}.zip"'.format(
             filename)
         return response
Exemple #28
0
def file_response_default_processor(start_response):

    response = IN.context.response

    if not response.headers.get('content-type', False):

        if response.file_path and not response.file_extension:
            response.file_extension = os.path.splitext(response.file_path)
        #print(response.file_extension)
        #print(httpgate.MimeTypes.mime_type(response.file_extension))
        response.headers.add_header(
            'content-type',
            In.http.MimeTypes.mime_type(response.file_extension))
    #else:
    #print(IN.context.response.headers.get('content-type', False))

    response_headers = response.headers.items()

    response.output = FileWrapper(response.file)

    start_response(str(response.status), response_headers)
def download_log_files(request, file_name=""):
    """
        Takes a GET request.
        Uses the 'logs' folder. Creates a zip file of the contents within the 'logs' folder.
        Returns the zip file in the response
    """
    if request.method == 'GET':
        try:
            files_path = "logs"
            path_to_zip = make_archive(files_path, "zip", files_path)
            response = HttpResponse(FileWrapper(open(path_to_zip, 'rb')),
                                    content_type='application/zip')
            response[
                'Content-Disposition'] = 'attachment; filename="{filename}.zip"'.format(
                    filename=file_name.replace(" ", "_"))
        except (FileNotFoundError):
            return HttpResponseNotFound()
        else:
            return response
    else:
        return HttpResponseBadRequest()
Exemple #30
0
def download_sample(request):
    data_received = request.query_params
    logger.info(f"Get binary by Job ID. Data received {data_received}")
    if "job_id" not in data_received:
        return Response({"error": "821"}, status=status.HTTP_400_BAD_REQUEST)
    # get job object or raise 404
    try:
        job = models.Job.objects.get(pk=data_received["job_id"])
    except models.Job.DoesNotExist:
        raise NotFound()
    # check permission
    if not request.user.has_perm("api_app.view_job", job):
        raise PermissionDenied()
    # make sure it is a sample
    if not job.is_sample:
        raise ParseError(
            detail="Requested job does not have a sample associated with it.")
    response = HttpResponse(FileWrapper(job.file),
                            content_type=job.file_mimetype)
    response["Content-Disposition"] = f"attachment; filename={job.file_name}"
    return response