Python django.contrib.staticfiles.finders.find() Examples
The following are 26
code examples of django.contrib.staticfiles.finders.find().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
django.contrib.staticfiles.finders
, or try the search function
.
Example #1
Source File: views.py From mrs with GNU Affero General Public License v3.0 | 7 votes |
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
Example #2
Source File: views.py From GTDWeb with GNU General Public License v2.0 | 6 votes |
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)
Example #3
Source File: views.py From python2017 with MIT License | 6 votes |
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)
Example #4
Source File: views.py From bioforum with MIT License | 6 votes |
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)
Example #5
Source File: mixins.py From adhocracy4 with GNU Affero General Public License v3.0 | 6 votes |
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
Example #6
Source File: views.py From openhgsenti with Apache License 2.0 | 6 votes |
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)
Example #7
Source File: views.py From Hands-On-Application-Development-with-PyCharm with MIT License | 6 votes |
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)
Example #8
Source File: svg.py From django-inline-svg with MIT License | 5 votes |
def svg(filename): SVG_DIRS = getattr(settings, 'SVG_DIRS', []) if type(SVG_DIRS) != list: raise ImproperlyConfigured('SVG_DIRS setting must be a list') path = None if SVG_DIRS: for directory in SVG_DIRS: svg_path = os.path.join(directory, '{filename}.svg'.format( filename=filename)) if os.path.isfile(svg_path): path = svg_path else: path = finders.find(os.path.join('svg', '{filename}.svg'.format( filename=filename)), all=True) if not path: message = "SVG '{filename}.svg' not found".format(filename=filename) # Raise exception if DEBUG is True, else just log a warning. if settings.DEBUG: raise SVGNotFound(message) else: logger.warning(message) return '' # Sometimes path can be a list/tuple if there's more than one file found if isinstance(path, (list, tuple)): path = path[0] with open(path) as svg_file: svg = mark_safe(svg_file.read()) return svg
Example #9
Source File: render.py From react-render with MIT License | 5 votes |
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)
Example #10
Source File: storage.py From django-cloudinary-storage with MIT License | 5 votes |
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)
Example #11
Source File: test_admin.py From django-treenode with MIT License | 5 votes |
def assertStaticFile(self, path): result = finders.find(path) self.assertTrue(result != None)
Example #12
Source File: findstatic.py From openhgsenti with Apache License 2.0 | 5 votes |
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))
Example #13
Source File: test_finders.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_find_first(self): src, dst = self.find_first found = self.finder.find(src) self.assertEqual(os.path.normcase(found), os.path.normcase(dst))
Example #14
Source File: test_finders.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_find_all(self): src, dst = self.find_all found = self.finder.find(src, all=True) found = [os.path.normcase(f) for f in found] dst = [os.path.normcase(d) for d in dst] self.assertEqual(found, dst)
Example #15
Source File: test_finders.py From djongo with GNU Affero General Public License v3.0 | 5 votes |
def test_searched_locations(self): finders.find('spam') self.assertEqual( finders.searched_locations, [os.path.join(TEST_ROOT, 'project', 'documents')] )
Example #16
Source File: widgets.py From yats with MIT License | 5 votes |
def get_locale_js_url_date(lang): url = 'datepicker/js/locales/bootstrap-datepicker.%s.js' % lang if finders.find(url): return settings.STATIC_URL + url if '-' in lang: return get_locale_js_url_date(lang.split('-')[0].lower()) return ''
Example #17
Source File: widgets.py From yats with MIT License | 5 votes |
def get_locale_js_url_datetime(lang): url = 'datetimepicker/js/locales/bootstrap-datetimepicker.%s.js' % lang if finders.find(url): return settings.STATIC_URL + url if '-' in lang: return get_locale_js_url_datetime(lang.split('-')[0].lower()) return ''
Example #18
Source File: findstatic.py From python2017 with MIT License | 5 votes |
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))
Example #19
Source File: utils.py From resolwe with Apache License 2.0 | 5 votes |
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") )
Example #20
Source File: findstatic.py From Hands-On-Application-Development-with-PyCharm with MIT License | 5 votes |
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))
Example #21
Source File: utils.py From hknweb with MIT License | 5 votes |
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)
Example #22
Source File: utils.py From hknweb with MIT License | 5 votes |
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
Example #23
Source File: storage.py From zulip with Apache License 2.0 | 5 votes |
def static_path(path: str) -> str: return find(path) or "/nonexistent"
Example #24
Source File: findstatic.py From bioforum with MIT License | 5 votes |
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))
Example #25
Source File: findstatic.py From GTDWeb with GNU General Public License v2.0 | 5 votes |
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))
Example #26
Source File: tests.py From longclaw with MIT License | 5 votes |
def _test_static_file(self, pth): result = finders.find(pth) print(result) self.assertTrue(result)