我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.views.static.serve()。
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)
def static(prefix, view=serve, **kwargs): """ Helper function to return a URL pattern for serving files in debug mode. from django.conf import settings from django.conf.urls.static import static urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) """ # No-op if not in debug mode or an non-local prefix if not settings.DEBUG or (prefix and '://' in prefix): return [] elif not prefix: raise ImproperlyConfigured("Empty static prefix not permitted") return [ url(r'^%s(?P<path>.*)$' % re.escape(prefix.lstrip('/')), view, kwargs=kwargs), ]
def protected_view(request, path, server="django", as_download=False): if server != "django": mimetype, encoding = mimetypes.guess_type(path) response = HttpResponse() response["Content-Type"] = mimetype if encoding: response["Content-Encoding"] = encoding if as_download: response["Content-Disposition"] = "attachment; filename={}".format( basename(path)) response[server_header(server)] = os.path.join( PROTECTED_MEDIA_LOCATION_PREFIX, path ).encode("utf8") else: response = serve( request, path, document_root=PROTECTED_MEDIA_ROOT, show_indexes=False ) return response
def download(self, request, **kwargs): ''' example use: http://.../fileservice/download/med.mp4/ or http://.../fileservice/med.mp4/download/ ''' # method check to avoid bad requests self.method_check(request, allowed=['get']) # Must be done otherwise endpoint will be wide open self.is_authenticated(request) response = None file_item_name = kwargs.get('name', None) if file_item_name: filename_absolute = helpers.get_filename_absolute(file_item_name) if os.path.isfile(filename_absolute): response = serve(request, os.path.basename(filename_absolute), os.path.dirname(filename_absolute)) response['Content-Disposition'] = 'attachment; filename="{}"'.format( os.path.basename(filename_absolute)) if not response: response = self.create_response(request=request, data={}, response_class=HttpNotFound) return response
def serve_static(request, path, insecure=False, **kwargs): """ This is copied from Django's contrib.staticfiles.views to remove the DEBUG check. We don't need to check DEBUG since we never actually serve the site with Django. 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. """ 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)
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:: (r'^(?P<path>.*)$', 'django.contrib.staticfiles.views.serve') in your URLconf. It uses the django.views.static view to serve the found files. """ if not settings.DEBUG and not insecure: raise ImproperlyConfigured("The staticfiles view can only be used in " "debug mode or if the --insecure " "option of 'runserver' is used") 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)
def serve_blog(request, username, path): bloguser = User.objects.get(username=username) print path if path.endswith('/') or not path: path = path + '/index.html' else: # append '/', if check if dir exists if os.path.isdir('{0}/{1}/octopress/public/{2}'.format( settings.BLOG_DIR_ROOT, bloguser.email, path)): path = path + '/index.html' # if path doesn't end with '/', check if a directory or file exist in path return static.serve(request, path, document_root=settings.BLOG_DIR_ROOT+'/'+bloguser.email+'/octopress/public/')
def get_response(self, request): from django.http import Http404 if self._should_handle(request.path): try: return self.serve(request) except Http404: pass return super(FSFilesHandler, self).get_response(request)
def serve(self, request): os_rel_path = self.file_path(request.path) os_rel_path = posixpath.normpath(unquote(os_rel_path)) # Emulate behavior of django.contrib.staticfiles.views.serve() when it # invokes staticfiles' finders functionality. # TODO: Modify if/when that internal API is refactored final_rel_path = os_rel_path.replace('\\', '/').lstrip('/') return serve(request, final_rel_path, document_root=self.get_base_dir())
def file_download(request, pk, *args): file = get_object_or_404(File, pk=pk) if getattr(settings, "USE_X_ACCEL_REDIRECT", False): response = HttpResponse() response["X-Accel-Redirect"] = file.file.url # delete content-type to allow Gondor to determine the filetype and # we definitely don't want Django's default :-) del response["content-type"] else: response = static.serve(request, file.file.name, document_root=settings.MEDIA_ROOT) return response
def document_download(request, pk, *args): document = get_object_or_404(SupportingDocument, pk=pk) if getattr(settings, "USE_X_ACCEL_REDIRECT", False): response = HttpResponse() response["X-Accel-Redirect"] = document.file.url # delete content-type to allow Gondor to determine the filetype and # we definitely don't want Django's crappy default :-) del response["content-type"] else: response = static.serve(request, document.file.name, document_root=settings.MEDIA_ROOT) return response
def contribute_json(request): """Advantages of having our own custom view over using django.view.static.serve is that we get the right content-type and as a view we write a unit test that checks that the JSON is valid and can be deserialized.""" with open(os.path.join(settings.BASE_DIR, 'contribute.json')) as f: contribute_json_dict = json.load(f) return http.JsonResponse( contribute_json_dict, json_dumps_params={'indent': 3} )
def frontend_index_html(request, path='/'): if request.path_info == '/index.html': # remove the static file mention return redirect('/') return serve( request, '/index.html', document_root=settings.STATIC_ROOT, )
def package_file_fetch(request, package_id): pref = preferences.Setting pkg = Version.objects.get(id=int(package_id)) if not pkg: return HttpResponseNotFound() file_path = os.path.join(settings.MEDIA_ROOT, pkg.storage.name) if not os.path.exists(file_path): return HttpResponseNotFound() if pref.download_cydia_only: if 'HTTP_X_UNIQUE_ID' not in request.META: return HttpResponseBadRequest() request_path = pkg.storage.name request_url = pkg.get_external_storage_link() pkg.download_times = pkg.download_times + 1 pkg.save() if pref.redirect_resources == 1: # Redirect URLs return redirect(request_url) elif pref.redirect_resources == 2: # Redirect to WEB server response = HttpResponse() if pref.web_server == 0: response['X-Accel-Redirect'] = request_url elif pref.web_server == 1: # You may set Send File Path to settings.MEDIA_ROOT response['X-sendfile'] = request_path elif pref.web_server == 2: pass else: # Return FileResponse By Reading Static File response = serve( request, path=request_path, document_root=settings.MEDIA_ROOT, ) response['Content-Type'] = 'application/octet-stream' response['Content-Transfer-Encoding'] = "binary" response['Cache-Control'] = "public, must-revalidate, max-age=0" response['Content-Disposition'] = "attachment; filename=\"" + urllib.quote_plus(pkg.base_filename()) + "\"" return response
def index(request): """ For devel purposes we need also index.html of frontend to be executed """ index = os.path.join(settings.VAULTIER['frontend_path'], 'html/index.html') return static.serve(request, index, document_root='/')
def objects_inventory(request, slug): """Renders the ``objects.inv`` as plain text.""" project = get_object_or_404(Project, slug=slug) response = serve( request, document_root=os.path.join(project.path, BUILDDIR), path='objects.inv', ) response['Content-Type'] = 'text/plain' return response
def sphinx_serve(request, slug, type_, path): """Serves sphinx static and other files.""" project = get_object_or_404(Project, slug=slug) return serve( request, document_root=os.path.join(project.path, BUILDDIR, type_), path=path, )