我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.conf.settings.MEDIA_URL。
def buildFastQCDetails(sampleData): """Builds the html to embed the fastQC summary pdf. HTML for the fastQC pdf tab in /gsuStats/run/<run name> drop downs Called by sampleAjax. """ #create the strings name_str = '<h1>Sample: %s (%s)</h1>' \ % (sampleData.sampleName, sampleData.sampleReference) #table_str = '<table class="psteptable">' fastQCFile = sampleData.fastQCSummary #embed the pdf fastQCHTML = "<embed height=\"400\" width=\"100%%\" name=\"plugin\" \ src=\"%s%s\" type=\"application/pdf\">" %(settings.MEDIA_URL, fastQCFile) #fastQCline = "<a href=\"javascript:void(null);\" onclick=\"pdfPopup();\">Open</a>" returnString = name_str + fastQCHTML return(returnString)
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 )
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")
def is_locale_independent(path): """ Returns whether the path is locale-independent. """ if (localeurl_settings.LOCALE_INDEPENDENT_MEDIA_URL and settings.MEDIA_URL and path.startswith(settings.MEDIA_URL)): return True if (localeurl_settings.LOCALE_INDEPENDENT_STATIC_URL and getattr(settings, "STATIC_URL", None) and path.startswith(settings.STATIC_URL)): return True for regex in localeurl_settings.LOCALE_INDEPENDENT_PATHS: if regex.search(path): return True return False
def get(self, request, *args, **kwargs): path = kwargs.get("path") # No path? You're boned. Move along. if not path: raise Http404 if self._is_url(path): content = requests.get(path, stream=True).raw.read() else: # Normalise the path to strip out naughty attempts path = os.path.normpath(path).replace( settings.MEDIA_URL, settings.MEDIA_ROOT, 1) # Evil path request! if not path.startswith(settings.MEDIA_ROOT): raise Http404 # The file requested doesn't exist locally. A legit 404 if not os.path.exists(path): raise Http404 with open(path, "rb") as f: content = f.read() content = Cryptographer.decrypted(content) return HttpResponse( content, content_type=magic.Magic(mime=True).from_buffer(content))
def export(self, request, queryset): """ Download selected photos as ZIP """ zip_subdir = 'photos' zip_filename = '{}.zip'.format(zip_subdir) zip_file = os.path.join(settings.MEDIA_ROOT, PHOTOLOGUE_DIR, zip_filename) try: os.remove(zip_file) except OSError: pass with zipfile.ZipFile(zip_file, "a") as zf: for photo in queryset.all(): path = photo.image.path if os.path.isfile(path): fdir, fname = os.path.split(path) zip_path = os.path.join(zip_subdir, fname) zf.write(path, zip_path) link = 'Photos download link: <a href="{0}?v={1}">{0}</a>'.format( urllib.parse.urljoin(settings.MEDIA_URL, PHOTOLOGUE_DIR + '/' + zip_filename), time()) messages.add_message(request, messages.INFO, mark_safe(link))
def get_css_content(handler, content, **kwargs): # Add $MEDIA_URL variable to CSS files content = content.replace('$MEDIA_URL/', settings.MEDIA_URL) # Remove @charset rules content = re.sub(r'@charset(.*?);', '', content) if not isinstance(handler, basestring): return content def fixurls(path): # Resolve ../ paths path = '%s%s/%s' % (settings.MEDIA_URL, os.path.dirname(handler % dict(kwargs)), path.group(1)) while path_re.search(path): path = path_re.sub('/', path, 1) return 'url("%s")' % path # Make relative paths work with MEDIA_URL content = re.sub(r'url\s*\(["\']?([\w\.][^:]*?)["\']?\)', fixurls, content) return content
def thumbnail_image_tag(self): if not self.thumbnail: return format_html('<span>No image to preview</span>') media_url = settings.MEDIA_URL if settings.USE_S3: media_url = 'https://{domain}/{bucket}/'.format( domain=settings.AWS_S3_CUSTOM_DOMAIN, bucket=settings.AWS_LOCATION ) html = '<img src="{media_url}{src}" style="width:25%">'.format( media_url=media_url, src=self.thumbnail ) return format_html(html)
def test_creation(self): self.assertEqual(self.image.__str__(), 'LC80010012015001LGN00_B4.TIF') self.assertEqual( self.image.file_path(), join(settings.MEDIA_ROOT, 'L8/LC80010012015001LGN00/LC80010012015001LGN00_B4.TIF') ) self.assertTrue(self.image.file_exists()) self.assertEqual( self.image.url(), join(settings.MEDIA_URL, 'L8/LC80010012015001LGN00/LC80010012015001LGN00_B4.TIF') ) Image.objects.create( name='LC80010012015001LGN00_B5.TIF', type='B5', scene=self.scene ) self.assertEqual(Image.objects.all().count(), 2) self.assertEqual(self.scene.images.count(), 2)
def parse_download_image(self, response): # url = "http://postfiles1.naver.net/20141204_160/kdk926_14176651128371lr8c_JPEG/20141203_110254.jpg?type=w2" # file_name = 'D:/workspace/DjangoProjects/BlogWorkspace/aquam/media/images/abcd.jpg' download_local_url = settings.BASE_DIR + '/media/images/' #mac test # download_local_url = settings.MEDIA_ROOT + '/images/' #ubuntu replace_item = response for i in range(0, response.count('src="')): temp = response.split('src="')[i+1] url = temp.split('"')[0] file_name = url.split('/')[-1].split('?')[0].replace('%', '') download_url = download_local_url + file_name media_url = settings.MEDIA_URL + 'images/' + file_name replace_item = str(replace_item).replace(url, media_url) if ImageItem.django_model.objects.filter(file='images/' + file_name).count() == 0: #??? ???? urllib.request.urlretrieve(url, download_url) #??? ???? return replace_item
def test_annotation_action_get_empty(self): response = self.test_client.get(reverse('annotation-action', kwargs={'sound_id': self.sound.id, 'tier_id': self.tier.id})) self.assertEqual(response.status_code, 200) response_data = response.json() # no segments are created self.assertEqual(response_data['task']['segments'], []) # create annotation in reference sound that should be in the response reference_annotation = Annotation.objects.create(name='reference_annotation', start_time=1.000, end_time=2.000, sound=self.reference_sound, tier=self.tier, user=self.user) response = self.test_client.get(reverse('annotation-action', kwargs={'sound_id': self.sound.id, 'tier_id': self.tier.id})) self.assertEqual(response.json()['task']['segments_ref'][0]['annotation'], reference_annotation.name) self.assertEqual(float(response.json()['task']['segments_ref'][0]['start']), reference_annotation.start_time) self.assertEqual(float(response.json()['task']['segments_ref'][0]['end']), reference_annotation.end_time) self.assertEqual(response.json()['task']['url'], os.path.join(settings.MEDIA_URL, self.data_set.name, self.exercise.name, self.sound.filename))
def get_picture(self): no_picture = 'http://localhost:8000/static/img/user.png' try: filename = django_settings.MEDIA_ROOT+'/webuser_pictures/'+self.user.username+'.jpg' picture_url = django_settings.MEDIA_URL+'webuser_pictures/'+self.user.username+'.jpg' if os.path.isfile(filename): return picture_url else: # gravatar_url = u'http://www.gravatar.com/avatar/{0}?{1}'.format( # hashlib.md5(self.user.email.lower()).hexdigest(), # urllib.urlencode({'d':no_picture, 's':'256'}) # ) gravatar_url='http://localhost:8000/static/img/user1.png' return gravatar_url except Exception, e: return no_picture
def print_qr_code(request, user_id, product_id): item = Item.objects.get(pk=signer.unsign(product_id)) qr_filename = str(item.pk) + ".png" save = False if item.qr_code is None: #new item! save = True url = "/users/" + str(user_id) + "/found/" + str(product_id) uri = request.build_absolute_uri(url) item.qr_code = uri item.save() url = item.qr_code qr = QRCode(version=20, error_correction=ERROR_CORRECT_M) qr.add_data(url) qr.make() img = qr.make_image() if save: img.save(settings.MEDIA_ROOT + qr_filename) #TODO: In production, we have to check where the QR image is being saved template_url = settings.MEDIA_URL + qr_filename return render(request, 'lostnfound/qr_code.html', {'qr_url': template_url , 'item': item}) #A user wants to change an item's settings
def render(self, name, value, attrs=None): if value is None: value = '' final_attrs = self.build_attrs(attrs, type=self.input_type, name=name) if value != '': try: final_attrs['value'] = \ force_unicode(value.strftime(self.dformat)) except: final_attrs['value'] = \ force_unicode(value) if not final_attrs.has_key('id'): final_attrs['id'] = u'%s_id' % (name) id = final_attrs['id'] jsdformat = self.dformat #.replace('%', '%%') cal = calbtn % (settings.MEDIA_URL, id, id, jsdformat, id) a = u'<input%s />%s%s' % (forms.util.flatatt(final_attrs), self.media, cal) return mark_safe(a)