Python django.conf.settings.MEDIA_ROOT Examples

The following are 30 code examples of django.conf.settings.MEDIA_ROOT(). 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 also want to check out all available functions/classes of the module django.conf.settings , or try the search function .
Example #1
Source File: forms.py    From ideascube with GNU Affero General Public License v3.0 7 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
Source File: views.py    From mendelmd with BSD 3-Clause "New" or "Revised" License 7 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
Source File: utils.py    From bioforum with 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 #4
Source File: utils.py    From GTDWeb with 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
Source File: views.py    From micro-finance with 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 #6
Source File: views.py    From mendelmd with 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 #7
Source File: storage.py    From GTDWeb with 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 #8
Source File: test_api.py    From django-freeradius with 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 #9
Source File: configuration.py    From palanaeum with 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 #10
Source File: views.py    From Python24 with 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 #11
Source File: storage.py    From anytask with 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 #12
Source File: tests.py    From REST-API with 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 #13
Source File: views.py    From AutoOut with 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 #14
Source File: views.py    From AutoOut with 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 #15
Source File: views.py    From AutoOut with 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 #16
Source File: views.py    From AutoOut with 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 #17
Source File: version.py    From DCRM with 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 #18
Source File: files.py    From FIR with 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 #19
Source File: tests.py    From REST-API with 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 #20
Source File: tasks.py    From OasisPlatform with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def log_worker_monitor(sender, **k):
    logger.info('DEBUG: {}'.format(settings.DEBUG))    
    logger.info('DB_ENGINE: {}'.format(settings.DB_ENGINE))    
    logger.info('STORAGE_TYPE: {}'.format(settings.STORAGE_TYPE))    
    logger.info('DEFAULT_FILE_STORAGE: {}'.format(settings.DEFAULT_FILE_STORAGE))    
    logger.info('MEDIA_ROOT: {}'.format(settings.MEDIA_ROOT))    
    logger.info('AWS_STORAGE_BUCKET_NAME: {}'.format(settings.AWS_STORAGE_BUCKET_NAME))    
    logger.info('AWS_LOCATION: {}'.format(settings.AWS_LOCATION))    
    logger.info('AWS_S3_REGION_NAME: {}'.format(settings.AWS_S3_REGION_NAME))    
    logger.info('AWS_QUERYSTRING_AUTH: {}'.format(settings.AWS_QUERYSTRING_AUTH))    
    logger.info('AWS_QUERYSTRING_EXPIRE: {}'.format(settings.AWS_QUERYSTRING_EXPIRE))    
    logger.info('AWS_SHARED_BUCKET: {}'.format(settings.AWS_SHARED_BUCKET))    
    logger.info('AWS_IS_GZIPPED: {}'.format(settings.AWS_IS_GZIPPED)) 
Example #21
Source File: utils.py    From django-freeradius with GNU General Public License v3.0 5 votes vote down vote up
def generate_pdf(prefix, data):
    template = get_template(BATCH_PDF_TEMPLATE)
    html = HTML(string=template.render(data))
    f = open("{}/{}.pdf".format(settings.MEDIA_ROOT, prefix), "w+b")
    html.write_pdf(target=f)
    f.seek(0)
    return File(f) 
Example #22
Source File: upload_image.py    From BikeMaps with MIT License 5 votes vote down vote up
def _handle_uploaded_file(f, size):
    im = Image.open(f)
    reduction = float(max(im.size)) / float(size)
    im = im.resize(map(lambda x: int(x/reduction), im.size))

    # Include date in filename to prevent clobbering of older images
    name, ext = f.name.split(".")
    m, d, y = time.strftime("%x").split("/")
    f.name = "_".join([name, m, d, y]) + "." + ext

    with open(os.path.join(settings.MEDIA_ROOT, "blogApp", f.name), 'wb+') as destination:
        im.save(destination)

    return f 
Example #23
Source File: test_receivers.py    From karrot-backend with GNU Affero General Public License v3.0 5 votes vote down vote up
def setUp(self):
        super().setUp()
        self.member = UserFactory()
        self.other_member = UserFactory()
        self.unrelated_user = UserFactory()
        self.group = GroupFactory(members=[self.member, self.other_member])
        pathlib.Path(settings.MEDIA_ROOT).mkdir(exist_ok=True)
        copyfile(
            os.path.join(os.path.dirname(__file__), './photo.jpg'), os.path.join(settings.MEDIA_ROOT, 'photo.jpg')
        )
        self.member.photo = 'photo.jpg'
        self.member.save()
        self.other_member.photo = 'photo.jpg'
        self.other_member.save() 
Example #24
Source File: views.py    From AutoOut with MIT License 5 votes vote down vote up
def upload_file(request):
    if request.method == 'POST':
        print(request.FILES)
        all_files = request.FILES.getlist('files[]')
        if len(all_files) > 0:
            try:
                uploaded_file = all_files[0]
                file_name = uploaded_file.name

                filename, file_extension = os.path.splitext(file_name)

                if not file_extension in [".csv", ".h5", '.xlxs']:
                    return JsonResponse({"status": "failure", "message": "Unsupported file format"})

                # TODO: Check for file extension here
                if not os.path.exists(settings.MEDIA_ROOT):
                    os.makedirs(settings.MEDIA_ROOT)

                file_name = "{}_{}".format(time.time(), file_name)
                file_path = os.path.join(settings.MEDIA_ROOT, file_name)
                fout = open(file_path, 'wb+')

                # Iterate through the chunks.
                for chunk in uploaded_file.chunks():
                    fout.write(chunk)
                fout.close()

                # Save this file to database
                dataset = Dataset(path=file_name)
                dataset.save()

                return JsonResponse({'status': 'success', 'message': 'Data uploaded successfully',
                                     'file_path': file_name, "dataset_id": dataset.id})
            except Exception as e:
                return JsonResponse({'status': 'failure', 'message': 'Error:Upload failed:{}'.format(e)})
        else:
            return JsonResponse({"status": "failure", "message": "No file found"})
    else:
        print(request)
        return JsonResponse({'status': 'failure', 'message': 'Invalid request'}) 
Example #25
Source File: 0060_work_poster.py    From mangaki with GNU Affero General Public License v3.0 5 votes vote down vote up
def save_poster_path(apps, schema_editor):
    Work = apps.get_model("mangaki", "Work")
    db_alias = schema_editor.connection.alias
    for work in Work.objects.using(db_alias):
        path = 'posters/{:d}.jpg'.format(work.id)
        if os.path.isfile(os.path.join(settings.MEDIA_ROOT, path)):
            work.int_poster.name = path
            work.save(using=db_alias, update_fields=['int_poster']) 
Example #26
Source File: views.py    From AutoOut with MIT License 5 votes vote down vote up
def treat_outliers(request):
    request_obj = json.loads(request.body.decode("utf-8"))
    experiment_id = request_obj["experiment_id"]
    treat_percentage = request_obj["treat_percentage"]

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

    experiment = Experiment.objects.get(pk=experiment_id)
    results_file_path = os.path.join(settings.RESULTS_ROOT, experiment.results_path)

    if experiment.process_status_id == 2:
        return JsonResponse({'status': 'success', 'message': 'Experiment is still running. Please wait for sometime'})

    try:
        with open(results_file_path, "r") as fp:
            outliers = json.load(fp)
    
            process = Process.objects.get(name='Treatment')
            process_status = ProcessStatus.objects.get(name='Running')
            experiment2 = Experiment(dataset=experiment.dataset, process=process, process_status=process_status)
            experiment2.save()

            results = delayed(treat)(os.path.join(settings.MEDIA_ROOT, experiment2.dataset.path),
                                     outliers, experiment2.id, settings.MEDIA_ROOT, treat_percentage)
            dask.compute(results)

            return JsonResponse(
                {"status": "success", "message": "Outlier treatment started", "experiment_id": experiment2.id})
    except Exception as e:
        print("Exception:", e)
        return JsonResponse({'status': "failure", "message": "Error"}) 
Example #27
Source File: tasks.py    From palanaeum with GNU Affero General Public License v3.0 5 votes vote down vote up
def create_snippet(snippet_id: int):
    """
    Create a snippet file.
    """
    time.sleep(1)  # To let the main process save changes to database.
    try:
        snippet = Snippet.objects.get(pk=snippet_id)
    except Snippet.DoesNotExist:
        logger.error("Snippet %s doesn't exist.", snippet_id)
        return
    if snippet.muted:
        logger.info("Muted snippets don't create new files.")
        return
    logger.info("Creating a file for snippet %s.", snippet_id)
    if snippet.file:
        filename = pathlib.Path(snippet.file).name
        match = re.match('^(\d+)_(\d+)\.mp3$', filename)
        beginning = int(match.group(1))
        length = int(match.group(2))
        if snippet.beginning == beginning and snippet.length == length and pathlib.Path(snippet.file).exists():
            logger.info("Snippet %s has already an OK file.", snippet_id)
            return

    # Recreate a snippet that's matching parameters.
    if snippet.file:
        os.unlink(snippet.file)
        snippet.file = ''
        snippet.save()

    new_name = "{}_{}.mp3".format(snippet.beginning, snippet.length)
    new_path = pathlib.Path(settings.MEDIA_ROOT, 'snippets', str(snippet.source_id), new_name)
    new_dir = new_path.parent
    new_dir.mkdir(parents=True, exist_ok=True)

    subprocess.run(["ffmpeg", "-y", "-ss", str(snippet.beginning), "-i", str(snippet.source.file.path),
                    "-t", str(snippet.length), str(new_path)],
                   stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
    snippet.file = str(new_path.relative_to(settings.BASE_DIR))
    snippet.save()
    logger.info("Snippet {} file created.".format(snippet_id))
    return 
Example #28
Source File: views.py    From OasisPlatform with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get(self, request):
        server_version = ""
        server_config = dict()

        try:
            with open('VERSION', 'r') as ver:
                server_version = ver.read().strip()
        except FileNotFoundError:
            server_version = ""

        server_config['DEBUG'] = settings.DEBUG
        server_config['LANGUAGE_CODE'] = settings.LANGUAGE_CODE
        server_config['TIME_ZONE'] = settings.TIME_ZONE

        # Backends  
        server_config['WSGI_APPLICATION'] = settings.WSGI_APPLICATION
        server_config['DEFAULT_FILE_STORAGE'] = settings.DEFAULT_FILE_STORAGE
        server_config['DB_ENGINE'] = settings.DB_ENGINE

        # Storage 
        server_config['STORAGE_TYPE'] = settings.STORAGE_TYPE
        server_config['MEDIA_ROOT'] = settings.MEDIA_ROOT
        server_config['AWS_STORAGE_BUCKET_NAME'] = settings.AWS_STORAGE_BUCKET_NAME
        server_config['AWS_LOCATION'] = settings.AWS_LOCATION
        server_config['AWS_SHARED_BUCKET'] = settings.AWS_SHARED_BUCKET
        server_config['AWS_QUERYSTRING_EXPIRE'] = settings.AWS_QUERYSTRING_EXPIRE
        server_config['AWS_QUERYSTRING_AUTH'] = settings.AWS_QUERYSTRING_AUTH

        # Token Conf
        server_config['ROTATE_REFRESH_TOKEN'] = settings.SIMPLE_JWT['ROTATE_REFRESH_TOKENS']
        server_config['ACCESS_TOKEN_LIFETIME'] = settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME']
        server_config['REFRESH_TOKEN_LIFETIME'] = settings.SIMPLE_JWT['REFRESH_TOKEN_LIFETIME']

        return Response({
            'version': server_version,
            'config': server_config
        }) 
Example #29
Source File: storage.py    From django2-project-template with MIT License 5 votes vote down vote up
def _open(self, name, mode='rb'):
        if self.exists(os.path.join(settings.MEDIA_ROOT, name)):
            return super()._open(name, mode)
        return File(open(self.file_not_found_image_path, mode)) 
Example #30
Source File: models.py    From osler with GNU General Public License v3.0 5 votes vote down vote up
def make_filepath(instance, filename):
    '''
        Produces a unique file path for the upload_to of a FileField. This is
        important because any URL is 1) transmitted unencrypted and 2)
        automatically referred to any libraries we include (i.e. Bootstrap,
        AngularJS).

        The produced path is of the form:
        "[model name]/[field name]/[random name].[filename extension]".

        Copypasta from https://djangosnippets.org/snippets/2819/
    '''


    field_name = 'image'
    carry_on = True
    while carry_on:
        new_filename = "%s.%s" % (User.objects.make_random_password(48),
                                  filename.split('.')[-1])
        #path = '/'.join([instance.__class__.__name__.lower(),field_name, new_filename])

        path = new_filename

        # if the file already exists, try again to generate a new filename
        carry_on = os.path.isfile(os.path.join(settings.MEDIA_ROOT, path))

    return path