Django-fr

Forum

#1 21-11-2011 18:16:49

Rémy HUBSCHER
Membre
Inscription : 11-08-2010
Messages : 161

[Résolu] Django Storage collectstatic

Bonjour,

Une petite question.

Je suis en train de mettre en place un système de themes pour un site.
L'idée est de simplifier la chose avec un répertoire themes/ contenant un répertoire du nom du themes, les templates et les fichiers statics.

Par exemple :

themes/
└── jungleland
    ├── jungleland.jpg
    ├── MANIFEST.json
    ├── static
    │   ├── css
    │   │   ├── ie6.css
    │   │   ├── Jungleland.css
    │   │   ├── reset.css
    │   │   └── screen.css
    │   └── images
    │       ├── arrow-up.gif
    │       ├── bg.gif
    │       ├── bullet.gif
    │       ├── button-bg.png
    │       ├── button-hover-bg.png
    │       ├── clock.gif
    │       ├── comment.gif
    │       ├── content-bg.jpg
    │       ├── email.gif
    │       ├── feed-icon14.gif
    │       ├── feed-icon16.gif
    │       ├── firefox-gray.jpg
    │       ├── footer-bg.png
    │       ├── gravatar.jpg
    │       ├── header-bg.jpg
    │       ├── header-search.png
    │       ├── img-featured.jpg
    │       ├── img-post.jpg
    │       ├── left-nav-bg.gif
    │       ├── quote.gif
    │       ├── ribbon.gif
    │       ├── ribbon.png
    │       ├── right-nav-bg.gif
    │       ├── search.png
    │       ├── sep-bg.jpg
    │       ├── thumb-1.jpg
    │       ├── thumb-2.jpg
    │       ├── thumb-3.jpg
    │       ├── thumb-4.jpg
    │       ├── thumb.jpg
    │       └── twitter.gif
    └── templates
        ├── archives.html
        ├── blog.html
        ├── index.html
        └── style.html

J'ai donc fait un template loader :

"""
Wrapper for loading templates from "themes" directories in modulo.
"""

import os
import sys

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.template.base import TemplateDoesNotExist
from django.template.loader import BaseLoader
from django.utils._os import safe_join
from django.utils.importlib import import_module

# At compile time, cache the directories to search.
fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
app_template_dirs = list(getattr(settings, 'THEMES_DIRS', []))

# It won't change, so convert it to a tuple to save memory.
app_template_dirs = tuple(app_template_dirs)

class Loader(BaseLoader):
    is_usable = True

    def get_template_sources(self, template_name, template_dirs=None):
        """
        Returns the absolute paths to "template_name", when appended to each
        directory in "template_dirs". Any paths that don't lie inside one of the
        template dirs are excluded from the result set, for security reasons.
        """
        if not template_dirs:
            template_dirs = app_template_dirs

        
        dirs = template_name.split('/')
        if len(dirs) >= 3 and dirs[0] == 'themes':
            template_name = u'/'.join([dirs[1], 'templates']+dirs[2:])

            for template_dir in template_dirs:
                print safe_join(template_dir, template_name)
                try:
                    yield safe_join(template_dir, template_name)
                except UnicodeDecodeError:
                    # The template dir name was a bytestring that wasn't valid UTF-8.
                    raise
                except ValueError:
                    # The joined path was located outside of template_dir.
                    pass

    def load_template_source(self, template_name, template_dirs=None):
        for filepath in self.get_template_sources(template_name, template_dirs):
            try:
                file = open(filepath)
                try:
                    return (file.read().decode(settings.FILE_CHARSET), filepath)
                finally:
                    file.close()
            except IOError:
                pass
        raise TemplateDoesNotExist(template_name)

_loader = Loader()

def load_template_source(template_name, template_dirs=None):
    # For backwards compatibility
    import warnings
    warnings.warn(
        "'modulo.layout.template_loader.load_template_source' is deprecated; use 'modulo.layout.template_loader.Loader' instead.",
        DeprecationWarning
    )
    return _loader.load_template_source(template_name, template_dirs)
load_template_source.is_usable = True

Et je cherche à faire un STATIC_FINDERS :

import os
import sys
from django.conf import settings
from django.contrib.staticfiles.finders import BaseStorageFinder
from django.utils.importlib import import_module
from django.utils._os import safe_join
from django.contrib.staticfiles import utils

from modulo.loaders.storage import ThemeStorage


class StaticFinder(BaseStorageFinder):

    storage = ThemeStorage

    def __init__(self, apps=None, *args, **kwargs):
        self.locations = list(getattr(settings, 'THEMES_DIRS', []))
        super(StaticFinder, self).__init__(*args, **kwargs)

    def find(self, path, all=False):
        """
        Looks for files in the theme locations
        as defined in ``THEMES_DIRS``.
        """
        matches = []
        for root in self.locations:
            matched_path = self.find_location(root, path)
            if matched_path:
                if not all:
                    return matched_path
                matches.append(matched_path)
        return matches

    def find_location(self, root, path):
        """
        Finds a requested static file in a location, returning the found
        absolute path (or ``None`` if no match).
        """
        dirs = path.split('/')
        if len(dirs) >= 3 and dirs[0] == 'themes':
            path = u'/'.join([dirs[1], 'static']+dirs[2:])
            path = safe_join(root, path)
            if os.path.exists(path):
                return path
        else:
            return None

En DEBUG ça fonctionne plutôt bien.
Le problème c'est pour faire le ThemeStorage pour que le collectstatic fonctionne bien.

À l'heure actuelle, le collectstatic recolte les fichiers tels qu'ils sont alors que j'aimerais qu'il modifie l'arborescence pour quelle ressemble à ça :

/static/themes/jungleband/css/ et non à /static/jungleband/static/css

Avez-vous une idée de comment je peux faire ça ?

Dernière modification par Rémy HUBSCHER (22-11-2011 09:45:22)

Hors ligne

#2 22-11-2011 09:44:13

Rémy HUBSCHER
Membre
Inscription : 11-08-2010
Messages : 161

Re : [Résolu] Django Storage collectstatic

J'ai finalement modifié un peu l'arborescence et ça fonctionne.

Hors ligne

#3 22-11-2011 13:52:15

Eric Veiras Galisson
Membre
Inscription : 11-08-2010
Messages : 12

Re : [Résolu] Django Storage collectstatic

Salut,

il y a quelque temps j'avais fait une appli pour gérer les thèmes,
notamment permettant de gérer des thèmes par utilisateur.
Elle n'a pas été touché depuis longtemps, je ne sais même pas si elle est
compatible avec les dernières versions de django, mais si ça peut servir tu
peux la trouver là https://bitbucket.org/daks/django-userthemes

Eric

Hors ligne

Pied de page des forums