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),
]
python类serve()的实例源码
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 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 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 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 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 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 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,
)
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())