Back to index

plone3  3.1.7
sitemap.py
Go to the documentation of this file.
00001 from Products.Five import BrowserView
00002 from zope.publisher.interfaces import NotFound
00003 from Products.CMFCore.utils import getToolByName
00004 from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
00005 
00006 from gzip import GzipFile
00007 from cStringIO import StringIO
00008 
00009 from plone.memoize import ram
00010 
00011 def _render_cachekey(fun, self):
00012     # Cache by filename
00013     url_tool = getToolByName(self.context, 'portal_url')
00014     return '%s/%s' % (url_tool(), self.filename)
00015 
00016 class SiteMapView(BrowserView):
00017     """Creates the sitemap as explained in the specifications.
00018 
00019     http://www.sitemaps.org/protocol.php
00020     """
00021 
00022     template = ViewPageTemplateFile('sitemap.xml')
00023 
00024     def __init__(self, context, request):
00025         self.context = context
00026         self.request = request
00027         self.filename = 'sitemap.xml.gz'
00028 
00029     def objects(self):
00030         """Returns the data to create the sitemap."""
00031         catalog = getToolByName(self.context, 'portal_catalog')
00032         for item in catalog.searchResults({'Language': 'all'}):
00033             yield {
00034                 'loc': item.getURL(),
00035                 'lastmod': item.modified.ISO8601(),
00036                 #'changefreq': 'always', # hourly/daily/weekly/monthly/yearly/never
00037                 #'prioriy': 0.5, # 0.0 to 1.0
00038             }
00039 
00040     @ram.cache(_render_cachekey)
00041     def generate(self):
00042         """Generates the Gzipped sitemap."""
00043         xml = self.template()
00044         fp = StringIO()
00045         gzip = GzipFile(self.filename, 'w', 9, fp)
00046         gzip.write(xml)
00047         gzip.close()
00048         data = fp.getvalue()
00049         fp.close()
00050         return data
00051 
00052     def __call__(self):
00053         """Checks if the sitemap feature is enable and returns it."""
00054         sp = getToolByName(self.context, 'portal_properties').site_properties
00055         if not sp.enable_sitemap:
00056             raise NotFound(self.context, self.filename, self.request)
00057 
00058         self.request.response.setHeader('Content-Type',
00059                                         'application/octet-stream')
00060         return self.generate()