5. PDF Hello World
from reportlab.pdfgen import canvas
from django.http import HttpResponse
def hello_pdf(request):
# Create the HttpResponse object with the appropriate PDF headers.
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=hello.pdf'
# Create the PDF object, using the response object as its "file."
p = canvas.Canvas(response)
# Draw things on the PDF. Here's where the PDF generation happens.
p.drawString(100, 100, "Hello world.")
# Close the PDF object cleanly, and we're done.
p.showPage()
p.save()
return response
6. PDF Hello World (w. cStringIO)
from cStringIO import StringIO
from reportlab.pdfgen import canvas
from django.http import HttpResponse
def hello_pdf(request):
# Create the HttpResponse object with the appropriate PDF headers.
response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=hello.pdf'
temp = StringIO()
p = canvas.Canvas(temp)
p.drawString(100, 100, "Hello world. (w. StringIO)")
p.showPage()
p.save()
# Get the value of the StringIO buffer and write it to the
response.
response.write(temp.getvalue())
return response
7. Others Format Libraries
● ZIP files
– zipfile
– tarfile
● Dynamics images
– PIL
● Plots and charts
– matplotlib
– pygraphviz
9. SiteMap Installation
● settings.py
– Add 'django.contrib.sitemaps' into
INSTALLED_APPS
– Make sure that
'django.template.loaders.app_directories.load_tem
plate_source' is in your TEMPLATE_LOADERS
setting
11. SiteMap Class Structure
● items (required)
– Doesn't care about the type
● location (optional)
– “absolute URL”
● Good: '/foo/bar/'
● Bad: 'example.com/foo/bar/'
● Bad: 'http://example.com/foo/bar/'
– Default: calling get_absolute_url() on each object
12. SiteMap Class Structure (ctn')
● lastmod (optional)
– The object’s “last modification” date
● changefreq (optional)
– How often the object changes.
● 'always', 'hourly', 'daily', 'weekly', 'monthly', 'yearly',
'never'
● priority (optional)
– Value is between 0.0 ~ 1.0 (default: 0.5)
13. A Sitemap Class Example
from django.contrib.sitemaps import Sitemap
from mysite.blog.models import Entry
class BlogSitemap(Sitemap):
changefreq = "never"
Priority = 0.5
def items(self):
return Entry.objects.filter(is_draft=False)
def lastmod(self, obj):
return obj.pub_date
14. Pinging Google
● To make Google reindex your sitemap
● django.contrib.sitemaps.ping_google()
– sitemap_url (optional)
● Should be the absolute URL of your sitemap.xml
● Usually we use save() method to call
ping_google():
15. save() for ping_google()
from django.contrib.sitemaps import ping_google
class Entry(models.Model):
# ...
def save(self, *args, **kwargs):
super(Entry, self).save(*args, **kwargs)
try:
ping_google()
except Exception:
# Bare 'except' because we could get a variety
# of HTTP-related exceptions.
pass