Python django.conf.settings.MEDIA_ROOT Examples

The following are 30 code examples for showing how to use django.conf.settings.MEDIA_ROOT(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.conf.settings , or try the search function .

Example 1
Project: ideascube   Author: ideascube   File: forms.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def save(self, commit=True):
        document = super().save(commit=False)
        original = self.cleaned_data['original']
        original = os.path.relpath(original, settings.MEDIA_ROOT)
        document.original = original

        preview = self.cleaned_data.get('preview', None)
        if preview:
            preview = os.path.relpath(preview, settings.MEDIA_ROOT)
            document.preview = preview

        if commit:
            if not document.id:
                document.save()
            self.save_m2m()
            document.save()
        return document 
Example 2
Project: mendelmd   Author: raonyguimaraes   File: views.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def download_annotated(request, individual_id):
    individual = get_object_or_404(Individual, pk=individual_id)
    
    filepath = os.path.dirname(str(individual.vcf_file.name))
    filename = os.path.basename(str(individual.vcf_file.name))
    
    # path = settings.MEDIA_ROOT
    # if filename.endswith('vcf.zip'):
       # basename = filename.split('.vcf.zip')[0]       
    # else:
    
    basename = filename.split('.vcf')[0]
    
    fullpath = '%s/annotation.final.vcf.zip' % (filepath)

    vcffile = open(fullpath, 'rb')

    response = HttpResponse(vcffile, content_type='application/x-zip-compressed')
    # # response['Content-Encoding'] = 'gzip'
    response['Content-Disposition'] = 'attachment; filename=%s.annotated.mendelmd.vcf.zip' % basename
    response['Content-Length'] = os.path.getsize(fullpath)
    return response 
Example 3
Project: mendelmd   Author: raonyguimaraes   File: views.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def download_annotated(request, individual_id):
    individual = get_object_or_404(Individual, pk=individual_id)
    
    filepath = os.path.dirname(str(individual.vcf_file.name))
    filename = os.path.basename(str(individual.vcf_file.name))
    
    # path = settings.MEDIA_ROOT
    # if filename.endswith('vcf.zip'):
       # basename = filename.split('.vcf.zip')[0]       
    # else:
    
    basename = filename.split('.vcf')[0]
    
    fullpath = '%s/annotation.final.vcf.zip' % (filepath)

    vcffile = open(fullpath, 'rb')

    response = HttpResponse(vcffile, content_type='application/x-zip-compressed')
    # # response['Content-Encoding'] = 'gzip'
    response['Content-Disposition'] = 'attachment; filename=%s.annotated.mendelmd.vcf.zip' % basename
    response['Content-Length'] = os.path.getsize(fullpath)
    return response 
Example 4
Project: GTDWeb   Author: lanbing510   File: utils.py    License: GNU General Public License v2.0 6 votes vote down vote up
def check_settings(base_url=None):
    """
    Checks if the staticfiles settings have sane values.

    """
    if base_url is None:
        base_url = settings.STATIC_URL
    if not base_url:
        raise ImproperlyConfigured(
            "You're using the staticfiles app "
            "without having set the required STATIC_URL setting.")
    if settings.MEDIA_URL == base_url:
        raise ImproperlyConfigured("The MEDIA_URL and STATIC_URL "
                                   "settings must have different values")
    if ((settings.MEDIA_ROOT and settings.STATIC_ROOT) and
            (settings.MEDIA_ROOT == settings.STATIC_ROOT)):
        raise ImproperlyConfigured("The MEDIA_ROOT and STATIC_ROOT "
                                   "settings must have different values") 
Example 5
Project: GTDWeb   Author: lanbing510   File: storage.py    License: GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, location=None, base_url=None, file_permissions_mode=None,
            directory_permissions_mode=None):
        if location is None:
            location = settings.MEDIA_ROOT
        self.base_location = location
        self.location = abspathu(self.base_location)
        if base_url is None:
            base_url = settings.MEDIA_URL
        elif not base_url.endswith('/'):
            base_url += '/'
        self.base_url = base_url
        self.file_permissions_mode = (
            file_permissions_mode if file_permissions_mode is not None
            else settings.FILE_UPLOAD_PERMISSIONS
        )
        self.directory_permissions_mode = (
            directory_permissions_mode if directory_permissions_mode is not None
            else settings.FILE_UPLOAD_DIRECTORY_PERMISSIONS
        ) 
Example 6
Project: Python24   Author: HaoZhang95   File: views.py    License: MIT License 6 votes vote down vote up
def test21(request):
    """接收用户上传的图片"""

    # 从请求报文中获取图片的网络数据
    picture = request.FILES.get('pic')
    # 获取图片名字
    name = picture.name
    # 拼接图片保存在服务器路径
    path = '%s/Book/%s' % (settings.MEDIA_ROOT, name)

    # 将图片网络数据写入到path
    with open(path, 'wb') as file:
        # 遍历图片网络数据
        for c in picture.chunks():
            # 写入图片网络数据到本地保存
            file.write(c)

    # 创建模型类将图片路径写入到数据库
    pictureinfo = PictureInfo()
    pictureinfo.path = 'Book/%s' % name
    # save才能写入到数据库
    pictureinfo.save()

    return HttpResponse('OK!') 
Example 7
Project: FIR   Author: certsocietegenerale   File: files.py    License: GNU General Public License v3.0 6 votes vote down vote up
def do_download_archive(request, content_type, object_id):
    object_type = ContentType.objects.get(pk=content_type)
    obj = get_object_or_404(object_type.model_class(), pk=object_id)
    if not request.user.has_perm('incidents.view_incidents', obj=obj):
        raise PermissionDenied()
    if obj.file_set.count() == 0:
        raise Http404
    temp = BytesIO()
    with zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED) as archive:
        media_root = settings.MEDIA_ROOT
        for file in obj.file_set.all():
            path = os.path.join(media_root, file.file.path)
            archive.write(path, os.path.basename(path))
    file_size = temp.tell()
    temp.seek(0)
    wrapper = FileWrapper(temp)

    response = HttpResponse(wrapper, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=archive_%s_%s.zip' % (object_type.model, object_id)
    response['Content-Length'] = file_size
    return response 
Example 8
Project: anytask   Author: znick   File: storage.py    License: MIT License 6 votes vote down vote up
def get_available_name(self, name):
        """Returns a filename that's free on the target storage system, and
        available for new content to be written to.

        Found at http://djangosnippets.org/snippets/976/

        This file storage solves overwrite on upload problem. Another
        proposed solution was to override the save method on the model
        like so (from https://code.djangoproject.com/ticket/11663):

        def save(self, *args, **kwargs):
            try:
                this = MyModelName.objects.get(id=self.id)
                if this.MyImageFieldName != self.MyImageFieldName:
                    this.MyImageFieldName.delete()
            except: pass
            super(MyModelName, self).save(*args, **kwargs)
        """
        # If the filename already exists, remove it as if it was a true file system
        if self.exists(name):
            os.remove(os.path.join(settings.MEDIA_ROOT, name))
        return name 
Example 9
Project: REST-API   Author: codingforentrepreneurs   File: tests.py    License: MIT License 6 votes vote down vote up
def test_status_create_with_image(self):
        self.status_user_token()
        url = api_reverse('api-status:list')
        # (w, h) = (800, 1280)
        # (255, 255, 255)
        image_item  = Image.new('RGB', (800, 1280), (0, 124, 174))
        tmp_file    = tempfile.NamedTemporaryFile(suffix='.jpg')
        image_item.save(tmp_file, format='JPEG')
        with open(tmp_file.name, 'rb') as file_obj:
            data = {
                'content': "some cool test content",
                'image': file_obj
            }
            response = self.client.post(url, data, format='multipart')
            self.assertEqual(response.status_code, status.HTTP_201_CREATED)
            self.assertEqual(Status.objects.count(), 2)
            img_data = response.data.get('image')
            self.assertNotEqual(img_data, None)
        temp_img_dir = os.path.join(settings.MEDIA_ROOT, 'status', 'testcfeuser')
        if os.path.exists(temp_img_dir):
            shutil.rmtree(temp_img_dir) 
Example 10
Project: REST-API   Author: codingforentrepreneurs   File: tests.py    License: MIT License 6 votes vote down vote up
def test_status_create_with_img_and_desc(self):
        self.status_user_token()
        url = api_reverse('api-status:list')
        # (w, h) = (800, 1280)
        # (255, 255, 255)
        image_item  = Image.new('RGB', (800, 1280), (0, 124, 174))
        tmp_file    = tempfile.NamedTemporaryFile(suffix='.jpg')
        image_item.save(tmp_file, format='JPEG')
        with open(tmp_file.name, 'rb') as file_obj:
            data = {
                'content': None,
                'image': file_obj
            }
            response = self.client.post(url, data, format='multipart')
            self.assertEqual(response.status_code, status.HTTP_201_CREATED)
            

            self.assertEqual(Status.objects.count(), 2)
        temp_img_dir = os.path.join(settings.MEDIA_ROOT, 'status', 'testcfeuser')
        if os.path.exists(temp_img_dir):
            shutil.rmtree(temp_img_dir) 
Example 11
Project: DCRM   Author: 82Flex   File: version.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def write_to_package_job(control, path, callback_version_id):
    # copy to temporary
    """
    This job will be called when any field in .deb file control part
    has been edited.
    
    :param control: New Control Dict
    :type control: dict
    :param path: Original Package Path
    :type path: str
    :param callback_version_id: Callback Version ID, for callback query
    :type callback_version_id: int
    """
    abs_path = os.path.join(settings.MEDIA_ROOT, path)
    temp_path = os.path.join(settings.TEMP_ROOT, str(uuid.uuid1()) + '.deb')
    shutil.copyfile(abs_path, temp_path)
    # read new package
    temp_package = DebianPackage(temp_path)
    temp_package.control = control
    # save new package
    temp_package.save()
    t_version = Version.objects.get(id=callback_version_id)
    t_version.write_callback(temp_package.path) 
Example 12
Project: bioforum   Author: reBiocoder   File: utils.py    License: MIT License 6 votes vote down vote up
def check_settings(base_url=None):
    """
    Check if the staticfiles settings have sane values.
    """
    if base_url is None:
        base_url = settings.STATIC_URL
    if not base_url:
        raise ImproperlyConfigured(
            "You're using the staticfiles app "
            "without having set the required STATIC_URL setting.")
    if settings.MEDIA_URL == base_url:
        raise ImproperlyConfigured("The MEDIA_URL and STATIC_URL "
                                   "settings must have different values")
    if ((settings.MEDIA_ROOT and settings.STATIC_ROOT) and
            (settings.MEDIA_ROOT == settings.STATIC_ROOT)):
        raise ImproperlyConfigured("The MEDIA_ROOT and STATIC_ROOT "
                                   "settings must have different values") 
Example 13
Project: AutoOut   Author: MateLabs   File: views.py    License: MIT License 6 votes vote down vote up
def detect_outliers(request):
    """
    Detect outliers end point
    """
    dataset_id = int(request.GET.get("dataset_id"))

    if dataset_id is None:
        return JsonResponse({"status": "failure", "message": "Dataset id is not provided"})

    dataset = Dataset.objects.get(pk=dataset_id)
    file_path = dataset.path
    delete_features = json.loads(dataset.deleted_features)

    # Create a detection experiment and start outlier detection
    process = Process.objects.get(name='Detection')
    process_status = ProcessStatus.objects.get(name='Running')
    experiment = Experiment(dataset=dataset, process=process, process_status=process_status)
    experiment.save()
    results = delayed(detect_all)(os.path.join(settings.MEDIA_ROOT, file_path), experiment.id, settings.RESULTS_ROOT,
                                  delete_features)
    dask.compute(results)

    return JsonResponse(
        {'status': 'success', 'message': 'Detection started successfully', 'experiment_id': experiment.id}) 
Example 14
Project: AutoOut   Author: MateLabs   File: views.py    License: MIT License 6 votes vote down vote up
def get_data(request):
    page_no = int(request.GET.get("page_num", 1))
    dataset_id = int(request.GET.get("dataset_id"))
    print("Page no:", page_no)

    if dataset_id is None:
        return JsonResponse({"status": "failure", "message": "Dataset id is not provided"})

    dataset = Dataset.objects.get(pk=dataset_id)

    # datasets = Dataset.objects.all().order_by('-created_at')
    # latest_dataset = datasets[0]
    dataset_name = dataset.path
    dataset_path = os.path.join(settings.MEDIA_ROOT, dataset_name)
    filename, file_extension = os.path.splitext(dataset_path)

    df = DataLoader.load(dataset_path)
    # df = pd.read_csv(dataset_path)
    df = df.iloc[(page_no - 1) * 20:(page_no - 1) * 20 + 20, :]
    return JsonResponse(df.to_json(orient='records'), safe=False) 
Example 15
Project: AutoOut   Author: MateLabs   File: views.py    License: MIT License 6 votes vote down vote up
def get_treated_data(request):
    page_no = int(request.GET.get("page_num", 1))
    experiment_id = int(request.GET.get("experiment_id"))
    print("Page no:", page_no)

    if experiment_id is None:
        return JsonResponse({"status": "failure", "message": "Experiment id is file"})

    experiment = Experiment.objects.get(pk=experiment_id)
    treated_file_name = experiment.treated_file_path

    dataset_path = os.path.join(settings.MEDIA_ROOT, treated_file_name)
    filename, file_extension = os.path.splitext(dataset_path)

    df = DataLoader.load(dataset_path)
    # df = pd.read_csv(dataset_path)
    df = df.iloc[(page_no - 1) * 20:(page_no - 1) * 20 + 20, :]
    return JsonResponse(df.to_json(orient='records'), safe=False) 
Example 16
Project: AutoOut   Author: MateLabs   File: views.py    License: MIT License 6 votes vote down vote up
def get_dataset_properties(request):
    """
    Dataset properties endpoints
    """
    dataset_id = int(request.GET.get("dataset_id"))
    if dataset_id is None:
        return JsonResponse({"status": "failure", "message": "Dataset id is not provided"})

    dataset = Dataset.objects.get(pk=dataset_id)
    dataset_name = dataset.path

    dataset_path = os.path.join(settings.MEDIA_ROOT, dataset_name)
    df = DataLoader.load(dataset_path)
    # df = pd.read_csv(dataset_path)

    no_samples = df.shape[0]
    no_features = df.shape[1]

    no_numerical_features = df.select_dtypes(include=[np.number]).shape[1]
    no_categorical_features = len([i for i in df.columns if df.dtypes[i] == 'object'])

    return JsonResponse({"no_samples": no_samples, "no_features": no_features,
                         "no_numerical_features": no_numerical_features,
                         "no_categorical_features": no_categorical_features,
                         "deleted_features": dataset.deleted_features}) 
Example 17
Project: palanaeum   Author: Palanaeum   File: configuration.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def set_config_file(key: str, file: UploadedFile):
    from palanaeum.models import ConfigEntry

    try:
        entry = ConfigEntry.objects.get(key=key)
        if entry.value:
            os.unlink(os.path.join(settings.MEDIA_ROOT, entry.value))
    except ConfigEntry.DoesNotExist:
        entry = ConfigEntry(key=key)
    except FileNotFoundError:
        pass

    file_path = os.path.join(settings.CONFIG_UPLOADS, file.name)
    os.makedirs(settings.CONFIG_UPLOADS, exist_ok=True)
    entry.value = os.path.relpath(file_path, settings.MEDIA_ROOT)

    with open(file_path, mode='wb') as write_file:
        for chunk in file.chunks():
            write_file.write(chunk)

    entry.save()
    cache.set(key, entry.value)
    return 
Example 18
Project: micro-finance   Author: MicroPyramid   File: views.py    License: MIT License 6 votes vote down vote up
def client_ledger_pdf_download(request, client_id, loanaccount_id):
    client = get_object_or_404(Client, id=client_id)
    loanaccount = get_object_or_404(LoanAccount, id=loanaccount_id)
    receipts_list = Receipts.objects.filter(
        client=client,
        member_loan_account=loanaccount
    ).exclude(
        demand_loanprinciple_amount_atinstant=0,
        demand_loaninterest_amount_atinstant=0
    )
    try:
        # context = Context({
        #     'pagesize': 'A4', "receipts_list": receipts_list,
        #     "client": client, "mediaroot": settings.MEDIA_ROOT})
        context = dict({
            'pagesize': 'A4', "receipts_list": receipts_list,
            "client": client, "mediaroot": settings.MEDIA_ROOT})
        return render(request, 'pdfledger.html', context)
    except Exception as err:
        errmsg = "%s" % (err)
        return HttpResponse(errmsg) 
Example 19
Project: django-freeradius   Author: openwisp   File: test_api.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_batch_csv_201(self):
        self.assertEqual(self.radius_batch_model.objects.count(), 0)
        self.assertEqual(User.objects.count(), 0)
        text = 'user,cleartext$abcd,email@gmail.com,firstname,lastname'
        with open('{}/test.csv'.format(settings.MEDIA_ROOT), 'wb') as file:
            text2 = text.encode('utf-8')
            file.write(text2)
        with open('{}/test.csv'.format(settings.MEDIA_ROOT), 'rb') as file:
            data = self._get_post_defaults({
                "name": "test",
                "strategy": "csv",
                "csvfile": file,
            })
            response = self.client.post(reverse('freeradius:batch'), data,
                                        HTTP_AUTHORIZATION=self.auth_header)
        self.assertEqual(response.status_code, 201)
        self.assertEqual(self.radius_batch_model.objects.count(), 1)
        self.assertEqual(User.objects.count(), 1) 
Example 20
Project: Servo   Author: fpsw   File: files.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_file(request, path):
    """
    Returns a file from the upload directory
    """
    try:
        f = open(os.path.join(settings.MEDIA_ROOT, path), 'r')
    except IOError:
        raise Http404
    
    mimetypes.init()
    t, e = mimetypes.guess_type(f.name)

    return HttpResponse(f.read(), t) 
Example 21
Project: Servo   Author: fpsw   File: makedirs.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def handle(self, *args, **options):
        help = "Create necessary upload directories"
        dirs = ['attachments', 'devices', 'logos',
                'products', 'repairs', 'return_labels',
                'settings', 'temp', 'templates']

        if not os.path.exists(settings.MEDIA_ROOT):
            os.mkdir(settings.MEDIA_ROOT)
            
        for d in dirs:
            fp = os.path.join(settings.MEDIA_ROOT, d)
            try:
                os.mkdir(fp)
            except OSError as e:
                logging.warning(e) 
Example 22
Project: ideascube   Author: ideascube   File: conftest.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def setup_dirs(monkeypatch, tmpdir, settings):
    storage_root = tmpdir.mkdir('storage')
    settings.STORAGE_ROOT = storage_root.strpath
    settings.BACKUPED_ROOT = storage_root.mkdir('main').strpath
    settings.MEDIA_ROOT = storage_root.mkdir('main', 'media').strpath
    settings.CATALOG_STORAGE_ROOT = storage_root.mkdir(
        'main', 'catalog').strpath

    cache_root = tmpdir.mkdir('cache')
    settings.CATALOG_CACHE_ROOT = cache_root.mkdir('catalog').strpath

    install_root = tmpdir.mkdir('installs')
    settings.CATALOG_HANDLER_INSTALL_DIR = (
        install_root.mkdir('handler').strpath)
    settings.CATALOG_KIWIX_INSTALL_DIR = (
        install_root.mkdir('kiwix').strpath)
    settings.CATALOG_MEDIACENTER_INSTALL_DIR = (
        install_root.mkdir('mediacenter').strpath)
    settings.CATALOG_NGINX_INSTALL_DIR = (
        install_root.mkdir('nginx').strpath)

    # Change also the location of the default_storage as this is cached
    # and not updated when settings changed.
    monkeypatch.setattr(
        'django.core.files.storage.default_storage.location',
        settings.MEDIA_ROOT
    )
    monkeypatch.setattr(
        'django.core.files.storage.default_storage.base_location',
        settings.MEDIA_ROOT
    ) 
Example 23
Project: ideascube   Author: ideascube   File: clean.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def _get_leftover_files(self):
        # List all (original and preview) files in the fs
        original_files_root_dir = os.path.join(settings.MEDIA_ROOT,
                                               'mediacenter/document')
        files_in_fs = set(
            Path(original_files_root_dir).glob('**/*'))

        preview_files_root_dir = os.path.join(settings.MEDIA_ROOT,
                                    'mediacenter/preview')
        files_in_fs.update(
            Path(preview_files_root_dir).glob('**/*'))

        dirs_in_fs = {p for p in files_in_fs if p.is_dir()}
        files_in_fs.difference_update(dirs_in_fs)

        # Remove known original paths.
        original_pathes = Document.objects.all().values_list(
            'original', flat=True)
        original_pathes = (Path(settings.MEDIA_ROOT, path)
                           for path in original_pathes)
        files_in_fs.difference_update(original_pathes)

        # Remove known preview paths.
        preview_pathes = Document.objects.all().values_list(
            'preview', flat=True)
        preview_pathes = (Path(settings.MEDIA_ROOT, path)
                          for path in preview_pathes if path)
        files_in_fs.difference_update(preview_pathes)

        return files_in_fs, dirs_in_fs 
Example 24
Project: ideascube   Author: ideascube   File: catalog.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def install(self, download_path, install_dir):
        super().install(download_path, install_dir)
        print('Adding medias to mediacenter database.')
        root = self.get_root_dir(install_dir)
        manifestfile = Path(root, 'manifest.yml')

        try:
            with manifestfile.open('r') as m:
                manifest = yaml.load(m.read(), Loader=BaseYAMLLoader)

        except FileNotFoundError:
            raise InvalidPackageContent('Missing manifest file in {}'.format(
                self.id))

        os.makedirs(settings.MEDIA_ROOT, exist_ok=True)
        catalog_path = os.path.join(settings.MEDIA_ROOT, "catalog")
        try:
            os.symlink(install_dir, catalog_path)
        except FileExistsError:
            if not os.path.islink(catalog_path):
                printerr("Cannot install package {}. {} must not exist "
                         "or being a symlink.".format(self.id, catalog_path))
                return

        pseudo_install_dir = os.path.join(catalog_path, self.id)
        for media in manifest['medias']:
            try:
                self._install_media(media, pseudo_install_dir)
            except Exception as e:
                # This can lead to installed package with uninstall media.
                # We sould handle this somehow.
                printerr("Cannot install media {} from package {} : {}".format(
                    media['title'], self.id, e))
                continue 
Example 25
Project: mendelmd   Author: raonyguimaraes   File: views.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def download(request, individual_id):
    individual = get_object_or_404(Individual, pk=individual_id)
    
    filepath = os.path.dirname(str(individual.vcf_file.name))
    filename = os.path.basename(str(individual.vcf_file.name))
    
    path = ''
    # os.chmod("%s/genomes/%s/%s" % (settings.MEDIA_ROOT, individual.user, individual.id), 0777)

    
    # if filename.endswith('vcf.zip'):
       # basename = filename.split('.vcf.zip')[0]       
    # elif filename.endswith('.zip'):
       # basename = filename.split('.zip')[0]       
    # else:
       # basename = filename.split('.vcf')[0]
    #print basename
    #print path
    #print filepath
    
    fullpath = '%s/%s' % (filepath, filename)
    if filename.endswith('.gz'):
        vcffile = gzip.open(fullpath, 'r')
    else:
        vcffile = open(fullpath, 'r')

    content = vcffile.read()
    vcffile.close()

    response = HttpResponse(content, content_type='text/plain')
    response['Content-Disposition'] = 'attachment; filename=%s' % filename
    response['Content-Length'] = os.path.getsize(fullpath)
    return response 
Example 26
Project: mendelmd   Author: raonyguimaraes   File: views.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def download(request, individual_id):
    individual = get_object_or_404(Individual, pk=individual_id)
    
    filepath = os.path.dirname(str(individual.vcf_file.name))
    filename = os.path.basename(str(individual.vcf_file.name))
    
    path = ''
    # os.chmod("%s/genomes/%s/%s" % (settings.MEDIA_ROOT, individual.user, individual.id), 0777)

    
    # if filename.endswith('vcf.zip'):
       # basename = filename.split('.vcf.zip')[0]       
    # elif filename.endswith('.zip'):
       # basename = filename.split('.zip')[0]       
    # else:
       # basename = filename.split('.vcf')[0]
    #print basename
    #print path
    #print filepath
    
    fullpath = '%s/%s' % (filepath, filename)
    if filename.endswith('.gz'):
        vcffile = gzip.open(fullpath, 'r')
    else:
        vcffile = open(fullpath, 'r')

    content = vcffile.read()
    vcffile.close()

    response = HttpResponse(content, content_type='text/plain')
    response['Content-Disposition'] = 'attachment; filename=%s' % filename
    response['Content-Length'] = os.path.getsize(fullpath)
    return response 
Example 27
Project: mendelmd   Author: raonyguimaraes   File: views.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def download(request, individual_id):
    individual = get_object_or_404(Individual, pk=individual_id)
    
    filepath = os.path.dirname(str(individual.vcf_file.name))
    filename = os.path.basename(str(individual.vcf_file.name))
    
    path = ''
    # os.chmod("%s/genomes/%s/%s" % (settings.MEDIA_ROOT, individual.user, individual.id), 0777)

    
    # if filename.endswith('vcf.zip'):
       # basename = filename.split('.vcf.zip')[0]       
    # elif filename.endswith('.zip'):
       # basename = filename.split('.zip')[0]       
    # else:
       # basename = filename.split('.vcf')[0]
    #print basename
    #print path
    #print filepath
    
    fullpath = '%s/%s' % (filepath, filename)
    if filename.endswith('.gz'):
        vcffile = gzip.open(fullpath, 'r')
    else:
        vcffile = open(fullpath, 'r')

    content = vcffile.read()
    vcffile.close()

    response = HttpResponse(content, content_type='text/plain')
    response['Content-Disposition'] = 'attachment; filename=%s' % filename
    response['Content-Length'] = os.path.getsize(fullpath)
    return response 
Example 28
Project: wagtailinvoices   Author: SableWalnut   File: editor.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def serve_pdf(invoice, request):
    # Convert HTML URIs to absolute system paths so xhtml2pdf can access those resources

    def link_callback(uri, rel):
        # use short variable names
        sUrl = settings.STATIC_URL      # Typically /static/
        sRoot = settings.STATIC_ROOT    # Typically /home/userX/project_static/
        mUrl = settings.MEDIA_URL       # Typically /static/media/
        mRoot = settings.MEDIA_ROOT     # Typically /home/userX/project_static/media/

        # convert URIs to absolute system paths
        if uri.startswith(mUrl):
            path = os.path.join(mRoot, uri.replace(mUrl, ""))
        elif uri.startswith(sUrl):
            path = os.path.join(sRoot, uri.replace(sUrl, ""))

        # make sure that file exists
        if not os.path.isfile(path):
                raise Exception(
                        'media URI must start with %s or %s' % \
                        (sUrl, mUrl))
        return path

    # Render html content through html template with context
    template = get_template(settings.PDF_TEMPLATE)
    html = template.render(Context(invoice))

    # Write PDF to file
    # file = open(os.path.join(settings.MEDIA_ROOT, 'Invoice #' + str(id) + '.pdf'), "w+b")
    file = StringIO.StringIO()
    pisaStatus = pisa.CreatePDF(html, dest=file, link_callback=link_callback)

    # Return PDF document through a Django HTTP response
    file.seek(0)
    # pdf = file.read()
    # file.close()            # Don't forget to close the file handle
    return HttpResponse(file, content_type='application/pdf') 
Example 29
Project: readux   Author: ecds   File: conftest.py    License: MIT License 5 votes vote down vote up
def media_storage(settings, tmpdir):
    settings.MEDIA_ROOT = tmpdir.strpath 
Example 30
def get_cover_base64(self):
        # settings.MEDIA_ROOT = '/path/to/env/projectname/media'
        return image_as_base64(settings.MEDIA_ROOT + self.cover.path)