def find_asset(theme, asset):
theme_path = ''
for name, label, path in hz_themes.get_themes():
if theme == name:
theme_path = path
theme_path = os.path.join(settings.ROOT_PATH, theme_path)
# If there is a 'static' subdir of the theme, then use
# that as the theme's asset root path
static_path = os.path.join(theme_path, 'static')
if os.path.exists(static_path):
theme_path = static_path
# The full path to the asset requested
asset_path = os.path.join(theme_path, asset)
if os.path.exists(asset_path):
return_path = os.path.join(hz_themes.get_theme_dir(), theme, asset)
else:
return_path = os.path.join('dashboard', asset)
return staticfiles_storage.url(pathname2url(return_path))
python类url()的实例源码
def environment(**options):
env = Environment(**options)
env.globals.update({
'static': loudfail_static,
'url': reverse,
"content": "project.content.constants",
"linkify": "project.jinja2.linkify",
"current_local_time": "project.jinja2.current_local_time",
"namify": "project.jinja2.namify",
"url_with_ids": "project.jinja2.url_with_ids",
"oxford_comma": "project.jinja2.oxford_comma",
"contact_info_to_html": "project.jinja2.contact_info_to_html",
"to_json": "project.jinja2.to_json",
"humanize": "project.jinja2.humanize",
"contact_method_verbs": "project.jinja2.contact_method_verbs",
"format_phone_number": "project.jinja2.format_phone_number",
"settings": "django.conf.settings",
"local_time": "intake.utils.local_time",
})
return env
def network_icon(self, obj):
icons_url = staticfiles_storage.url('social_networks/img/admin_icons.svg')
try:
icon_code, icon_title = next((
network_tuple
for network_tuple in conf.ALL_NETWORKS
if network_tuple[0] == obj.network
))
except StopIteration:
return
offset = 100 / (len(SPRITE_ICONS) - 1) * SPRITE_ICONS.index(icon_code)
return """
<span style="display:inline-block; width:21px; height:20px; margin:0;
background:url(%s) %0.4f%% 0; vertical-align:middle;" title="%s"/>""" % (
icons_url, offset, icon_title
)
def render_to_page_load_async_html(self):
"""
Generates script tag containing Javascript to register an
asynchronously loading Javascript FrontEnd plugin against the core
front-end Kolibri app. It passes in the events that would trigger
loading the plugin, both multi-time firing events (events) and one time
firing events (once).
It also passes in information about the methods that the events should
be delegated to once the plugin has loaded.
TODO: What do we do with the extension parameter here?
:returns: HTML of a script tag to insert into a page.
"""
urls = [chunk['url'] for chunk in self.sorted_chunks()]
tags = self.frontend_message_tag() +\
['<script>{kolibri_name}.registerKolibriModuleAsync("{bundle}", ["{urls}"], {events}, {once});</script>'.format(
kolibri_name=django_settings.KOLIBRI_CORE_JS_NAME,
bundle=self.unique_slug,
urls='","'.join(urls),
events=json.dumps(self.events),
once=json.dumps(self.once),
)]
return mark_safe('\n'.join(tags))
def is_immutable_file(self, path, url):
"""
Determine whether given URL represents an immutable file (i.e. a
file with a hash of its contents as part of its name) which can
therefore be cached forever
"""
if not url.startswith(self.static_prefix):
return False
name = url[len(self.static_prefix):]
name_without_hash = self.get_name_without_hash(name)
if name == name_without_hash:
return False
static_url = self.get_static_url(name_without_hash)
# If the static URL function maps the name without hash
# back to the original URL, then we know we've got a
# versioned filename
if static_url and static_url.endswith(url):
return True
return False
def url(self):
try:
return super().url
except ValueError:
from django.contrib.staticfiles.storage import staticfiles_storage
return staticfiles_storage.url(self.field.static_image_path)
def _media(self):
"""
Include media
"""
js = (
staticfiles_storage.url("prosemirror/widget.min.js"),
)
css = {
"all": (
staticfiles_storage.url(
"prosemirror/widget.min.css"),
)
}
return forms.Media(css=css, js=js)
def environment(**options):
env = Environment(**options)
env.globals.update({
'static': staticfiles_storage.url,
'url': reverse,
})
return env
def static(path):
return staticfiles_storage.url(path)
def url(self, context):
path = self.path.resolve(context)
return static(path)
def get_statc_url(cls, path):
return super(StaticExtension, cls).get_statc_url(
staticfiles_storage.url(path))
def fp_lastmod(request, url):
return datetime.datetime.fromtimestamp(
Path(loader.get_template(
FlatPage.objects.get(url=url).template_name
or "flatpages/default.html"
).template.origin.name).stat().st_mtime
)
def environment(**options):
"""
Create a environment object for settings.TEMPLATE.Jinja2.ENGINE
:param options:
:return:
"""
env = BaseEnvironment(pyecharts_config=PyEchartsConfig(jshost=settings.STATIC_URL), **options)
env.globals.update({
'static': staticfiles_storage.url,
'url': reverse,
})
return env
def environment(**options):
"""Get jinja2 environment.
:param options: Options
:return env: return environment instance
"""
env = Environment(**options)
env.globals.update({
'static': staticfiles_storage.url,
'url': reverse,
'LANGUAGES': settings.LANGUAGES,
'translation': translation,
})
# add django filters
env.filters['slugify'] = slugify
# use django-bootstrap-form on jinja
from bootstrapform.templatetags import bootstrap
env.filters['bootstrap'] = bootstrap.bootstrap
env.filters['bootstrap_horizontal'] = bootstrap.bootstrap_horizontal
env.filters['bootstrap_inline'] = bootstrap.bootstrap_inline
# add custom filters
env.filters['fupper'] = fupper
env.install_gettext_translations(translation)
return env
def loudfail_static(*args, **kwargs):
result = staticfiles_storage.url(*args, **kwargs)
if not result:
raise ObjectDoesNotExist(
"Cannot find static file with: {} {}".format(args, kwargs))
else:
return result
def externalize_url(url):
return urljoin(settings.DEFAULT_HOST, url)
def build_link(self, lookup):
url = self.links[lookup]
return '<a href="{}">{}</a>'.format(
url, escape(lookup))
def get_urls(self):
urls = super().get_urls()
info = self.model._meta.app_label, self.model._meta.model_name
submit_urls = [
url(
r'^(\d+)/share/$',
self.admin_site.admin_view(self.submit_view),
name='%s_%s_share' % info
),
]
return submit_urls + urls
def submit_view(self, request, object_id):
try:
obj = self.model._default_manager.get(pk=object_id)
except self.model.DoesNotExist:
raise Http404
form = self.get_autopost_form(request, obj)
if form.is_valid():
obj_ct = ContentType.objects.get_for_model(obj)
text = form.cleaned_data.get('text')
networks = form.cleaned_data.get('networks')
for network in networks:
try:
post = FeedPost.objects.get(
network=network,
content_type=obj_ct,
object_id=obj.pk,
)
except FeedPost.DoesNotExist:
FeedPost.objects.create(
network=network,
url=request.build_absolute_uri(self.get_autopost_url(obj)),
text=text,
content_type=obj_ct,
object_id=obj.pk,
)
else:
if post.scheduled:
# ????????? ??????
post.url = request.build_absolute_uri(self.get_autopost_url(obj))
post.text = text
post.save()
return JsonResponse({})
else:
return JsonResponse({
'errors': form.errors
}, status=400)
def __init__(self, *args, sprite='', size=(), background='#FFFFFF', **kwargs):
kwargs.setdefault('max_length', 100)
super().__init__(*args, **kwargs)
self.sprite = sprite
self.sprite_url = staticfiles_storage.url(self.sprite)
self.background = background
self.size = size
def render_css(self, package, path, template_name=None):
template_name = package.template_name or template_name or "pipeline/css_default.html"
modified = staticfiles_storage.modified_time(path).timestamp()
context = package.extra_context
context.update({
'type': guess_type(path, 'text/css'),
'url': mark_safe(staticfiles_storage.url(path)),
'modified': int(modified),
})
return loader.render_to_string(template_name, context)
def render_js(self, package, path):
template_name = package.template_name or "pipeline/js_default.html"
modified = staticfiles_storage.modified_time(path).timestamp()
context = package.extra_context
context.update({
'type': guess_type(path, 'text/javascript'),
'url': mark_safe(staticfiles_storage.url(path)),
'modified': int(modified),
})
return loader.render_to_string(template_name, context)
def environment(**options):
env = Environment(**options)
env.globals.update({
'static': staticfiles_storage.url,
'url': url_tag,
'url_for': url_tag,
'url_with_form': url_with_form,
})
return env
def url_with_form(view, form, args, kwargs):
"""Expects a view name, a form, and optional arguments. The form's data will be
serialized, with any overrides from kwargs applied. Args are passed through to `reverse`"""
url = reverse(view, args=args)
qs = form.data.urlencode()
parsed = parse_qs(qs)
if kwargs:
parsed.update(kwargs)
url = url + '?' + urlencode(parsed, doseq=True)
return url
def url_tag(view, *args, **kwargs):
url = reverse(view, args=args)
if kwargs:
url += '?' + urlencode(kwargs)
return url
def bundle(self):
"""
:returns: a generator yielding dict objects with properties of the built
asset, most notably its URL.
"""
for f in self._stats_file_content["files"]:
filename = f['name']
if any(list(regex.match(filename) for regex in settings.IGNORE_PATTERNS)):
continue
relpath = '{0}/{1}'.format(self.unique_slug, filename)
if django_settings.DEBUG:
f['url'] = f['publicPath']
else:
f['url'] = staticfiles_storage.url(relpath)
yield f
def js_and_css_tags(self):
js_tag = '<script type="text/javascript" src="{url}"></script>'
css_tag = '<link type="text/css" href="{url}" rel="stylesheet"/>'
# Sorted to load css before js
for chunk in self.sorted_chunks():
if chunk['name'].endswith('.js'):
yield js_tag.format(url=chunk['url'])
elif chunk['name'].endswith('.css'):
yield css_tag.format(url=chunk['url'])
def get_image_url(self):
return self.image.url if self.image else staticfiles_storage.url(settings.PODCAST_NO_ARTWORK)
def get_image_url(self):
return self.image.url if self.image else self.show.get_image_url()
def get_poster_url(self):
return self.poster.url if self.poster else self.episode.get_image_url()