SlideShare ist ein Scribd-Unternehmen logo
1 von 25
Downloaden Sie, um offline zu lesen
Django Class-BasedViews
CoMo Rich Web, October 2010
Agenda
• Python 101
• RegularViews
• GenericViews
• Class-BasedViews
Python 101
# defining a function
def say_hello(subject):
print 'Hello, %s' % subject
# calling a function
say_hello('World')
# defining a function
def say_hello(subject):
print 'Hello, %s' % subject
# calling a function
say_hello('World')
# defining a class
class HelloSayer(object):
def __init__(self, name):
self.name = name
def say_hello(self):
print 'Hello, %s' % self.name
# creating an object instance
i = HelloSayer('World')
i.say_hello()
First-Class Everything
• first-class functions
• can be stored in variables
• can be passed into other functions
• can be returned from functions
• first-class classes
• ditto all the above
f = say_hello
f('Everybody')
cls = MyClass
j = cls('Everybody')
j.say_hello()
Text
class FakeFunction(object):
def __init__(self):
print 'Constructing...'
def __call__(self):
print 'You called?'
f = FakeFunction() # Constructing...
f() # You called?
result = x()
# is `x()` calling a function?
# creating an object?
# or calling a method on an object?
DjangoViews
• a view is a function that takes (at minimum)
an HttpRequest and returns an
HttpResponse
• views usually live in the file views.py
• URLs are routed to views using patterns in
the file urls.py
View Basics
# __init__.py intentionally left blank
# models.py intentionally left blank
# views.py
from django.http import HttpResponse
def homepage(request):
return HttpResponse('<html><body><h1>Welcome to website</h1></body></html>')
# urls.py
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^$', 'myapp.views.homepage'),
)
# views.py
def user_profile(request, username):
# do useful stuff here...
return HttpResponse('''<html><body>
<h1>Profile for user %s</h1>
</body></html>''' % username)
# urls.py
urlpatterns = patterns('',
(r'^user/(w+)/profile$', 'myapp.views.user_profile'),
)
GenericViews
Paving the Cow Paths
• “CRUD” apps have well-known patterns
• dynamic typing allows Django to provide
common view patterns as reusable
functions
# hypothetical URL: /users?page=3
def user_list(request):
page = int(request.GET.get('page', '1')) # sloppy parsing
users = User.objects.all()
per_page = 20
num_pages = math.ceil(len(users) / per_page) # buggy math
if page <= 0 or page > num_pages:
raise Http404()
start_index = (page - 1) * per_page # buggy math
end_index = page * per_page # buggy math
users_on_page = users[start_index:end_index]
context = {
'users': users_on_page,
'page': page,
'num_pages': num_pages
# next or prev pages?
}
return render_to_response('myapp/user_list.html', context)
from django.views.generic import list_detail
# hypothetical URL: /users?page=3
def user_list(request):
return list_detail.object_list(request,
queryset=User.objects.all(),
paginate_by=20)
from django.views.generic import list_detail
# hypothetical URL: /users?staff=y
def user_list(request):
if request.GET.get('staff', 'n').lower() == 'y':
qs = Users.objects.filter(staff=True)
else:
qs = Users.objects.all()
return list_detail.object_list(request,
queryset=qs,
paginate_by=20)
Going off the Beaten Path
• at some point you’ll want to customize the
generic views even more
• wrapping only gets you so far
• what about deeper behavior changes?
• e.g,“delete” should actually flag as
“inactive”
Class-BasedViews
Benefits
• control not just parameters but behavior
• more code reuse
# completely made-up example
from django.views.generic.list_detail import ObjectListView
class UserListView(ObjectListView):
def get_queryset(self):
if self.request.GET.get('staff', 'n').lower() == 'y':
return Users.objects.filter(staff=True)
else:
return Users.objects.all()
# meanwhile, in urls.py...
(r'^users$', 'myapp.views.UserListView')
# completely made-up example
from django.views.generic.create_update import DeleteObjectView
class DeleteUserView(DeleteObjectView):
def perform_deletion(self, user):
user.is_active = False
user.save()
Not a Silver Bullet
• still only allows customization the original
author thought of
• can introduce multithreading issues
• “official” Django views aren’t finished yet
Questions?
Thanks for listening!

Weitere ähnliche Inhalte

Was ist angesagt?

Perl6 operators and metaoperators
Perl6   operators and metaoperatorsPerl6   operators and metaoperators
Perl6 operators and metaoperatorsSimon Proctor
 
PHP Object Injection Vulnerability in WordPress: an Analysis
PHP Object Injection Vulnerability in WordPress: an AnalysisPHP Object Injection Vulnerability in WordPress: an Analysis
PHP Object Injection Vulnerability in WordPress: an AnalysisPositive Hack Days
 
Swift勉強会第3回 〜UIを作ろう②〜
Swift勉強会第3回 〜UIを作ろう②〜Swift勉強会第3回 〜UIを作ろう②〜
Swift勉強会第3回 〜UIを作ろう②〜真次郎 新納
 
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, Germany
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, GermanyLet's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, Germany
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, GermanyBalázs Tatár
 
Ruby 2: some new things
Ruby 2: some new thingsRuby 2: some new things
Ruby 2: some new thingsDavid Black
 
PythonでJWT生成からボット作成、投稿までやってみた
PythonでJWT生成からボット作成、投稿までやってみたPythonでJWT生成からボット作成、投稿までやってみた
PythonでJWT生成からボット作成、投稿までやってみたitoxdev
 
Drupal Field API. Practical usage
Drupal Field API. Practical usageDrupal Field API. Practical usage
Drupal Field API. Practical usagePavel Makhrinsky
 
Python Novice to Ninja
Python Novice to NinjaPython Novice to Ninja
Python Novice to NinjaAl Sayed Gamal
 
Demystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHPDemystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHPAlena Holligan
 
Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014
Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014
Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014Puppet
 
Demystifying Object-Oriented Programming - Midwest PHP
Demystifying Object-Oriented Programming - Midwest PHPDemystifying Object-Oriented Programming - Midwest PHP
Demystifying Object-Oriented Programming - Midwest PHPAlena Holligan
 
PyLecture1 -Python Basics-
PyLecture1 -Python Basics-PyLecture1 -Python Basics-
PyLecture1 -Python Basics-Yoshiki Satotani
 
Class 8 - Database Programming
Class 8 - Database ProgrammingClass 8 - Database Programming
Class 8 - Database ProgrammingAhmed Swilam
 
テストデータどうしてますか?
テストデータどうしてますか?テストデータどうしてますか?
テストデータどうしてますか?Yuki Shibazaki
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretssmueller_sandsmedia
 

Was ist angesagt? (20)

Perl6 operators and metaoperators
Perl6   operators and metaoperatorsPerl6   operators and metaoperators
Perl6 operators and metaoperators
 
PHP Object Injection Vulnerability in WordPress: an Analysis
PHP Object Injection Vulnerability in WordPress: an AnalysisPHP Object Injection Vulnerability in WordPress: an Analysis
PHP Object Injection Vulnerability in WordPress: an Analysis
 
Swift勉強会第3回 〜UIを作ろう②〜
Swift勉強会第3回 〜UIを作ろう②〜Swift勉強会第3回 〜UIを作ろう②〜
Swift勉強会第3回 〜UIを作ろう②〜
 
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, Germany
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, GermanyLet's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, Germany
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, Germany
 
Mootools selectors
Mootools selectorsMootools selectors
Mootools selectors
 
6. hello popescu 2
6. hello popescu 26. hello popescu 2
6. hello popescu 2
 
Ruby 2: some new things
Ruby 2: some new thingsRuby 2: some new things
Ruby 2: some new things
 
PythonでJWT生成からボット作成、投稿までやってみた
PythonでJWT生成からボット作成、投稿までやってみたPythonでJWT生成からボット作成、投稿までやってみた
PythonでJWT生成からボット作成、投稿までやってみた
 
Drupal Field API. Practical usage
Drupal Field API. Practical usageDrupal Field API. Practical usage
Drupal Field API. Practical usage
 
Python Novice to Ninja
Python Novice to NinjaPython Novice to Ninja
Python Novice to Ninja
 
Demystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHPDemystifying Object-Oriented Programming - Lone Star PHP
Demystifying Object-Oriented Programming - Lone Star PHP
 
Growing jQuery
Growing jQueryGrowing jQuery
Growing jQuery
 
PageObject
PageObject PageObject
PageObject
 
Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014
Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014
Absolute Beginners Guide to Puppet Through Types - PuppetConf 2014
 
Demystifying Object-Oriented Programming - Midwest PHP
Demystifying Object-Oriented Programming - Midwest PHPDemystifying Object-Oriented Programming - Midwest PHP
Demystifying Object-Oriented Programming - Midwest PHP
 
PyLecture1 -Python Basics-
PyLecture1 -Python Basics-PyLecture1 -Python Basics-
PyLecture1 -Python Basics-
 
Class 8 - Database Programming
Class 8 - Database ProgrammingClass 8 - Database Programming
Class 8 - Database Programming
 
テストデータどうしてますか?
テストデータどうしてますか?テストデータどうしてますか?
テストデータどうしてますか?
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
 
23. CodeIgniter sessions
23. CodeIgniter sessions23. CodeIgniter sessions
23. CodeIgniter sessions
 

Ähnlich wie Django class based views

Writing automation tests with python selenium behave pageobjects
Writing automation tests with python selenium behave pageobjectsWriting automation tests with python selenium behave pageobjects
Writing automation tests with python selenium behave pageobjectsLeticia Rss
 
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby DeveloperVenturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby DeveloperJon Kruger
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosEdgar Suarez
 
Python Development (MongoSF)
Python Development (MongoSF)Python Development (MongoSF)
Python Development (MongoSF)Mike Dirolf
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1Zaar Hai
 
Lo nuevo de Django 1.7 y 1.8
Lo nuevo de Django 1.7 y 1.8Lo nuevo de Django 1.7 y 1.8
Lo nuevo de Django 1.7 y 1.8pedroburonv
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoJoaquim Rocha
 
PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2Graham Dumpleton
 
Object.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examplesObject.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examplesRobert Lujo
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v RubyJano Suchal
 
RubyBarCamp “Полезные gems и plugins”
RubyBarCamp “Полезные gems и plugins”RubyBarCamp “Полезные gems и plugins”
RubyBarCamp “Полезные gems и plugins”apostlion
 
Drupaljam xl 2019 presentation multilingualism makes better programmers
Drupaljam xl 2019 presentation   multilingualism makes better programmersDrupaljam xl 2019 presentation   multilingualism makes better programmers
Drupaljam xl 2019 presentation multilingualism makes better programmersAlexander Varwijk
 
Modularity and Layered Data Model
Modularity and Layered Data ModelModularity and Layered Data Model
Modularity and Layered Data ModelAttila Jenei
 

Ähnlich wie Django class based views (20)

PyUIA 0.3
PyUIA 0.3PyUIA 0.3
PyUIA 0.3
 
Writing automation tests with python selenium behave pageobjects
Writing automation tests with python selenium behave pageobjectsWriting automation tests with python selenium behave pageobjects
Writing automation tests with python selenium behave pageobjects
 
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby DeveloperVenturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
 
Python Development (MongoSF)
Python Development (MongoSF)Python Development (MongoSF)
Python Development (MongoSF)
 
Django Heresies
Django HeresiesDjango Heresies
Django Heresies
 
SOLID Ruby, SOLID Rails
SOLID Ruby, SOLID RailsSOLID Ruby, SOLID Rails
SOLID Ruby, SOLID Rails
 
Django - sql alchemy - jquery
Django - sql alchemy - jqueryDjango - sql alchemy - jquery
Django - sql alchemy - jquery
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1
 
Lo nuevo de Django 1.7 y 1.8
Lo nuevo de Django 1.7 y 1.8Lo nuevo de Django 1.7 y 1.8
Lo nuevo de Django 1.7 y 1.8
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Ruby on Rails
Ruby on RailsRuby on Rails
Ruby on Rails
 
PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2PyCon US 2012 - State of WSGI 2
PyCon US 2012 - State of WSGI 2
 
Django Good Practices
Django Good PracticesDjango Good Practices
Django Good Practices
 
Mojolicious
MojoliciousMojolicious
Mojolicious
 
Object.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examplesObject.__class__.__dict__ - python object model and friends - with examples
Object.__class__.__dict__ - python object model and friends - with examples
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v Ruby
 
RubyBarCamp “Полезные gems и plugins”
RubyBarCamp “Полезные gems и plugins”RubyBarCamp “Полезные gems и plugins”
RubyBarCamp “Полезные gems и plugins”
 
Drupaljam xl 2019 presentation multilingualism makes better programmers
Drupaljam xl 2019 presentation   multilingualism makes better programmersDrupaljam xl 2019 presentation   multilingualism makes better programmers
Drupaljam xl 2019 presentation multilingualism makes better programmers
 
Modularity and Layered Data Model
Modularity and Layered Data ModelModularity and Layered Data Model
Modularity and Layered Data Model
 

Kürzlich hochgeladen

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
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...Martijn de Jong
 
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...Neo4j
 
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 textsMaria Levchenko
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
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.pptxHampshireHUG
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
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 2024The Digital Insurer
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 

Kürzlich hochgeladen (20)

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
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...
 
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...
 
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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 

Django class based views

  • 2. Agenda • Python 101 • RegularViews • GenericViews • Class-BasedViews
  • 4. # defining a function def say_hello(subject): print 'Hello, %s' % subject # calling a function say_hello('World')
  • 5. # defining a function def say_hello(subject): print 'Hello, %s' % subject # calling a function say_hello('World') # defining a class class HelloSayer(object): def __init__(self, name): self.name = name def say_hello(self): print 'Hello, %s' % self.name # creating an object instance i = HelloSayer('World') i.say_hello()
  • 6. First-Class Everything • first-class functions • can be stored in variables • can be passed into other functions • can be returned from functions • first-class classes • ditto all the above
  • 7. f = say_hello f('Everybody') cls = MyClass j = cls('Everybody') j.say_hello() Text
  • 8. class FakeFunction(object): def __init__(self): print 'Constructing...' def __call__(self): print 'You called?' f = FakeFunction() # Constructing... f() # You called?
  • 9. result = x() # is `x()` calling a function? # creating an object? # or calling a method on an object?
  • 11. • a view is a function that takes (at minimum) an HttpRequest and returns an HttpResponse • views usually live in the file views.py • URLs are routed to views using patterns in the file urls.py View Basics
  • 12. # __init__.py intentionally left blank # models.py intentionally left blank # views.py from django.http import HttpResponse def homepage(request): return HttpResponse('<html><body><h1>Welcome to website</h1></body></html>') # urls.py from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^$', 'myapp.views.homepage'), )
  • 13. # views.py def user_profile(request, username): # do useful stuff here... return HttpResponse('''<html><body> <h1>Profile for user %s</h1> </body></html>''' % username) # urls.py urlpatterns = patterns('', (r'^user/(w+)/profile$', 'myapp.views.user_profile'), )
  • 15. Paving the Cow Paths • “CRUD” apps have well-known patterns • dynamic typing allows Django to provide common view patterns as reusable functions
  • 16. # hypothetical URL: /users?page=3 def user_list(request): page = int(request.GET.get('page', '1')) # sloppy parsing users = User.objects.all() per_page = 20 num_pages = math.ceil(len(users) / per_page) # buggy math if page <= 0 or page > num_pages: raise Http404() start_index = (page - 1) * per_page # buggy math end_index = page * per_page # buggy math users_on_page = users[start_index:end_index] context = { 'users': users_on_page, 'page': page, 'num_pages': num_pages # next or prev pages? } return render_to_response('myapp/user_list.html', context)
  • 17. from django.views.generic import list_detail # hypothetical URL: /users?page=3 def user_list(request): return list_detail.object_list(request, queryset=User.objects.all(), paginate_by=20)
  • 18. from django.views.generic import list_detail # hypothetical URL: /users?staff=y def user_list(request): if request.GET.get('staff', 'n').lower() == 'y': qs = Users.objects.filter(staff=True) else: qs = Users.objects.all() return list_detail.object_list(request, queryset=qs, paginate_by=20)
  • 19. Going off the Beaten Path • at some point you’ll want to customize the generic views even more • wrapping only gets you so far • what about deeper behavior changes? • e.g,“delete” should actually flag as “inactive”
  • 21. Benefits • control not just parameters but behavior • more code reuse
  • 22. # completely made-up example from django.views.generic.list_detail import ObjectListView class UserListView(ObjectListView): def get_queryset(self): if self.request.GET.get('staff', 'n').lower() == 'y': return Users.objects.filter(staff=True) else: return Users.objects.all() # meanwhile, in urls.py... (r'^users$', 'myapp.views.UserListView')
  • 23. # completely made-up example from django.views.generic.create_update import DeleteObjectView class DeleteUserView(DeleteObjectView): def perform_deletion(self, user): user.is_active = False user.save()
  • 24. Not a Silver Bullet • still only allows customization the original author thought of • can introduce multithreading issues • “official” Django views aren’t finished yet