python类serve()的实例源码

static.py 文件源码 项目:django-next-train 作者: bitpixdigital 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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),
    ]
views.py 文件源码 项目:hexopress 作者: joelewis 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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/')
views.py 文件源码 项目:LatinSounds_AppEnviaMail 作者: G3ek-aR 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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)
views.py 文件源码 项目:DjangoZeroToHero 作者: RayParra 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
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)
views.py 文件源码 项目:Roboism 作者: markroxor 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
views.py 文件源码 项目:django-wechat-api 作者: crazy-canux 项目源码 文件源码 阅读 15 收藏 0 点赞 0 评论 0
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)
static.py 文件源码 项目:django-wechat-api 作者: crazy-canux 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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),
    ]
testcases.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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)
testcases.py 文件源码 项目:CodingDojo 作者: ComputerSocietyUNB 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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())
views.py 文件源码 项目:pyconjp-website 作者: pyconjp 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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
views.py 文件源码 项目:pyconjp-website 作者: pyconjp 项目源码 文件源码 阅读 120 收藏 0 点赞 0 评论 0
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
views.py 文件源码 项目:pyconjp-website 作者: pyconjp 项目源码 文件源码 阅读 57 收藏 0 点赞 0 评论 0
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
views.py 文件源码 项目:tecken 作者: mozilla-services 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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}
    )
views.py 文件源码 项目:tecken 作者: mozilla-services 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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,
    )
publish.py 文件源码 项目:DCRM 作者: 82Flex 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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
views.py 文件源码 项目:vaultier 作者: Movile 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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='/')
views.py 文件源码 项目:django-sphinxdoc 作者: luminum-solutions 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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
views.py 文件源码 项目:django-sphinxdoc 作者: luminum-solutions 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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,
    )
testcases.py 文件源码 项目:lifesoundtrack 作者: MTG 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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)
testcases.py 文件源码 项目:lifesoundtrack 作者: MTG 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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())


问题


面经


文章

微信
公众号

扫码关注公众号