The Django Book CH13 Generating Non-HTML Content
Upcoming SlideShare
Loading in...5
×

Like this? Share it with your network

Share

The Django Book CH13 Generating Non-HTML Content

  • 432 views
Uploaded on

This slide is an introduction of "The Django Book" chapter #13 in Taipei.Py, Aug. 20, 2013.

This slide is an introduction of "The Django Book" chapter #13 in Taipei.Py, Aug. 20, 2013.

More in: Technology , Education
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
432
On Slideshare
428
From Embeds
4
Number of Embeds
1

Actions

Shares
Downloads
1
Comments
0
Likes
2

Embeds 4

https://twitter.com 4

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Generating Non-HTML Content Django Meetup Johnny Wang Aug. 20, 2013
  • 2. A Simple Example... ● A simple non-HTML example: loading an image from django.http import HttpResponse def my_image(request): image_data = open("/path/to/my/image.png", "rb").read() return HttpResponse(image_data, mimetype="image/png")
  • 3. Generating CSV files import csv from django.http import HttpResponse UNRULY_PASSENGERS = [146,184,235,200,226,251,299,273,281,304,203] def unruly_passengers_csv(request): response = HttpResponse(mimetype='text/csv') response['Content-Disposition'] = 'attachment; filename=unruly.csv' writer = csv.writer(response) writer.writerow(['Year', 'Unruly Airline Passengers']) for (year, num) in zip(range(1995, 2006), UNRULY_PASSENGERS): writer.writerow([year, num]) return response
  • 4. PDF Open Source Library pip install reportlab
  • 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
  • 8. Site Map
  • 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
  • 10. SiteMap Initialization ● urls.py (r'^sitemap.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}) ● File name is not important, but the location is.
  • 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
  • 16. Thank You