简体   繁体   中英

Expand url django patterns

i have standard django 1.4 url patterns:

urlpatterns = patterns('',  
    url('^',include('events.urls')),
    url(r'^$', home, {'template_name':'index.html','mod':None}, name='home'),
    url(r'^contact$',contact, {'template_name':'index.html',
        'mod':'contacto'},name='contact'),
    url('^task/(?P<task_id>[\w+-]+)',celery_tasks,name='tasks'),
)

I want to build my sitemap.xml leaving out some urls, for example that /task url should not appear(it makes no sense for the web spiders). My strategy is passing all the url patterns to my Sitemap class, like this

from sitemaps import EventsSitemap, StaticSitemap

sitemaps = {
    'Events': CandidateSiteMap,
    'static': StaticSitemap(urlpatterns),
}

As you can see i´m passing the patterns to the class, so i can later filter the urls like this

class StaticSitemap(Sitemap):

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

    def _initialize(self):
        do_not_show = ['tasks']
        for p in self.patterns:
            # no dynamic urls in this class (we handle those separately)
            if not p.regex.groups:
                if getattr(p,'name',False) and p.name not in do_not_show:
                   self._items[p.name] = self._get_modification_date(p)

So i keep this list of do_not_show url names and thats how i filter out urls, so far so good, the problem is with included urls such as:

url('^',include('events.urls')),

I can't just iterate on self.patterns and get the included urls, i have to expand them first, thats my question, how can i do that? How can i get a flat list of urls as if there were no included ones, all were on a single urls module.

Any recommendations to filter out urls in the sitemaps.xml would be most appreciated.

Ok i have to answer my own question because i solved it, what i did was a little function to expand the patterns like this

def expand_patterns(patterns):
    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

This will flatten out the urlpatterns into a single list. So now i can use self.patterns to filter out anything in my Sitemap class :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM