Exemplo n.º 1
0
def media_serve(request, path, document_root=None, show_indexes=False):
    try:
        return django_serve(request, path, document_root, show_indexes)
    except Http404:
        if getattr(settings, 'CACHEBUSTER_PREPEND_MEDIA', False):
            unique_string, new_path = path.split("/", 1)
            return django_serve(request, new_path, document_root, show_indexes)
        raise
Exemplo n.º 2
0
def media_serve(request, path, document_root=None, show_indexes=False):
    try:
        return django_serve(request, path, document_root, show_indexes)
    except Http404:
        if getattr(settings, "CACHEBUSTER_PREPEND_MEDIA", False):
            unique_string, new_path = path.split("/", 1)
            return django_serve(request, new_path, document_root, show_indexes)
        raise
Exemplo n.º 3
0
def serve(request, app, path, show_indexes=True):
    if request.method == 'GET':
        apps = get_apps()
        for x in apps:
            app_dir = osp.dirname(x.__file__)
            module = x.__name__
            if app == module.split('.')[-2]:  #we get the models module here
                if app_dir.endswith("models"):
                    # this can happen only in case when models are an directory
                    app_dir = osp.split(app_dir)[0]
                media_dir = osp.join(app_dir, "media", app)
                if not osp.isdir(media_dir):
                    media_dir = osp.join(app_dir, "media")
                asset = osp.join(media_dir, path)
                if osp.exists(asset):
                    return django_serve(request,
                                        path,
                                        document_root=media_dir,
                                        show_indexes=show_indexes)
                #continue
        return django_serve(request,
                            app + "/" + path,
                            document_root=settings.MEDIA_ROOT,
                            show_indexes=show_indexes)
    elif request.method == 'POST':
        data = request.POST.get("data", "")
        apps = get_apps()
        for x in apps:
            app_dir = osp.dirname(x.__file__)
            module = x.__name__
            if app == module.split('.')[-2]:  #we get the models module here
                media_dir = osp.join(app_dir, "media")
                asset = osp.join(media_dir, path)
                if osp.exists(asset):
                    f = file(asset, 'w')
                    for line in data.split('\n'):
                        line.strip()
                        line = line[:-1]
                        if line:
                            selector, datap = line.split('{')
                            print >> f, selector, '{'
                            datap.strip()
                            lines = datap.split(';')
                            if lines:
                                print >> f, "    " + ";\n    ".join(lines)
                            print >> f, '}\n'
                    f.close()

                    return django_serve(request,
                                        path,
                                        document_root=media_dir,
                                        show_indexes=show_indexes)
                continue
Exemplo n.º 4
0
def static_serve(request, path, document_root=None, show_indexes=False):
    try:
        if django_staticfiles_serve:
            return django_staticfiles_serve(request, path, document_root)
        else:
            return django_serve(request, path, document_root, show_indexes)
    except Http404:
        if getattr(settings, "CACHEBUSTER_PREPEND_STATIC", False):
            unique_string, new_path = path.split("/", 1)
            if django_staticfiles_serve:
                return django_staticfiles_serve(request, new_path, document_root)
            else:
                return django_serve(request, new_path, document_root, show_indexes)
        raise
Exemplo n.º 5
0
def static_serve(request, path, document_root=None, show_indexes=False):
    try:
        if django_staticfiles_serve:
            return django_staticfiles_serve(request, path, document_root)
        else:
            return django_serve(request, path, document_root, show_indexes)
    except Http404:
        if getattr(settings, 'CACHEBUSTER_PREPEND_STATIC', False):
            unique_string, new_path = path.split("/", 1)
            if django_staticfiles_serve:
                return django_staticfiles_serve(request, new_path, document_root)
            else:
                return django_serve(request, new_path, document_root, show_indexes)
        raise
Exemplo n.º 6
0
def serve(request, path, document_root=None, show_indexes=False):
    try:
        full_document_root = safe_join(document_root,
                                       request.tenant.domain_url)
    except AttributeError:
        full_document_root = document_root

    return django_serve(request, path, full_document_root, show_indexes)
Exemplo n.º 7
0
def serve(request, app, path, show_indexes=True):
    if request.method == 'GET':
        apps = get_apps()
        for x in apps:
            app_dir = osp.dirname(x.__file__)
            module = x.__name__
            if app == module.split('.')[-2]: #we get the models module here
                if app_dir.endswith("models"):
                    # this can happen only in case when models are an directory
                    app_dir = osp.split(app_dir)[0]
                media_dir = osp.join(app_dir, "media", app)
                if not osp.isdir(media_dir):
                    media_dir = osp.join(app_dir, "media")
                asset = osp.join(media_dir, path)
                if osp.exists(asset):
                    return django_serve(request, path, document_root=media_dir, show_indexes=show_indexes)
                #continue
        return django_serve(request, app+"/"+path, document_root=settings.MEDIA_ROOT, show_indexes=show_indexes)
    elif request.method == 'POST':
        data = request.POST.get("data", "")
        apps = get_apps()
        for x in apps:
            app_dir = osp.dirname(x.__file__)
            module = x.__name__
            if app == module.split('.')[-2]: #we get the models module here
                media_dir = osp.join(app_dir, "media")
                asset = osp.join(media_dir, path)
                if osp.exists(asset):
                    f = file(asset, 'w')
                    for line in data.split('\n'):
                        line.strip()
                        line = line[:-1]
                        if line:
                            selector, datap = line.split('{')
                            print >>f, selector, '{'
                            datap.strip()
                            lines = datap.split(';')
                            if lines:
                                print >>f, "    "+";\n    ".join(lines)
                            print >>f, '}\n'
                    f.close()

                    return django_serve(request, path, document_root=media_dir, show_indexes=show_indexes)
                continue
    else:
        raise Http404()
Exemplo n.º 8
0
def serve_mixed(request, *args, **kwargs):
    """
    First attempts to serve the file from the filesystem,
    then tries the database.
    """
    name = kwargs.get("name") or kwargs.get("path")
    document_root = kwargs.get("document_root")
    document_root = document_root or settings.MEDIA_ROOT
    try:
        # First attempt to serve from filesystem.
        return django_serve(request, name, document_root)
    except Http404:
        # Then try serving from database.
        return serve(request, name)
Exemplo n.º 9
0
def serve_mixed(request, *args, **kwargs):
    """
    First attempts to serve the file from the filesystem,
    then tries the database.
    """
    name = kwargs.get('name') or kwargs.get('path')
    document_root = kwargs.get('document_root')
    document_root = document_root or settings.MEDIA_ROOT
    try:
        # First attempt to serve from filesystem.
        return django_serve(request, name, document_root)
    except Http404:
        # Then try serving from database.
        return serve(request, name)
Exemplo n.º 10
0
def serve(request, path, document_root=None, show_indexes=False):
    '''
    处理静态文件请求
    '''
    try:
        response=django_serve(request, path, document_root, show_indexes)
    except Http404, e:
        if "+" in path:
            try:
                response=serve_combined_files(path, document_root)
            except:
                import traceback; traceback.print_exc()
                raise
        else:
            raise
Exemplo n.º 11
0
def serve(request, path, document_root=None, show_indexes=False):
    try:
        response = django_serve(request, path, document_root, show_indexes)
    except Http404 as e:
        if "+" in path:
            try:
                response = serve_combined_files(path, document_root)
            except:
                import traceback
                traceback.print_exc()
                raise
        else:
            raise

    return response
Exemplo n.º 12
0
def serve(request, **kwargs):
    if request.path_info == "/contribute.json":
        # 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})
    _, ext = os.path.splitext(request.path_info)
    if ext:
        return http.HttpResponseNotFound(request.path_info)

    response = django_serve(request, "/index.html", **kwargs)
    if isinstance(response, http.FileResponse):
        max_age = 60 * 60 * 24
        response["cache-control"] = f"max-age={max_age}, public"
    return response
Exemplo n.º 13
0
def serve(request, path, show_indexes=False):
    """
    Serve static files from locations inferred from INSTALLED_APPS and
    STATICFILES_DIRS.

    To use, put a URL pattern such as::

        (r'^(?P<path>.*)$', 'staticfiles.views.serve')

    in your URLconf. You may also set ``show_indexes`` to ``True`` if you'd
    like to serve a basic index of the directory.  This index view will use the
    template hardcoded below, but if you'd like to override it, you can create
    a template called ``static/directory_index``.
    
    """
    absolute_path = resolve(path)
    if not absolute_path:
        raise http.Http404("%r could not be resolved to a static file." % path)
    absolute_path, filename = os.path.split(absolute_path)
    return django_serve(request, path=filename, document_root=absolute_path, show_indexes=show_indexes)
Exemplo n.º 14
0
def serve(request, filename, simple_404=True, **kwargs):
    """
    Serves requested TopLevelFile.

    Checks if requested filename matches existing TopLevelFile object and
    returns 'django.views.static.serve' passing it all unhandled keyword
    arguments. 'filename' keyword argument is required and should be normally
    captured with urlconf. Passing 'simple_404=False' allows to render usual
    404 page with 'handler404'.

    """
    try:
        TopLevelFile.objects.only('id').get(type__file_name=filename)
    except TopLevelFile.DoesNotExist:
        if simple_404:
            return HttpResponseNotFound('file not found')
        else:
            raise Http404

    return django_serve(request, filename, document_root=settings.MEDIA_ROOT,
                        **kwargs)
Exemplo n.º 15
0
def serve(request, path, show_indexes=False):
    """
    Serve static files from locations inferred from INSTALLED_APPS and
    STATICFILES_DIRS.

    To use, put a URL pattern such as::

        (r'^(?P<path>.*)$', 'staticfiles.views.serve')

    in your URLconf. You may also set ``show_indexes`` to ``True`` if you'd
    like to serve a basic index of the directory.  This index view will use the
    template hardcoded below, but if you'd like to override it, you can create
    a template called ``static/directory_index``.
    
    """
    absolute_path = resolve(path)
    if not absolute_path:
        raise http.Http404('%r could not be resolved to a static file.' % path)
    absolute_path, filename = os.path.split(absolute_path)
    return django_serve(request, path=filename, document_root=absolute_path,
                        show_indexes=show_indexes)
Exemplo n.º 16
0
def serve(request, path, document_root=None, show_indexes=False):
    if not settings.USE_BUNDLES:
        path = posixpath.normpath(urllib.unquote(path))
        path = path.lstrip('/')
        newpath = ''
        for part in path.split('/'):
            if not part:
                # Strip empty path components.
                continue
            drive, part = os.path.splitdrive(part)
            head, part = os.path.split(part)
            if part in (os.curdir, os.pardir):
                # Strip '.' and '..' in path.
                continue
            newpath = os.path.join(newpath, part).replace('\\', '/')

        fullpath = os.path.join(document_root, newpath)

        cached = get_file(fullpath)
        if cached:
            return HttpResponse(cached['contents'], content_type=cached['mimetype'])

    return django_serve(request, path, document_root=document_root, show_indexes=show_indexes)
Exemplo n.º 17
0
def serve(request, path, document_root=None, show_indexes=False):
    if not settings.USE_BUNDLES:
        path = posixpath.normpath(urllib.unquote(path))
        path = path.lstrip('/')
        newpath = ''
        for part in path.split('/'):
            if not part:
                # Strip empty path components.
                continue
            drive, part = os.path.splitdrive(part)
            head, part = os.path.split(part)
            if part in (os.curdir, os.pardir):
                # Strip '.' and '..' in path.
                continue
            newpath = os.path.join(newpath, part).replace('\\', '/')

        fullpath = os.path.join(document_root, newpath)

        cached = get_file(fullpath)
        if cached:
            return HttpResponse(cached['contents'], mimetype=cached['mimetype'])

    return django_serve(request, path, document_root=document_root, show_indexes=show_indexes)
Exemplo n.º 18
0
def serve(request, path, document_root=None, show_indexes=False, cache=True,
          fallback_server=None, auth_user=None, auth_pass=None):
    """
    Serve static files using Django's static file function but if it returns a
    404, then attempt to find the file on the fallback_server. Optionally and by
    default, cache the file locally.
    
    To use, put a URL pattern such as::

        (r'^(?P<path>.*)$', 'static_fallback.serve', {'document_root' : '/path/to/my/files/'})

    in your URLconf. You must provide the ``document_root`` param (required by 
    Django). You may also set ``show_indexes`` to ``True`` if you'd like to 
    serve a basic index of the directory. These parameters are passed through
    directly to django.views.static.serve. You should see the doc_string there 
    for details.
    
    Passing cache to True (default) copies the file locally.
    
    Be sure to set settings.FALLBACK_STATIC_URL to something like:
    
    FALLBACK_STATIC_URL = 'http://myprodsite.com'
    
    Alternatively, you can also tell it the fallback server as a parameter
    sent in the URLs.
    
    Author: Ed Menendez ([email protected])
    Concept: Johnny Dobbins
    """

    # get out of the eway if the requested path does not start with any of the prefixes
    # specified in FALLBACK_STATIC_PREFIXES
    if not any(imap(path.startswith, getattr(settings, 'FALLBACK_STATIC_PREFIXES', []))):
        # let django take care of it
        return django_serve(request, path, document_root, show_indexes)
    
    if fallback_server is None:
        try:
            fallback_server = settings.FALLBACK_STATIC_URL
        except AttributeError:
            print u"You're using static_fallback.serve to serve static content " + \
                   "however settings.FALLBACK_STATIC_URL has not been set."
    
    # Save this for later to pass to Django.
    original_path = path
    
    # This was mostly copied from Django's version. We need the filepath for 
    # caching and it also serves as an optimization. If the file is not found
    # then there's no reason to go through the Django process.
    path = posixpath.normpath(urllib.unquote(path))
    path = path.lstrip('/')
    newpath = ''
    for part in path.split('/'):
        if not part:
            # Strip empty path components.
            continue
        drive, part = os.path.splitdrive(part)
        head, part = os.path.split(part)
        if part in (os.curdir, os.pardir):
            # Strip '.' and '..' in path.
            continue
        newpath = os.path.join(newpath, part).replace('\\', '/')
    if newpath and path != newpath:
        return HttpResponseRedirect(newpath)                    # RETURN
    fullpath = os.path.join(document_root, newpath)
    # End of the "mostly from Django" section.

    try:
        # Don't bother trying the Django function if the file isn't there.
        if not os.path.isdir(fullpath) and not os.path.exists(fullpath):
            raise Http404, '"%s" does not exist' % fullpath     # RAISE
        else:
            # Pass through cleanly to Django's verson
            return django_serve(                                # RETURN
                        request, original_path, document_root, show_indexes)
    except Http404:
        if fallback_server:
            # Attempt to find it on the remote server.
            path = request.path_info
            if path.startswith(settings.MEDIA_URL):
                path = path[len(settings.MEDIA_URL):]
            fq_url = '%s%s' % (fallback_server, urllib.quote(path))
            print "fallback_serve: trying to fetch from %s" % fq_url
            try:
                contents = fetch(fq_url)
            except urllib2.HTTPError, e:
                # Naive to assume a 404 - ed
                raise Http404, 'Cannot get %s - %s' % (fq_url, str(e))   # RAISE
            else:
                # Found the doc. Return it to response.
                mimetype = mimetypes.guess_type(fq_url)
                response = HttpResponse(contents, mimetype=mimetype[0])
                
                # Do we need to cache the file?
                if cache:
                    if not os.path.exists(os.path.split(fullpath)[0]):
                        os.makedirs(os.path.split(fullpath)[0])
                    f = open(fullpath, 'wb+')
                    f.write(contents)
                    f.close()
                
                # Success! We have the file. Send it back.
                return response                                 # RETURN
        else:
            # No fallback_server was defined. So, it's really a 404 now.
            raise Http404                                       # RAISE
Exemplo n.º 19
0
def serve(request,
          path,
          document_root=None,
          show_indexes=False,
          cache=True,
          fallback_server=None,
          auth_user=None,
          auth_pass=None):
    """
    Serve static files using Django's static file function but if it returns a
    404, then attempt to find the file on the fallback_server. Optionally and by
    default, cache the file locally.
    
    To use, put a URL pattern such as::

        (r'^(?P<path>.*)$', 'static_fallback.serve', {'document_root' : '/path/to/my/files/'})

    in your URLconf. You must provide the ``document_root`` param (required by 
    Django). You may also set ``show_indexes`` to ``True`` if you'd like to 
    serve a basic index of the directory. These parameters are passed through
    directly to django.views.static.serve. You should see the doc_string there 
    for details.
    
    Passing cache to True (default) copies the file locally.
    
    Be sure to set settings.FALLBACK_STATIC_URL to something like:
    
    FALLBACK_STATIC_URL = 'http://myprodsite.com'
    
    Alternatively, you can also tell it the fallback server as a parameter
    sent in the URLs.
    
    Author: Ed Menendez ([email protected])
    Concept: Johnny Dobbins
    """

    # get out of the eway if the requested path does not start with any of the prefixes
    # specified in FALLBACK_STATIC_PREFIXES
    if not any(
            imap(path.startswith,
                 getattr(settings, 'FALLBACK_STATIC_PREFIXES', []))):
        # let django take care of it
        return django_serve(request, path, document_root, show_indexes)

    if fallback_server is None:
        try:
            fallback_server = settings.FALLBACK_STATIC_URL
        except AttributeError:
            print u"You're using static_fallback.serve to serve static content " + \
                   "however settings.FALLBACK_STATIC_URL has not been set."

    # Save this for later to pass to Django.
    original_path = path

    # This was mostly copied from Django's version. We need the filepath for
    # caching and it also serves as an optimization. If the file is not found
    # then there's no reason to go through the Django process.
    path = posixpath.normpath(urllib.unquote(path))
    path = path.lstrip('/')
    newpath = ''
    for part in path.split('/'):
        if not part:
            # Strip empty path components.
            continue
        drive, part = os.path.splitdrive(part)
        head, part = os.path.split(part)
        if part in (os.curdir, os.pardir):
            # Strip '.' and '..' in path.
            continue
        newpath = os.path.join(newpath, part).replace('\\', '/')
    if newpath and path != newpath:
        return HttpResponseRedirect(newpath)  # RETURN
    fullpath = os.path.join(document_root, newpath)
    # End of the "mostly from Django" section.

    try:
        # Don't bother trying the Django function if the file isn't there.
        if not os.path.isdir(fullpath) and not os.path.exists(fullpath):
            raise Http404, '"%s" does not exist' % fullpath  # RAISE
        else:
            # Pass through cleanly to Django's verson
            return django_serve(  # RETURN
                request, original_path, document_root, show_indexes)
    except Http404:
        if fallback_server:
            # Attempt to find it on the remote server.
            path = request.path_info
            if path.startswith(settings.MEDIA_URL):
                path = path[len(settings.MEDIA_URL):]
            fq_url = '%s%s' % (fallback_server, urllib.quote(path))
            print "fallback_serve: trying to fetch from %s" % fq_url
            try:
                contents = fetch(fq_url)
            except urllib2.HTTPError, e:
                # Naive to assume a 404 - ed
                raise Http404, 'Cannot get %s - %s' % (fq_url, str(e))  # RAISE
            else:
                # Found the doc. Return it to response.
                mimetype = mimetypes.guess_type(fq_url)
                response = HttpResponse(contents, mimetype=mimetype[0])

                # Do we need to cache the file?
                if cache:
                    if not os.path.exists(os.path.split(fullpath)[0]):
                        os.makedirs(os.path.split(fullpath)[0])
                    f = open(fullpath, 'wb+')
                    f.write(contents)
                    f.close()

                # Success! We have the file. Send it back.
                return response  # RETURN
        else:
            # No fallback_server was defined. So, it's really a 404 now.
            raise Http404  # RAISE