本文整理匯總了Python中django.contrib.staticfiles.finders.find方法的典型用法代碼示例。如果您正苦於以下問題:Python finders.find方法的具體用法?Python finders.find怎麽用?Python finders.find使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類django.contrib.staticfiles.finders
的用法示例。
在下文中一共展示了finders.find方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: serve
# 需要導入模塊: from django.contrib.staticfiles import finders [as 別名]
# 或者: from django.contrib.staticfiles.finders import find [as 別名]
def serve(request, path, insecure=False, **kwargs):
"""
Serve static files below a given point in the directory structure or
from locations inferred from the staticfiles finders.
To use, put a URL pattern such as::
from django.contrib.staticfiles import views
url(r'^(?P<path>.*)$', views.serve)
in your URLconf.
It uses the django.views.static.serve() view to serve the found files.
"""
if not settings.DEBUG and not insecure:
raise Http404
normalized_path = posixpath.normpath(unquote(path)).lstrip('/')
absolute_path = finders.find(normalized_path)
if not absolute_path:
if path.endswith('/') or path == '':
raise Http404("Directory indexes are not allowed here.")
raise Http404("'%s' could not be found" % path)
document_root, path = os.path.split(absolute_path)
return static.serve(request, path, document_root=document_root, **kwargs)
示例2: serve
# 需要導入模塊: from django.contrib.staticfiles import finders [as 別名]
# 或者: from django.contrib.staticfiles.finders import find [as 別名]
def serve(request, path, insecure=False, **kwargs):
"""
Serve static files below a given point in the directory structure or
from locations inferred from the staticfiles finders.
To use, put a URL pattern such as::
from django.contrib.staticfiles import views
url(r'^(?P<path>.*)$', views.serve)
in your URLconf.
It uses the django.views.static.serve() view to serve the found files.
"""
if not settings.DEBUG and not insecure:
raise Http404
normalized_path = posixpath.normpath(path).lstrip('/')
absolute_path = finders.find(normalized_path)
if not absolute_path:
if path.endswith('/') or path == '':
raise Http404("Directory indexes are not allowed here.")
raise Http404("'%s' could not be found" % path)
document_root, path = os.path.split(absolute_path)
return static.serve(request, path, document_root=document_root, **kwargs)
示例3: get
# 需要導入模塊: from django.contrib.staticfiles import finders [as 別名]
# 或者: from django.contrib.staticfiles.finders import find [as 別名]
def get(self, request, *args, **kwargs):
path = finders.find(self.path)
if self.stream:
response = http.FileResponse(
open(path, 'rb'),
content_type=self.content_type,
)
else:
with open(path, 'r', encoding='utf8') as f:
response = http.HttpResponse(
f.read(),
content_type=self.content_type,
)
if self.allow_origin:
response['Access-Control-Allow-Origin'] = self.allow_origin
return response
示例4: get_attachments
# 需要導入模塊: from django.contrib.staticfiles import finders [as 別名]
# 或者: from django.contrib.staticfiles.finders import find [as 別名]
def get_attachments(self):
attachments = super().get_attachments()
filename = (
finders.find('images/email_logo.png')
or finders.find('images/email_logo.svg')
)
if filename:
if filename.endswith('.png'):
imagetype = 'png'
else:
imagetype = 'svg+xml'
with open(filename, 'rb') as f:
logo = MIMEImage(f.read(), imagetype)
logo.add_header('Content-ID', '<{}>'.format('logo'))
return attachments + [logo]
return attachments
示例5: validation_schema
# 需要導入模塊: from django.contrib.staticfiles import finders [as 別名]
# 或者: from django.contrib.staticfiles.finders import find [as 別名]
def validation_schema(name):
"""Return json schema for json validation."""
schemas = {
"processor": "processSchema.json",
"descriptor": "descriptorSchema.json",
"field": "fieldSchema.json",
"type": "typeSchema.json",
}
if name not in schemas:
raise ValueError()
field_schema_file = finders.find("flow/{}".format(schemas["field"]), all=True)[0]
with open(field_schema_file, "r") as fn:
field_schema = fn.read()
if name == "field":
return json.loads(field_schema.replace("{{PARENT}}", ""))
schema_file = finders.find("flow/{}".format(schemas[name]), all=True)[0]
with open(schema_file, "r") as fn:
schema = fn.read()
return json.loads(
schema.replace("{{FIELD}}", field_schema).replace("{{PARENT}}", "/field")
)
示例6: _test_static_file
# 需要導入模塊: from django.contrib.staticfiles import finders [as 別名]
# 或者: from django.contrib.staticfiles.finders import find [as 別名]
def _test_static_file(self, pth):
result = finders.find(pth)
print(result)
self.assertTrue(result)
示例7: handle_label
# 需要導入模塊: from django.contrib.staticfiles import finders [as 別名]
# 或者: from django.contrib.staticfiles.finders import find [as 別名]
def handle_label(self, path, **options):
verbosity = options['verbosity']
result = finders.find(path, all=options['all'])
path = force_text(path)
if verbosity >= 2:
searched_locations = ("Looking in the following locations:\n %s" %
"\n ".join(force_text(location)
for location in finders.searched_locations))
else:
searched_locations = ''
if result:
if not isinstance(result, (list, tuple)):
result = [result]
result = (force_text(os.path.realpath(path)) for path in result)
if verbosity >= 1:
file_list = '\n '.join(result)
return ("Found '%s' here:\n %s\n%s" %
(path, file_list, searched_locations))
else:
return '\n'.join(result)
else:
message = ["No matching file found for '%s'." % path]
if verbosity >= 2:
message.append(searched_locations)
if verbosity >= 1:
self.stderr.write('\n'.join(message))
示例8: handle_label
# 需要導入模塊: from django.contrib.staticfiles import finders [as 別名]
# 或者: from django.contrib.staticfiles.finders import find [as 別名]
def handle_label(self, path, **options):
verbosity = options['verbosity']
result = finders.find(path, all=options['all'])
if verbosity >= 2:
searched_locations = (
"\nLooking in the following locations:\n %s" %
"\n ".join(finders.searched_locations)
)
else:
searched_locations = ''
if result:
if not isinstance(result, (list, tuple)):
result = [result]
result = (os.path.realpath(path) for path in result)
if verbosity >= 1:
file_list = '\n '.join(result)
return ("Found '%s' here:\n %s%s" %
(path, file_list, searched_locations))
else:
return '\n'.join(result)
else:
message = ["No matching file found for '%s'." % path]
if verbosity >= 2:
message.append(searched_locations)
if verbosity >= 1:
self.stderr.write('\n'.join(message))
示例9: static_path
# 需要導入模塊: from django.contrib.staticfiles import finders [as 別名]
# 或者: from django.contrib.staticfiles.finders import find [as 別名]
def static_path(path: str) -> str:
return find(path) or "/nonexistent"
示例10: get_all_photos
# 需要導入模塊: from django.contrib.staticfiles import finders [as 別名]
# 或者: from django.contrib.staticfiles.finders import find [as 別名]
def get_all_photos():
""" This function is not used; it can be used to view all photos available. """
with open(find("animal_photo_urls.txt")) as f:
urls = f.readlines()
return [url.strip() + "?w=400" for url in urls]
# images from pexels.com
示例11: get_rand_photo
# 需要導入模塊: from django.contrib.staticfiles import finders [as 別名]
# 或者: from django.contrib.staticfiles.finders import find [as 別名]
def get_rand_photo(width=400):
with open(find("animal_photo_urls.txt")) as f:
urls = f.readlines()
return urls[randint(0, len(urls) - 1)].strip() + "?w=" + str(width)
示例12: handle_label
# 需要導入模塊: from django.contrib.staticfiles import finders [as 別名]
# 或者: from django.contrib.staticfiles.finders import find [as 別名]
def handle_label(self, path, **options):
verbosity = options['verbosity']
result = finders.find(path, all=options['all'])
path = force_text(path)
if verbosity >= 2:
searched_locations = (
"\nLooking in the following locations:\n %s" %
"\n ".join(force_text(location) for location in finders.searched_locations)
)
else:
searched_locations = ''
if result:
if not isinstance(result, (list, tuple)):
result = [result]
result = (force_text(os.path.realpath(path)) for path in result)
if verbosity >= 1:
file_list = '\n '.join(result)
return ("Found '%s' here:\n %s%s" %
(path, file_list, searched_locations))
else:
return '\n'.join(result)
else:
message = ["No matching file found for '%s'." % path]
if verbosity >= 2:
message.append(searched_locations)
if verbosity >= 1:
self.stderr.write('\n'.join(message))
示例13: render_component
# 需要導入模塊: from django.contrib.staticfiles import finders [as 別名]
# 或者: from django.contrib.staticfiles.finders import find [as 別名]
def render_component(path_to_source, props=None, to_static_markup=False, json_encoder=None):
if not os.path.isabs(path_to_source):
# If its using the manifest staticfiles storage, to the hashed name.
# eg. js/hello.js -> js/hello.d0bf07ff5f07.js
if isinstance(staticfiles_storage, HashedFilesMixin):
try:
path_to_source = staticfiles_storage.stored_name(path_to_source)
except ValueError:
# Couldn't find it.
pass
# first, attempt to resolve at STATIC_ROOT if the file was collected
abs_path = os.path.join(settings.STATIC_ROOT or '', path_to_source)
if os.path.exists(abs_path):
path_to_source = abs_path
else:
# Otherwise, resolve it using finders
path_to_source = find_static(path_to_source) or path_to_source
if json_encoder is None:
json_encoder = DjangoJSONEncoder().encode
try:
html = render_core(path_to_source, props, to_static_markup, json_encoder, service_url=SERVICE_URL)
except:
if not FAIL_SAFE:
raise
log.exception('Error while rendering %s', path_to_source)
html = ''
return RenderedComponent(html, path_to_source, props, json_encoder)
示例14: hashed_name
# 需要導入模塊: from django.contrib.staticfiles import finders [as 別名]
# 或者: from django.contrib.staticfiles.finders import find [as 別名]
def hashed_name(self, name, content=None, filename=None):
parsed_name = urlsplit(unquote(name))
clean_name = parsed_name.path.strip()
opened = False
if content is None:
absolute_path = finders.find(clean_name)
try:
content = open(absolute_path, 'rb')
except (IOError, OSError) as e:
if e.errno == errno.ENOENT:
raise ValueError("The file '%s' could not be found with %r." % (clean_name, self))
else:
raise
content = File(content)
opened = True
try:
file_hash = self.file_hash(clean_name, content)
finally:
if opened:
content.close()
path, filename = os.path.split(clean_name)
root, ext = os.path.splitext(filename)
if file_hash is not None:
file_hash = ".%s" % file_hash
hashed_name = os.path.join(path, "%s%s%s" % (root, file_hash, ext))
unparsed_name = list(parsed_name)
unparsed_name[2] = hashed_name
# Special casing for a @font-face hack, like url(myfont.eot?#iefix")
# http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax
if '?#' in name and not unparsed_name[3]:
unparsed_name[2] += '?'
return urlunsplit(unparsed_name)
示例15: assertStaticFile
# 需要導入模塊: from django.contrib.staticfiles import finders [as 別名]
# 或者: from django.contrib.staticfiles.finders import find [as 別名]
def assertStaticFile(self, path):
result = finders.find(path)
self.assertTrue(result != None)