Login

Expand(flatten) url patterns

Author:
grillermo
Posted:
November 21, 2012
Language:
Python
Version:
1.4
Score:
0 (after 0 ratings)

This is a small function for those time when you want a list of all your urls, expanding included urls, so in the end is like all your urls are in one module. This function recursively does it, so it doesnt matter how nested the includes are in the end you get one flat list.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
def expand_patterns(urlpatterns):
    new_patterns = []
    def recursive_expand(patterns):
        for p in patterns:
            if getattr(p,'url_patterns',False):
                recursive_expand(p.url_patterns)
            else:
                new_patterns.append(p)
    recursive_expand(patterns)
    return new_patterns

# Example usage, a Sitemap class
class StaticSitemap(Sitemap):
    """Return the static sitemap items"""
    priority = 0.4
    changefreq = 'yearly'

    def __init__(self, patterns):
        self.patterns = expand_patterns(patterns)
        self._items = {}
        self._initialize()

    def _initialize(self):
        do_not_show = ['logout','admin','login']
        for p in self.patterns:
            if [url for url in do_not_show if url in p.regex.pattern]:
                # do not show urls with this word in them
                continue
            if p.regex.groups:
                # do not show dynamic urls, we handle those in another Sitemap class
                continue
            if 'template_name' in p.default_args or 'template' in p.default_args :
                # only urls with templates, because we get mtime from the file
               if getattr(p,'name',False):
                   # only views with names so reverse() can work on them
                   self._items[p.name] = self._get_modification_date(p)

    def _get_modification_date(self, p):
        # We get the modification date from the template itself
        if getattr(p,'default_args',None):
            if 'template_name' in p.default_args:
                template = p.default_args['template_name']
            elif 'template' in p.default_args:
                template = p.default_args['template']
            template_path = self._get_template_path(template)
            mtime = os.stat(template_path).st_mtime
            return datetime.datetime.fromtimestamp(mtime)

    def _get_template_path(self, template_path):
        for template_dir in settings.TEMPLATE_DIRS:
            path = os.path.join(template_dir, template_path)
            if os.path.exists(path):
                return path
        return None

    def items(self):
        return self._items.keys()

    def changefreq(self, obj):
        return 'monthly' #Todo unhardcode this, somehow

    def lastmod(self, obj):
        return self._items[obj]

    def location(self, obj):
        return urlresolvers.reverse(obj)
        

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months, 1 week ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

Please login first before commenting.