def generate_sitemap(): """Deferred task to generate a Sitemap.xml for all published blog posts""" root = etree.Element('urlset', { 'attr': 'http://www.sitemaps.org/schemas/sitemap/0.9' }) def add_url(location, last_modified=None, change_freq='always', priority=0.5): e = etree.SubElement(root, 'url') etree.SubElement(e, 'loc').text = location if last_modified: etree.SubElement(e, 'lastmod').text = last_modified.strftime('%Y-%m-%dT%H:%M:%S+00:00') etree.SubElement(e, 'changefreq').text = change_freq etree.SubElement(e, 'priority').text = str(priority) for p in Post.objects_published().order('-created_at'): add_url(p.absolute_url(external=True), p.updated_at) for c in Category.all(): add_url(c.absolute_url(external=True)) add_url(url_for('blog.index', _external=True), priority=1.0) add_url(url_for('blog.latest_posts', _external=True)) logging.info('Generated sitemap.xml with %d blog posts', len(root)) xml = etree.tostring(root, encoding='utf-8', pretty_print=True, xml_declaration=True) cache.set('blog_sitemaps', xml) return xml
def latest_posts(): feed = AtomFeed('Libcoffee.net', feed_url=request.url, url=request.url_root) for p in Post.objects_published().order('-created_at')[:POSTS_PER_PAGE]: feed.add(p.title, unicode(p.__html__()), content_type='html', author=p.author.nickname(), url=p.absolute_url(external=True), updated=p.updated_at, published=p.created_at) return Response(feed.to_string(), mimetype='application/atom+xml')
def get_posts(year, month=None, day=None, slug=None): """Helper function to load posts, optionally by year, month, day and slug""" queryset = Post.objects_published().order('-created_at') date = datetime(int(year), month and int(month) or 1, day and int(day) or 1) if date > datetime.now(): abort(404) date2 = timedelta(days=(month is None and 365 or day is None and 31 or 1)) if slug: queryset = queryset.filter('slug =', slug) return queryset.filter('created_at >=', date) \ .filter('created_at <', date + date2)
def posts_by_category(category): """Page listing posts for a category""" q = Post.objects_published().order('-created_at') \ .filter('categories =', category) return render_posts_paginated(q)
def index(): """Main page""" q = Post.objects_published().order('-created_at') return render_posts_paginated(q)