def get_thumbnail(instance, size, method='crop'):
size_name = '%s__%s' % (method, size)
if instance:
if (size_name not in AVAILABLE_SIZES and not
settings.VERSATILEIMAGEFIELD_SETTINGS['create_images_on_demand']):
msg = ('Thumbnail size %s is not defined in settings '
'and it won\'t be generated automatically' % size_name)
warnings.warn(msg)
try:
if method == 'crop':
thumbnail = instance.crop[size]
else:
thumbnail = instance.thumbnail[size]
except:
logger.exception('Thumbnail fetch failed',
extra={'instance': instance, 'size': size})
else:
return thumbnail.url
return static(choose_placeholder(size))
python类static()的实例源码
def render(self, context=None, request=None):
"""
Render the template with a given context. Here we're adding
some context variables that are required for all templates in
the system like the statix url and the CSRF tokens, etc.
:param context: It must be a dict if provided
:param request: It must be a django.http.HttpRequest if provided
:return: A rendered template
"""
if context is None:
context = {}
if request is not None:
# As Django doesn't have a global request object,
# it's useful to put it in the context.
context['request'] = request
# Passing the CSRF token is mandatory.
context['csrf_input'] = csrf_input_lazy(request)
context['csrf_token'] = csrf_token_lazy(request)
context['static'] = static
context['url'] = reverse
return self.template.render(**context)
def get_context_data(self, **kwargs):
context = super(ChartIconMixin, self).get_context_data(**kwargs)
# Get all the template icons and them in a dict we can use as a
# lookup
icons = Template.objects.defer('data')
icon_lookup = {i.title: i.icon for i in icons}
default_icon = static('chartwerk/img/chartwerk_100.png')
for chart in context[self.context_object_name]:
tpl_title = chart.data['template']['title']
# If the chart template isn't found or it's icon field is null,
# use default
if not icon_lookup.get(tpl_title):
chart.icon = default_icon
else:
chart.icon = icon_lookup[tpl_title].url
return context
def render_static_string(url):
"""Render static strings.
Opens dependency files and renders them into a string for injection
or returns the url string.
"""
try:
return {
'script': urlopen(url).read().decode('UTF-8'),
'inject': True
}
except:
return {
'url': url,
'inject': False
}
def send_postponed(self, meeting, postponed_date, reason):
text = "There will be *no* group meeting next week (%A, %b %d, %Y)"
text = postponed_date.strftime(text) + ("%s.\n" % reason.lower())
text += "The next group meeting has been postponed to "
text += meeting.date.strftime("%A, %b %d, %Y. ")
text += "Presenters will be %s." % get_text_list(
map(unicode, meeting.presenters.all()), 'and'
)
attachments = [{
"fallback": "Go %s for detail." % _url(meeting.get_absolute_url()),
"actions": [{
"type": "button",
"text": "Detail",
"url": _url(meeting.get_absolute_url()),
}]
}]
return unicode(self("chat.postMessage",
text=text,
attachments=attachments,
icon_url=_url(static('slack/presentation.png')),
username='Meeting Bot',
))
def rawlayout_pdf(request, pdf):
doc = to_doc(as_path(pdf))
script_params = {
'pdfPath': reverse('raw_pdf', kwargs={'pdf': pdf}),
'workerSrc': static('ombpdf/js/pdf.worker.bundle.js'),
}
html, ctx = rawlayout.to_html(doc)
return render(request, 'ombpdf/rawlayout.html', {
'doc': doc,
'html': SafeString(html),
'script_params': SafeString(json.dumps(script_params)),
**ctx,
})
def gameplay_context(game, token):
if game.current_round > 1:
# gif from last player
received_gif = game.gameround_set.get(round_number=game.current_round - 1).giphy_url
else:
# if roundnumber of game is 1 (first turn)
received_gif = ""
try:
game_round = game.gameround_set.get(round_number=game.current_round)
gif = game_round.giphy_url
phrase = game_round.user_text
# no phrase has been entered by the player yet
except:
gif = static('img/giphy_static.gif')
phrase = ""
context = {
'token': token,
'game': game,
'gif': gif,
'phrase': phrase,
'received_gif': received_gif
}
return context
# Creates context for multiplayer games
def icons(self):
r = {}
if getattr(self, '_icon', False):
for size in FILER_ADMIN_ICON_SIZES:
try:
r[size] = static("filer/icons/%s_%sx%s.png" % (
self._icon, size, size))
except ValueError:
# Do not raise an exception while trying to call static()
# on non-existent icon file. This avoids the issue with
# rendering parts of the template as empty blocks that
# happens on an attempt to access object 'icons' attribute
# in template.
pass
return r
def static(path):
global _static
if _static is None:
if apps.is_installed('django.contrib.staticfiles'):
from django.contrib.staticfiles.templatetags.staticfiles import static as _static
else:
from django.templatetags.static import static as _static
return _static(path)
def test_get_thumbnail_no_instance(monkeypatch):
"""When no instance, function should return placeholder"""
monkeypatch.setattr(
'saleor.product.templatetags.product_images.choose_placeholder',
lambda x: 'placeholder')
output = get_thumbnail(instance=None, size='10x10', method='crop')
assert output == static('placeholder')
def xstatic(*tags):
from .vendors import vendors
node = vendors
fs = []
lang = get_language()
cls_str = str if six.PY3 else basestring
for tag in tags:
try:
for p in tag.split('.'):
node = node[p]
except Exception as e:
if tag.startswith('xadmin'):
file_type = tag.split('.')[-1]
if file_type in ('css', 'js'):
node = "xadmin/%s/%s" % (file_type, tag)
else:
raise e
else:
raise e
if isinstance(node, cls_str):
files = node
else:
mode = 'dev'
if not settings.DEBUG:
mode = getattr(settings, 'STATIC_USE_CDN',
False) and 'cdn' or 'production'
if mode == 'cdn' and mode not in node:
mode = 'production'
if mode == 'production' and mode not in node:
mode = 'dev'
files = node[mode]
files = type(files) in (list, tuple) and files or [files, ]
fs.extend([f % {'lang': lang.replace('_', '-')} for f in files])
return [f.startswith('http://') and f or static(f) for f in fs]
def xstatic(*tags):
from vendors import vendors
node = vendors
fs = []
lang = get_language()
for tag in tags:
try:
for p in tag.split('.'):
node = node[p]
except Exception, e:
if tag.startswith('xadmin'):
file_type = tag.split('.')[-1]
if file_type in ('css', 'js'):
node = "xadmin/%s/%s" % (file_type, tag)
else:
raise e
else:
raise e
if type(node) in (str, unicode):
files = node
else:
mode = 'dev'
if not settings.DEBUG:
mode = getattr(settings, 'STATIC_USE_CDN',
False) and 'cdn' or 'production'
if mode == 'cdn' and mode not in node:
mode = 'production'
if mode == 'production' and mode not in node:
mode = 'dev'
files = node[mode]
files = type(files) in (list, tuple) and files or [files, ]
fs.extend([f % {'lang': lang.replace('_', '-')} for f in files])
return [f.startswith('http://') and f or static(f) for f in fs]
def public_path(request):
"""
Return the correct public_path for Webpack to use
"""
if settings.USE_WEBPACK_DEV_SERVER:
return ensure_trailing_slash(webpack_dev_server_url(request))
else:
return ensure_trailing_slash(static("bundles/"))
def xstatic(*tags):
from .vendors import vendors
node = vendors
fs = []
lang = get_language()
cls_str = str if six.PY3 else basestring
for tag in tags:
try:
for p in tag.split('.'):
node = node[p]
except Exception as e:
if tag.startswith('xadmin'):
file_type = tag.split('.')[-1]
if file_type in ('css', 'js'):
node = "xadmin/%s/%s" % (file_type, tag)
else:
raise e
else:
raise e
if isinstance(node, cls_str):
files = node
else:
mode = 'dev'
if not settings.DEBUG:
mode = getattr(settings, 'STATIC_USE_CDN',
False) and 'cdn' or 'production'
if mode == 'cdn' and mode not in node:
mode = 'production'
if mode == 'production' and mode not in node:
mode = 'dev'
files = node[mode]
files = type(files) in (list, tuple) and files or [files, ]
fs.extend([f % {'lang': lang.replace('_', '-')} for f in files])
return [f.startswith('http://') and f or static(f) for f in fs]
def get_image_url(self):
if self.image:
return self.image.url
return static('image/anonymous.png')
def global_admin_css():
return format_html('<link rel="stylesheet" href="{}">', static('wagtailcloudinary/css/main.css'))
def global_admin_js():
html = []
scripts = [
static('wagtailcloudinary/js/csrf-token.js'),
static('js/jquery.ui.widget.js'),
static('js/jquery.iframe-transport.js'),
static('js/jquery.fileupload.js'),
]
for item in scripts:
html.append('<script src="{}"></script>'.format(item))
return format_html(''.join(html))
def xstatic(*tags):
from .vendors import vendors
node = vendors
fs = []
lang = get_language()
cls_str = str if six.PY3 else basestring
for tag in tags:
try:
for p in tag.split('.'):
node = node[p]
except Exception as e:
if tag.startswith('xadmin'):
file_type = tag.split('.')[-1]
if file_type in ('css', 'js'):
node = "xadmin/%s/%s" % (file_type, tag)
else:
raise e
else:
raise e
if isinstance(node, cls_str):
files = node
else:
mode = 'dev'
if not settings.DEBUG:
mode = getattr(settings, 'STATIC_USE_CDN',
False) and 'cdn' or 'production'
if mode == 'cdn' and mode not in node:
mode = 'production'
if mode == 'production' and mode not in node:
mode = 'dev'
files = node[mode]
files = type(files) in (list, tuple) and files or [files, ]
fs.extend([f % {'lang': lang.replace('_', '-')} for f in files])
return [f.startswith('http://') and f or static(f) for f in fs]
def toggle_bookmark(request):
"""API toggle_bookmark"""
if request.method == 'POST':
app = request.POST['app']
id = request.POST['id']
app_id = app + '-' + id
profile = request.user.profile
bookmarks = profile.bookmarks.split(',')
if app_id not in bookmarks:
if len(bookmarks) > settings.MAX_BOOKMARKS:
return JsonResponse({'status': 'false'}, status=400)
if profile.bookmarks != '':
profile.bookmarks += ","
profile.bookmarks += app_id
data = static('icons/stared28.png')
else:
regstr = re.escape(app_id) + r"\b(,|)"
profile.bookmarks = re.sub(regstr, '', profile.bookmarks)
if profile.bookmarks and profile.bookmarks[-1] == ',':
profile.bookmarks = profile.bookmarks[:-1]
data = static('icons/star28.png')
request.user.profile.save()
return JsonResponse([data], safe=False, status=201)
return error_page(request)
def media(self):
parent_media = super(CardsBlock, self).media
cards_css = {
'screen': (static('wagtailblocks_cards/css/wagtailblocks_cards.css'),)
}
cards_media = forms.Media(css=cards_css)
return parent_media + cards_media
def icon_path(self):
return static('cms_contact/src/img/{}.png'.format(self.type.lower()))
def get_image_url(self):
if not self.image:
return static("img/itugnu.png")
else:
return self.image.url
def get_image_url(self):
if not self.image:
return static("img/itugnu.png")
else:
return self.image.url
def static(path):
global _static
if _static is None:
if apps.is_installed('django.contrib.staticfiles'):
from django.contrib.staticfiles.templatetags.staticfiles import static as _static
else:
from django.templatetags.static import static as _static
return _static(path)
def get_advert_thumbnail(advert):
"""
Takes Advert object and returns thumbnail image, if no thumbnail - returns first image
if no image at all returns 'no-photo.jpg'
"""
photos = advert.images.all()
if photos:
for photo in photos:
if photo.thumbnail:
return photo.image.url
return photos[0].image.url
return static('img/no-photo.jpg')
def xstatic(*tags):
from vendors import vendors
node = vendors
fs = []
lang = get_language()
for tag in tags:
try:
for p in tag.split('.'):
node = node[p]
except Exception, e:
if tag.startswith('xadmin'):
file_type = tag.split('.')[-1]
if file_type in ('css', 'js'):
node = "xadmin/%s/%s" % (file_type, tag)
else:
raise e
else:
raise e
if type(node) in (str, unicode):
files = node
else:
mode = 'dev'
if not settings.DEBUG:
mode = getattr(settings, 'STATIC_USE_CDN',
False) and 'cdn' or 'production'
if mode == 'cdn' and mode not in node:
mode = 'production'
if mode == 'production' and mode not in node:
mode = 'dev'
files = node[mode]
files = type(files) in (list, tuple) and files or [files, ]
fs.extend([f % {'lang': lang.replace('_', '-')} for f in files])
return [f.startswith('http://') and f or static(f) for f in fs]
def valid(self, obj):
if obj.validation_warning == True:
return '<img src="%s">' % static('admin/img/icon-alert.svg')
elif obj.validation_ok == True:
return '<img src="%s">' % static('admin/img/icon-yes.svg')
elif obj.validation_ok == False:
return '<img src="%s">' % static('admin/img/icon-no.svg')
return ''
def static(path):
global _static
if _static is None:
if apps.is_installed('django.contrib.staticfiles'):
from django.contrib.staticfiles.templatetags.staticfiles import static as _static
else:
from django.templatetags.static import static as _static
return _static(path)
def static(path):
global _static
if _static is None:
if apps.is_installed('django.contrib.staticfiles'):
from django.contrib.staticfiles.templatetags.staticfiles import static as _static
else:
from django.templatetags.static import static as _static
return _static(path)
def static(path):
global _static
if _static is None:
if apps.is_installed('django.contrib.staticfiles'):
from django.contrib.staticfiles.templatetags.staticfiles import static as _static
else:
from django.templatetags.static import static as _static
return _static(path)