• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
The Django Book CH13 Generating Non-HTML Content
 

The Django Book CH13 Generating Non-HTML Content

on

  • 281 views

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.

Statistics

Views

Total Views
281
Views on SlideShare
281
Embed Views
0

Actions

Likes
0
Downloads
1
Comments
0

0 Embeds 0

No embeds

Accessibility

Upload Details

Uploaded via as OpenOffice

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    The Django Book CH13 Generating Non-HTML Content The Django Book CH13 Generating Non-HTML Content Presentation Transcript

    • Generating Non-HTML Content Django Meetup Johnny Wang Aug. 20, 2013
    • 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")
    • 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
    • PDF Open Source Library pip install reportlab
    • 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
    • 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
    • Others Format Libraries ● ZIP files – zipfile – tarfile ● Dynamics images – PIL ● Plots and charts – matplotlib – pygraphviz
    • Site Map
    • 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
    • SiteMap Initialization ● urls.py (r'^sitemap.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}) ● File name is not important, but the location is.
    • 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
    • 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)
    • 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
    • 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():
    • 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
    • Thank You