SlideShare uma empresa Scribd logo
1 de 16
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

Mais conteúdo relacionado

Mais procurados

Paperjs presentation
Paperjs presentationPaperjs presentation
Paperjs presentation
sharp-blade
 

Mais procurados (17)

gd
gdgd
gd
 
React for Beginners
React for BeginnersReact for Beginners
React for Beginners
 
Big mountain data competition training: scraping-n-munge
Big mountain data competition training: scraping-n-mungeBig mountain data competition training: scraping-n-munge
Big mountain data competition training: scraping-n-munge
 
AWS user group September 2017 - Rob Ribeiro "Seeking Solutions for Debugging ...
AWS user group September 2017 - Rob Ribeiro "Seeking Solutions for Debugging ...AWS user group September 2017 - Rob Ribeiro "Seeking Solutions for Debugging ...
AWS user group September 2017 - Rob Ribeiro "Seeking Solutions for Debugging ...
 
F(2)
F(2)F(2)
F(2)
 
script
scriptscript
script
 
Paperjs presentation
Paperjs presentationPaperjs presentation
Paperjs presentation
 
Bubble Sort
Bubble SortBubble Sort
Bubble Sort
 
Git avançado
Git avançadoGit avançado
Git avançado
 
181220_slideshare_git
181220_slideshare_git181220_slideshare_git
181220_slideshare_git
 
Php 7.x 8.0 and hhvm and
Php 7.x 8.0 and hhvm and Php 7.x 8.0 and hhvm and
Php 7.x 8.0 and hhvm and
 
Testing Black Box
Testing Black BoxTesting Black Box
Testing Black Box
 
Ruby on Rails - UNISO
Ruby on Rails - UNISORuby on Rails - UNISO
Ruby on Rails - UNISO
 
파이썬 웹 서비스 구성과 이해
파이썬 웹 서비스 구성과 이해파이썬 웹 서비스 구성과 이해
파이썬 웹 서비스 구성과 이해
 
Functional php
Functional phpFunctional php
Functional php
 
Flex With Rubyamf
Flex With RubyamfFlex With Rubyamf
Flex With Rubyamf
 
From Javascript To Haskell
From Javascript To HaskellFrom Javascript To Haskell
From Javascript To Haskell
 

Semelhante a The Django Book CH13 Generating Non-HTML Content

Gae Meets Django
Gae Meets DjangoGae Meets Django
Gae Meets Django
fool2nd
 
The Best (and Worst) of Django
The Best (and Worst) of DjangoThe Best (and Worst) of Django
The Best (and Worst) of Django
Jacob Kaplan-Moss
 
The Power of Rails 2.3 Engines & Templates
The Power of Rails 2.3 Engines & TemplatesThe Power of Rails 2.3 Engines & Templates
The Power of Rails 2.3 Engines & Templates
Tse-Ching Ho
 

Semelhante a The Django Book CH13 Generating Non-HTML Content (20)

Gae Meets Django
Gae Meets DjangoGae Meets Django
Gae Meets Django
 
Pyramid Lighter/Faster/Better web apps
Pyramid Lighter/Faster/Better web appsPyramid Lighter/Faster/Better web apps
Pyramid Lighter/Faster/Better web apps
 
Keeping the frontend under control with Symfony and Webpack
Keeping the frontend under control with Symfony and WebpackKeeping the frontend under control with Symfony and Webpack
Keeping the frontend under control with Symfony and Webpack
 
Django
DjangoDjango
Django
 
The Best (and Worst) of Django
The Best (and Worst) of DjangoThe Best (and Worst) of Django
The Best (and Worst) of Django
 
Django - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazosDjango - Framework web para perfeccionistas com prazos
Django - Framework web para perfeccionistas com prazos
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Django Show
Django ShowDjango Show
Django Show
 
Grunt & Front-end Workflow
Grunt & Front-end WorkflowGrunt & Front-end Workflow
Grunt & Front-end Workflow
 
The Future of CSS with Web components
The Future of CSS with Web componentsThe Future of CSS with Web components
The Future of CSS with Web components
 
The Future of CSS with Web Components
The Future of CSS with Web ComponentsThe Future of CSS with Web Components
The Future of CSS with Web Components
 
Introduction to angular js
Introduction to angular jsIntroduction to angular js
Introduction to angular js
 
How to replace rails asset pipeline with webpack?
How to replace rails asset pipeline with webpack?How to replace rails asset pipeline with webpack?
How to replace rails asset pipeline with webpack?
 
The Power of Rails 2.3 Engines & Templates
The Power of Rails 2.3 Engines & TemplatesThe Power of Rails 2.3 Engines & Templates
The Power of Rails 2.3 Engines & Templates
 
Building Cloud-Backed Mobile Apps (MBL402) | AWS re:Invent 2013
Building Cloud-Backed Mobile Apps (MBL402) | AWS re:Invent 2013Building Cloud-Backed Mobile Apps (MBL402) | AWS re:Invent 2013
Building Cloud-Backed Mobile Apps (MBL402) | AWS re:Invent 2013
 
Building a Dynamic Website Using Django
Building a Dynamic Website Using DjangoBuilding a Dynamic Website Using Django
Building a Dynamic Website Using Django
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know
 
Mongo+java (1)
Mongo+java (1)Mongo+java (1)
Mongo+java (1)
 
Python tools to deploy your machine learning models faster
Python tools to deploy your machine learning models fasterPython tools to deploy your machine learning models faster
Python tools to deploy your machine learning models faster
 
James Thomas - Serverless Machine Learning With TensorFlow - Codemotion Berli...
James Thomas - Serverless Machine Learning With TensorFlow - Codemotion Berli...James Thomas - Serverless Machine Learning With TensorFlow - Codemotion Berli...
James Thomas - Serverless Machine Learning With TensorFlow - Codemotion Berli...
 

Último

Último (20)

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 

The Django Book CH13 Generating Non-HTML Content

  • 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
  • 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