Here are the examples of the python api django.conf.settings.MEDIA_ROOT taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
247 Examples
3
Source : admin_views.py
with GNU Affero General Public License v3.0
from 17thshard
with GNU Affero General Public License v3.0
from 17thshard
def index(request):
usage = shutil.disk_usage(settings.MEDIA_ROOT)
total_space_str = "{:.2f} Gb".format(usage.total / 1024**3)
used_space_str = "{:.2f} Gb".format(usage.used / 1024**3)
free_space_str = "{:.2f} Gb".format(usage.free / 1024**3)
return render(request, 'palanaeum/admin/admin_index.html',
{'used_space': usage.used, 'available_space': usage.free,
'total_space': usage.total, 'total_space_str': total_space_str,
'free_space_str': free_space_str, 'used_space_str': used_space_str})
@user_passes_test(lambda u: u.is_superuser, login_url="auth_login")
3
Source : models.py
with GNU Affero General Public License v3.0
from 17thshard
with GNU Affero General Public License v3.0
from 17thshard
def save_uploaded_file(self, uploaded_file: UploadedFile):
save_path = pathlib.Path(settings.MEDIA_ROOT, 'sources', str(self.event_id), uploaded_file.name)
if save_path.exists():
save_path = save_path.with_name("{}_{}{}".format(save_path.name, time.time(), save_path.suffix))
save_path.parent.mkdir(parents=True, exist_ok=True, mode=0o775)
with open(str(save_path), mode='wb') as save_file:
for chunk in uploaded_file.chunks():
save_file.write(chunk)
self.file = str(save_path.relative_to(settings.MEDIA_ROOT))
return
def delete(self, using=None, keep_parents=False):
3
Source : ai_file_tags.py
with MIT License
from ambient-innovation
with MIT License
from ambient-innovation
def filesize(value):
"""
Returns the filesize of the filename given in value
:param value:
:return filesize:
"""
try:
return os.path.getsize("%s%s" % (settings.MEDIA_ROOT, value))
except Exception:
return 0
3
Source : comicimporter.py
with GNU General Public License v3.0
from bpepple
with GNU General Public License v3.0
from bpepple
def create_arc_images(cls, db_obj, img_dir):
base_name = os.path.basename(db_obj.image.name)
old_image_path = settings.MEDIA_ROOT + '/images/' + base_name
db_obj.image = utils.resize_images(db_obj.image, img_dir,
NORMAL_IMG_WIDTH, NORMAL_IMG_HEIGHT)
db_obj.save()
os.remove(old_image_path)
# Only the Creators are using this right now.
@classmethod
3
Source : comicimporter.py
with GNU General Public License v3.0
from bpepple
with GNU General Public License v3.0
from bpepple
def create_images(cls, db_obj, img_dir):
base_name = os.path.basename(db_obj.image.name)
old_image_path = settings.MEDIA_ROOT + '/images/' + base_name
db_obj.image = utils.resize_images(db_obj.image, img_dir,
CREATOR_IMG_WIDTH, CREATOR_IMG_HEIGHT)
db_obj.save()
os.remove(old_image_path)
@classmethod
3
Source : views.py
with Apache License 2.0
from CARV-ICS-FORTH
with Apache License 2.0
from CARV-ICS-FORTH
def on_completion(self, uploaded_file, request):
'''
Placeholder method to define what to do when upload is complete.
'''
# Get user file domains.
file_domains = request.user.file_domains if not getattr(request.user, 'is_impersonate', False) else User.objects.get(pk=request.user.pk).file_domains
path_worker = file_domains[request.POST['domain']].path_worker(request.POST['path'].split('/'))
if path_worker.exists(uploaded_file.name):
Message.add(request, 'error', 'Can not add "%s". An item with the same name already exists.' % uploaded_file.name)
return
filename = os.path.join(settings.MEDIA_ROOT, uploaded_file.file.name)
path_worker.upload(filename, uploaded_file.name)
def get_response_data(self, chunked_upload, request):
3
Source : views.py
with Apache License 2.0
from CARV-ICS-FORTH
with Apache License 2.0
from CARV-ICS-FORTH
def get_response_data(self, chunked_upload, request):
'''
Data for the response. Should return a dictionary-like object.
Called *only* if POST is successful.
'''
filename = os.path.join(settings.MEDIA_ROOT, chunked_upload.file.name)
chunked_upload.delete(delete_file=os.path.exists(filename))
return {}
@staff_member_required
3
Source : views.py
with GNU General Public License v3.0
from cc0411
with GNU General Public License v3.0
from cc0411
def post(self,request):
if request.is_ajax():
p_name = request.POST.get('p_name')
name = request.POST.get('name')
file = os.path.join(p_name, name)
if os.path.exists(file):
content = ''
with open(file, 'r') as f:
for line in f.readlines():
content = content + line
relative_path = p_name.split('{}/{}/'.format(settings.MEDIA_ROOT, 'roles'))[-1] + '/' + name
return JsonResponse({'status': True, 'content': content, 'relative_path': relative_path})
else:
return JsonResponse({'status': False, 'msg': 'No such file or dictionary!'})
#更新role
class RoleUpdate(LoginRequiredMixin,View):
3
Source : admin.py
with MIT License
from djangocon
with MIT License
from djangocon
def twitter_card(self, instance):
source = ImageFile(instance.twitter_card_image)
path = thumb_storage.backend._get_thumbnail_filename(source, "300x200", {'format': 'PNG'})
full_path = os.path.join(settings.MEDIA_ROOT, path)
if os.path.exists(full_path):
os.unlink(full_path)
thumbnail = get_thumbnail(instance.twitter_card_image, "300x200", format="PNG")
settings.THUMBNAIL_FORCE_OVERWRITE = False
html = """ < a href="{url}" target="_blank"> < img src="{img}"> < /a>""".format(
url=instance.twitter_card_image.url,
img=thumbnail.url
)
return mark_safe(html)
twitter_card.short_description = "Twitter card"
3
Source : models.py
with MIT License
from djangocon
with MIT License
from djangocon
def twitter_card_path(instance, __):
relative_path = 'pretalx_utils/twitter_card_{}.png'.format(instance.submission.code)
# Delete any existing image
fullname = os.path.join(settings.MEDIA_ROOT, relative_path)
container_dir = os.path.dirname(fullname)
if not os.path.exists(container_dir):
os.makedirs(container_dir)
if os.path.exists(fullname):
os.remove(fullname)
return relative_path
class TalkExtraProperties(models.Model):
3
Source : serializers.py
with BSD 3-Clause "New" or "Revised" License
from DJWOMS
with BSD 3-Clause "New" or "Revised" License
from DJWOMS
def to_internal_value(self, value):
f = value.split("/").pop().split(".").pop(1)
if f == "jpeg" or f == "jpg" or f == "webp":
way = "tmp/img{}.j2p".format(value.split("/").pop().split(".").pop(0))
outputPath = os.path.joGin(settings.MEDIA_ROOT, way)
# quality = 50
try:
Image.open(settings.MEDIA_ROOT + "/" + way)
except:
im = Image.open(BASE_DIR + value[value.rfind('/media'):])
im.save(outputPath, 'JPEG', optimize=True, quality=60)
path = settings.MEDIA_URL[:settings.MEDIA_URL.find('media')] + outputPath[outputPath.rfind('media'):]
return path
else:
return value
class PhotoSerializer(serializers.ModelSerializer):
3
Source : celery_tasks.py
with MIT License
from doccano
with MIT License
from doccano
def export_dataset(project_id, file_format: str, export_approved=False):
project = get_object_or_404(Project, pk=project_id)
repository = create_repository(project)
writer = create_writer(file_format)(settings.MEDIA_ROOT)
service = ExportApplicationService(repository, writer)
filepath = service.export(export_approved)
return filepath
3
Source : snippet.py
with Apache License 2.0
from dockerizeme
with Apache License 2.0
from dockerizeme
def serve_media(request, file_path):
"""
Django view that serves a media file using X_ACCEL_REDIRECT_PREFIX if
USE_X_ACCEL_REDIRECT is enabled in settings, or django.views.static.serve
if not (for development and testing).
"""
if USE_X_ACCEL_REDIRECT:
response = HttpResponse('')
response['X-Accel-Redirect'] = join('/', X_ACCEL_REDIRECT_PREFIX, file_path)
response['Content-Type'] = ''
else:
response = serve(request, file_path, settings.MEDIA_ROOT)
return response
3
Source : admin.py
with MIT License
from dtcooper
with MIT License
from dtcooper
def changelist_view(self, request, extra_context=None):
extra_context = extra_context or {}
extra_context["disk_usage"] = shutil.disk_usage(settings.MEDIA_ROOT)
return super().changelist_view(request, extra_context=extra_context)
class AudioAssetAdminBase(admin.ModelAdmin):
3
Source : views.py
with MIT License
from ebysofyan
with MIT License
from ebysofyan
def import_user_view(request):
"""
The column of the excel file should be part of
[Username, Password, Email, First Name, Last Name]
"""
form = ImportFileForm(request.POST, request.FILES)
if form.is_valid():
filepath = os.path.join(
settings.MEDIA_ROOT, in_memory_file_to_temp(form.cleaned_data.get('document_file'))
)
task = import_user_task.delay(os.path.join(settings.MEDIA_ROOT, filepath))
return HttpResponse(json.dumps({"task_id": task.id}), content_type='application/json')
raise Http404
def get_progress_view(request):
3
Source : views.py
with MIT License
from Eeyhan
with MIT License
from Eeyhan
def upload(request):
"""富文本编辑,图片在线显示"""
img = request.FILES.get('upload_img')
path = os.path.join(settings.MEDIA_ROOT, 'article_img', img.name)
f = open(path, 'wb')
for biner in img:
f.write(biner)
f.close()
responese = {
'error': 0,
'url': 'media/article_img/%s' % img.name
}
return HttpResponse(json.dumps(responese))
3
Source : backup.py
with GNU General Public License v3.0
from erikdewildt
with GNU General Public License v3.0
from erikdewildt
def make_media_backup(self, destination=None, pattern=None):
"""Make a media backup."""
if not settings.MEDIA_ROOT:
logger.warning('Media root is not set, please check your Django settings')
return False
media_backup_filename = f'media_{pattern}.{self.media_backup_extension}'
with tarfile.open(f'{destination}/{media_backup_filename}', "w:gz") as backup_file:
for file in glob.iglob(f'{settings.MEDIA_ROOT}/**', recursive=True):
backup_file.add(file)
backup_file.close()
logger.info(f'Created Media backup of `{settings.MEDIA_ROOT}` to `{destination}/{media_backup_filename}`')
return f'{destination}/{media_backup_filename}'
#
# Main Rotating logic
#
def archive(self, backup_file=None):
3
Source : test_field.py
with BSD 3-Clause "New" or "Revised" License
from escaped
with BSD 3-Clause "New" or "Revised" License
from escaped
def remotestorage(mocker):
"""
Return a patched FileSystemStorage that does not support path()
"""
storage = FileSystemStorage()
def remote_open(name, mode):
media_image_path = Path(settings.MEDIA_ROOT) / IMAGE_NAME
return open(media_image_path, mode)
def remote_path():
raise NotImplementedError("Remote storage does not implement path()")
mocker.patch.object(storage, 'path', remote_path)
mocker.patch.object(storage, 'open', remote_open)
yield storage
@pytest.fixture
3
Source : test_apkpointer.py
with GNU Affero General Public License v3.0
from f-droid
with GNU Affero General Public License v3.0
from f-droid
def test_initialize(self):
self.apk.initialize(self.repo) # this calls self.apk_pointer.initialize()
# assert that global APK file has been linked/copied properly
self.assertEqual(get_apk_file_path(self.apk, self.apk_file_name), self.apk.file.name)
self.assertTrue(os.path.isfile(os.path.join(settings.MEDIA_ROOT, self.apk.file.name)))
# get the created Apk object and assert that it has been created properly
app = App.objects.get(pk=1)
self.assertEqual(self.apk_pointer.repo, app.repo)
self.assertEqual(self.apk.package_id, app.package_id)
self.assertEqual([settings.LANGUAGE_CODE], list(app.get_available_languages()))
# assert that the app icon has been created properly
icon_name = app.package_id + '.' + str(self.apk.version_code) + '.png'
self.assertTrue(app.icon.name.endswith(icon_name))
self.assertTrue(os.path.isfile(app.icon.path))
def test_initialize_reuses_existing_app(self):
3
Source : test_remoterepository.py
with GNU Affero General Public License v3.0
from f-droid
with GNU Affero General Public License v3.0
from f-droid
def test_get_path(self):
self.assertEqual(os.path.join(settings.MEDIA_ROOT, 'remote_repo_1'),
self.remote_repo.get_path())
with self.assertRaises(NotImplementedError):
AbstractRepository().get_repo_path()
def test_initial_update(self):
3
Source : test_storage.py
with GNU Affero General Public License v3.0
from f-droid
with GNU Affero General Public License v3.0
from f-droid
def test_publish(self, push, bar):
# create an empty fake repo
os.chdir(settings.MEDIA_ROOT)
os.mkdir(REPO_DIR)
# publish to git remote storage
self.storage.publish()
# assert that git mirror directory exist and that the repo was pushed
self.assertTrue(os.path.isdir(os.path.join(settings.MEDIA_ROOT, 'git-mirror')))
self.assertTrue(push.called)
bar.called = None # we don't care a about the progress bar, but have to use it
class StorageManagerTestCase(TestCase):
3
Source : test_finders.py
with Apache License 2.0
from gethue
with Apache License 2.0
from gethue
def setUp(self):
super(TestDefaultStorageFinder, self).setUp()
self.finder = finders.DefaultStorageFinder(
storage=storage.StaticFilesStorage(location=settings.MEDIA_ROOT))
test_file_path = os.path.join(settings.MEDIA_ROOT, 'media-file.txt')
self.find_first = ('media-file.txt', test_file_path)
self.find_all = ('media-file.txt', [test_file_path])
@override_settings(
3
Source : test_e2e.py
with BSD 2-Clause "Simplified" License
from getmetamapper
with BSD 2-Clause "Simplified" License
from getmetamapper
def clean_uploads_folder(datastore_id, run_id):
"""Once the tests have ran, we should remove all files from `uploads/` directory.
"""
root_dir = os.path.join(settings.MEDIA_ROOT, 'uploads', 'revisioner')
run_path = os.path.join(root_dir, datastore_id, 'run_id=%s' % run_id)
if os.path.isdir(run_path):
shutil.rmtree(run_path)
class End2EndRevisionerTests(TestCase):
3
Source : views.py
with BSD 3-Clause "New" or "Revised" License
from GhostManager
with BSD 3-Clause "New" or "Revised" License
from GhostManager
def download_archive(request, pk):
"""
Return the target :model:`reporting.Report` archive file for download.
"""
archive_instance = Archive.objects.get(pk=pk)
file_path = os.path.join(settings.MEDIA_ROOT, archive_instance.report_archive.path)
if os.path.exists(file_path):
with open(file_path, "rb") as archive_file:
response = HttpResponse(
archive_file.read(), content_type="application/x-zip-compressed"
)
response["Content-Disposition"] = "attachment; filename=" + os.path.basename(
file_path
)
return response
raise Http404
@login_required
3
Source : views.py
with BSD 3-Clause "New" or "Revised" License
from GhostManager
with BSD 3-Clause "New" or "Revised" License
from GhostManager
def get(self, *args, **kwargs):
self.object = self.get_object()
file_path = os.path.join(settings.MEDIA_ROOT, self.object.document.path)
if os.path.exists(file_path):
return FileResponse(
open(file_path, "rb"),
as_attachment=True,
filename=os.path.basename(file_path),
)
raise Http404
class GenerateReportJSON(LoginRequiredMixin, SingleObjectMixin, View):
3
Source : models.py
with Apache License 2.0
from heartexlabs
with Apache License 2.0
from heartexlabs
def upload_name_generator(instance, filename):
project = str(instance.project_id)
project_dir = os.path.join(settings.MEDIA_ROOT, settings.UPLOAD_DIR, project)
os.makedirs(project_dir, exist_ok=True)
path = settings.UPLOAD_DIR + '/' + project + '/' + str(uuid.uuid4())[0:8] + '-' + filename
return path
class FileUpload(models.Model):
3
Source : services.py
with MIT License
from hermanTenuki
with MIT License
from hermanTenuki
def _generate_unique_image_path(file_extension, r=0, r_max=10):
"""
Recursive function that generates random, but unique file name and path.
:return: Full path to file, name with extension. Return 2 nones if too many recursions.
"""
name = ''.join(random.choices(string.ascii_lowercase + string.digits, k=20))
full_name = f'{name}{file_extension}'
full_path = os.path.join(settings.MEDIA_ROOT, 'input_images/', full_name)
if os.path.exists(full_path):
if r >= r_max:
return None, None
full_path, full_name = GeneratedASCIIService._generate_unique_image_path(file_extension, r=r + 1)
return full_path, full_name
@staticmethod
3
Source : download_extras.py
with BSD 3-Clause "New" or "Revised" License
from ietf-tools
with BSD 3-Clause "New" or "Revised" License
from ietf-tools
def handle(self, *filenames, **options):
for src, dst in (
('rsync.ietf.org::dev.media/', settings.MEDIA_ROOT), ):
if src and dst:
if not dst.endswith(os.pathsep):
dst += os.pathsep
subprocess.call(('rsync', '-auz', '--info=progress2', src, dst))
3
Source : 0014_document_checksum.py
with GNU General Public License v3.0
from jonaswinkler
with GNU General Public License v3.0
from jonaswinkler
def source_path(self):
return os.path.join(
settings.MEDIA_ROOT,
"documents",
"originals",
"{:07}.{}.gpg".format(self.pk, self.file_type)
)
@property
3
Source : items_images.py
with GNU General Public License v3.0
from Kivou-2000607
with GNU General Public License v3.0
from Kivou-2000607
def handle(self, **options):
print(f"[CRON {logdate()}] START items_images")
for item in Item.objects.all():
image_file = os.path.join(os.path.join(settings.MEDIA_ROOT, "items"), f'{item.tId}.png')
if not os.path.isfile(image_file):
print(f"Missing image for {item}")
print(image_file)
image_url = f"https://www.torn.com/images/items/{item.tId}/large.png"
r = requests.get(image_url, stream = True)
r.raw.decode_content = True
with open(image_file,'wb') as f:
shutil.copyfileobj(r.raw, f)
# print(image_file, is_file)
print(f"[CRON {logdate()}] END")
3
Source : utils.py
with Apache License 2.0
from ldv-klever
with Apache License 2.0
from ldv-klever
def setUp(self):
if not os.path.exists(os.path.join(settings.MEDIA_ROOT, TESTS_DIR)):
os.makedirs(os.path.join(settings.MEDIA_ROOT, TESTS_DIR).encode("utf8"))
self.client = Client()
super(KleverTestCase, self).setUp()
def tearDown(self):
3
Source : utils.py
with Apache License 2.0
from ldv-klever
with Apache License 2.0
from ldv-klever
def tearDown(self):
super(KleverTestCase, self).tearDown()
try:
shutil.rmtree(os.path.join(settings.MEDIA_ROOT, TESTS_DIR))
except PermissionError:
pass
def has_references(obj):
3
Source : Download.py
with Apache License 2.0
from ldv-klever
with Apache License 2.0
from ldv-klever
def __iter__(self):
for file_inst in FileSystem.objects.filter(decision=self.decision).select_related('file'):
arch_name = '/'.join(['root', file_inst.name])
file_src = '/'.join([settings.MEDIA_ROOT, file_inst.file.file.name])
for data in self.stream.compress_file(file_src, arch_name):
yield data
yield self.stream.close_stream()
class JobArchiveGenerator:
3
Source : test.py
with Apache License 2.0
from ldv-klever
with Apache License 2.0
from ldv-klever
def tearDown(self):
if os.path.exists(os.path.join(settings.MEDIA_ROOT, self.safe_archive)):
os.remove(os.path.join(settings.MEDIA_ROOT, self.safe_archive))
if os.path.exists(os.path.join(settings.MEDIA_ROOT, self.unsafe_archive)):
os.remove(os.path.join(settings.MEDIA_ROOT, self.unsafe_archive))
if os.path.exists(os.path.join(settings.MEDIA_ROOT, self.unknown_archive)):
os.remove(os.path.join(settings.MEDIA_ROOT, self.unknown_archive))
if os.path.exists(os.path.join(settings.MEDIA_ROOT, self.test_tagsfile)):
os.remove(os.path.join(settings.MEDIA_ROOT, self.test_tagsfile))
if os.path.exists(os.path.join(settings.MEDIA_ROOT, self.all_marks_arch)):
os.remove(os.path.join(settings.MEDIA_ROOT, self.all_marks_arch))
super(TestMarks, self).tearDown()
3
Source : models.py
with Apache License 2.0
from ldv-klever
with Apache License 2.0
from ldv-klever
def add_archive(self, fp, save=False):
self.archive.save(REPORT_ARCHIVE['original_sources'], File(fp), save)
if not os.path.isfile(os.path.join(settings.MEDIA_ROOT, self.archive.name)):
raise RuntimeError('OriginalSources.archive was not saved')
class Meta:
3
Source : models.py
with Apache License 2.0
from ldv-klever
with Apache License 2.0
from ldv-klever
def add_archive(self, fp, save=False):
self.archive.save(REPORT_ARCHIVE['additional_sources'], File(fp), save)
if not os.path.isfile(os.path.join(settings.MEDIA_ROOT, self.archive.name)):
raise RuntimeError('AdditionalSources.archive was not saved')
class Meta:
3
Source : models.py
with Apache License 2.0
from ldv-klever
with Apache License 2.0
from ldv-klever
def add_log(self, fp, save=False):
self.log.save(REPORT_ARCHIVE['log'], File(fp), save)
if not os.path.isfile(os.path.join(settings.MEDIA_ROOT, self.log.name)):
raise RuntimeError('ReportComponent.log was not saved')
def add_verifier_files(self, fp, save=False):
3
Source : models.py
with Apache License 2.0
from ldv-klever
with Apache License 2.0
from ldv-klever
def add_verifier_files(self, fp, save=False):
self.verifier_files.save(REPORT_ARCHIVE['verifier_files'], File(fp), save)
if not os.path.isfile(os.path.join(settings.MEDIA_ROOT, self.verifier_files.name)):
raise RuntimeError('ReportComponent.verifier_files was not saved')
class Meta:
3
Source : models.py
with Apache License 2.0
from ldv-klever
with Apache License 2.0
from ldv-klever
def add_trace(self, fp, save=False):
self.error_trace.save(REPORT_ARCHIVE['error_trace'], File(fp), save)
if not os.path.isfile(os.path.join(settings.MEDIA_ROOT, self.error_trace.name)):
raise RuntimeError('ReportUnsafe.error_trace was not saved')
class Meta:
3
Source : models.py
with Apache License 2.0
from ldv-klever
with Apache License 2.0
from ldv-klever
def add_problem_desc(self, fp, save=False):
self.problem_description.save(REPORT_ARCHIVE['problem_description'], File(fp), save)
if not os.path.isfile(os.path.join(settings.MEDIA_ROOT, self.problem_description.name)):
raise RuntimeError('ReportUnknown.problem_description was not saved')
class Meta:
3
Source : test.py
with Apache License 2.0
from ldv-klever
with Apache License 2.0
from ldv-klever
def tearDown(self):
if os.path.exists(os.path.join(settings.MEDIA_ROOT, self.job_archive)):
os.remove(os.path.join(settings.MEDIA_ROOT, self.job_archive))
super().tearDown()
class ResponseError(Exception):
3
Source : test.py
with Apache License 2.0
from ldv-klever
with Apache License 2.0
from ldv-klever
def __init__(self):
self.session = requests.Session()
self.root_dir = os.path.join(settings.MEDIA_ROOT, 'images')
# Authenticate
resp = self.__request('/service/get_token/', data={'username': 'service', 'password': 'service'})
self.session.headers.update({'Authorization': 'Token {}'.format(resp.json()['token'])})
self.create_images()
def create_images(self):
3
Source : utils.py
with Apache License 2.0
from ldv-klever
with Apache License 2.0
from ldv-klever
def __clear_files_with_ref(self, model, files_dir):
objects_without_relations(model).delete()
files_in_the_system = set()
to_delete = set()
for instance in model.objects.all():
# file_path = os.path.abspath(os.path.join(settings.MEDIA_ROOT, f.file.name))
for file_path in self.__files_paths(instance):
files_in_the_system.add(file_path)
if not (os.path.exists(file_path) and os.path.isfile(file_path)):
logger.error('Deleted from DB (file not exists): {}'.format(
os.path.relpath(file_path, settings.MEDIA_ROOT)
), stack_info=True)
to_delete.add(instance.pk)
model.objects.filter(id__in=to_delete).delete()
self.__clear_unused_files(files_dir, files_in_the_system)
def __files_paths(self, instance):
3
Source : utils.py
with Apache License 2.0
from ldv-klever
with Apache License 2.0
from ldv-klever
def __clear_service_files(self):
files_in_the_system = set()
for s in Solution.objects.values_list('archive', flat=True):
files_in_the_system.add(os.path.abspath(os.path.join(settings.MEDIA_ROOT, s)))
for s in Task.objects.values_list('archive', flat=True):
files_in_the_system.add(os.path.abspath(os.path.join(settings.MEDIA_ROOT, s)))
self.__clear_unused_files(SERVICE_DIR, files_in_the_system)
def __clear_unused_files(self, files_dir, excluded: set):
3
Source : utils.py
with Apache License 2.0
from ldv-klever
with Apache License 2.0
from ldv-klever
def __clear_unused_files(self, files_dir, excluded: set):
files_directory = os.path.join(settings.MEDIA_ROOT, files_dir)
if os.path.isdir(files_directory):
files_on_disk = set(os.path.abspath(os.path.join(files_directory, x)) for x in os.listdir(files_directory))
for f in files_on_disk - excluded:
os.remove(f)
class RecalculateLeaves:
3
Source : runtests.py
with BSD 3-Clause "New" or "Revised" License
from linuxsoftware
with BSD 3-Clause "New" or "Revised" License
from linuxsoftware
def cleanMedia():
mediaDir = settings.MEDIA_ROOT
imgDir = os.path.join(mediaDir, "images")
origImgDir = os.path.join(mediaDir, "original_images")
for path in glob(os.path.join(imgDir, "*")) + glob(os.path.join(origImgDir, "*")):
try:
os.remove(path)
except:
print("Error deleting", path)
def runPytest():
3
Source : storage.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def __init__(self, location=None, base_url=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
self.base_url = base_url
def _open(self, name, mode='rb'):
3
Source : tests.py
with Apache License 2.0
from lumanjiao
with Apache License 2.0
from lumanjiao
def setUp(self):
super(TestDefaultStorageFinder, self).setUp()
self.finder = finders.DefaultStorageFinder(
storage=storage.StaticFilesStorage(location=settings.MEDIA_ROOT))
test_file_path = os.path.join(settings.MEDIA_ROOT, 'media-file.txt')
self.find_first = ('media-file.txt', test_file_path)
self.find_all = ('media-file.txt', [test_file_path])
class TestMiscFinder(TestCase):
3
Source : signals.py
with Apache License 2.0
from MaltoseEditor
with Apache License 2.0
from MaltoseEditor
def del_image(sender, instance, **kwargs):
if str(instance.file):
image = os.path.join(settings.MEDIA_ROOT, str(instance.file))
if os.path.exists(image):
os.remove(image)
@receiver(post_init, sender=Article)
3
Source : receivers.py
with MIT License
from mangadventure
with MIT License
from mangadventure
def _move(old_dir: str, new_dir: str):
new_path = settings.MEDIA_ROOT / new_dir
if not new_path.exists():
old_path = settings.MEDIA_ROOT / old_dir
old_path.rename(new_path)
@receiver(pre_save, sender=Series)
See More Examples