當前位置: 首頁>>代碼示例>>Python>>正文


Python settings.MEDIA_ROOT屬性代碼示例

本文整理匯總了Python中django.conf.settings.MEDIA_ROOT屬性的典型用法代碼示例。如果您正苦於以下問題:Python settings.MEDIA_ROOT屬性的具體用法?Python settings.MEDIA_ROOT怎麽用?Python settings.MEDIA_ROOT使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在django.conf.settings的用法示例。


在下文中一共展示了settings.MEDIA_ROOT屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: save

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MEDIA_ROOT [as 別名]
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 
開發者ID:ideascube,項目名稱:ideascube,代碼行數:19,代碼來源:forms.py

示例2: download_annotated

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MEDIA_ROOT [as 別名]
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 
開發者ID:raonyguimaraes,項目名稱:mendelmd,代碼行數:24,代碼來源:views.py

示例3: check_settings

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MEDIA_ROOT [as 別名]
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") 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:20,代碼來源:utils.py

示例4: __init__

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MEDIA_ROOT [as 別名]
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
        ) 
開發者ID:lanbing510,項目名稱:GTDWeb,代碼行數:21,代碼來源:storage.py

示例5: test21

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MEDIA_ROOT [as 別名]
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!') 
開發者ID:HaoZhang95,項目名稱:Python24,代碼行數:26,代碼來源:views.py

示例6: do_download_archive

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MEDIA_ROOT [as 別名]
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 
開發者ID:certsocietegenerale,項目名稱:FIR,代碼行數:23,代碼來源:files.py

示例7: get_available_name

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MEDIA_ROOT [as 別名]
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 
開發者ID:znick,項目名稱:anytask,代碼行數:24,代碼來源:storage.py

示例8: test_status_create_with_image

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MEDIA_ROOT [as 別名]
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) 
開發者ID:codingforentrepreneurs,項目名稱:REST-API,代碼行數:23,代碼來源:tests.py

示例9: test_status_create_with_img_and_desc

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MEDIA_ROOT [as 別名]
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) 
開發者ID:codingforentrepreneurs,項目名稱:REST-API,代碼行數:23,代碼來源:tests.py

示例10: write_to_package_job

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MEDIA_ROOT [as 別名]
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) 
開發者ID:82Flex,項目名稱:DCRM,代碼行數:25,代碼來源:version.py

示例11: check_settings

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MEDIA_ROOT [as 別名]
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") 
開發者ID:reBiocoder,項目名稱:bioforum,代碼行數:19,代碼來源:utils.py

示例12: detect_outliers

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MEDIA_ROOT [as 別名]
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}) 
開發者ID:MateLabs,項目名稱:AutoOut,代碼行數:26,代碼來源:views.py

示例13: get_data

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MEDIA_ROOT [as 別名]
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) 
開發者ID:MateLabs,項目名稱:AutoOut,代碼行數:22,代碼來源:views.py

示例14: get_treated_data

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MEDIA_ROOT [as 別名]
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) 
開發者ID:MateLabs,項目名稱:AutoOut,代碼行數:20,代碼來源:views.py

示例15: get_dataset_properties

# 需要導入模塊: from django.conf import settings [as 別名]
# 或者: from django.conf.settings import MEDIA_ROOT [as 別名]
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}) 
開發者ID:MateLabs,項目名稱:AutoOut,代碼行數:27,代碼來源:views.py


注:本文中的django.conf.settings.MEDIA_ROOT屬性示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。