Share
Embed
Django Workshop at PyCon PH 2014
Jon Danao
February 16, 2014
Transcript
81 slides
-
Who is Jon Danao? • Mid-30‘s jack-of-all-trades developer • Head
of Technology, Innovations @ ABS-CBN’s Digital Media Division • Award Winner (CMMA, 2001) • Award Winner (Yahoo! Hack Day, 2009) -
Who is Jon Danao? • Speaks several languages: English, Filipino,
Cebuano, Chavacano, HTML, ActionScript, Java, PHP, SQL, Lua, Javascript, Objective-C and Python • Find me • twitter.com/jondanao • facebook.com/jondanao • github.com/jondanao • [email protected] -
Who are you? • Students? • Teachers? • Managers? •
Developers? • PHP / Ruby / Node.js / Java? • Python? Django? • Non-developers? -
Outline 1. Introduction 2. Dev Machine 3. Learning Cycle 4.
The Project 5. Dive Into Django -
What is Django? • Python web framework • Similar to
Ruby on Rails, Code Igniter, Play Framework, Meteor • Encourages rapid development • Clean and pragmatic design • Uses shared-nothing architecture • Uses MVC pattern -
Philosophies Loose Coupling Flexibility KISS Clarity RAD DRY Consistency “For
perfectionists with deadlines” Agility Reusability Predictability -
Who uses Django? • All Mozilla sites migrated from CakePHP
to Django • Firefox add-ons site: • 250k add-ons • 150M views/month • 500M API hits/day Source: http://www.slideshare.net/andymckay/anatomy-of-a-large-django-site-7590098 -
Who uses Django? Source: http://blog.disqus.com/post/62187806135/scaling-django-to-8-billion-page-views • 700k websites • 30M
profiles • 170M comments • 500M unique visitors • 45k requests/sec • 8B page views/day -
Who uses Django? Source: http://expandedramblings.com/index.php/pinterest-stats/ http://highscalability.com/blog/2013/4/15/scaling-pinterest-from-0-to-10s-of-billions-of-page-views-a.html • 70M users •
18M visitors/month • 80M objects in S3 • 500M pins/day • 2.5B page views/month • 1.6B follower rows -
Who uses Django? Source: http://expandedramblings.com/index.php/important-instagram-stats/ • 150M monthly active users
• 55M photo uploads/day • 13k likes/second • 1k comments/second • 16B photos shared • 35M selfies -
Dev Machine 1. Python 2.6, 2.7, 3.2, 3.3 http://www.python.org/getit $
python --version 2. Pip $ [sudo] easy_install pip $ pip --version 3. VirtualEnv $ [sudo] pip install virtualenv $ virtualenv --version 4. Git http://git-scm.com/downloads $ git --version 5. SQLite Browser (optional) -
Code of Conduct • Be welcoming, friendly and patient •
Be considerate • Be respectful • Be careful in the words that you choose • Be constructive than destructive speakup.io/coc.html & djangoproject.com/conduct -
Topics 1. Setup How to start a project 2. Models
How to define your data 3. URLs and Views How to access your data 4. Templates How to render your data -
Pip • Python CLI package management system • Easy to
install a package $ pip install [package-name] • Easy to uninstall a package $ pip uninstall [package-name] • Easy to list all installed packages $ pip freeze > requirements.txt • Easy to install package list $ pip install -r requirements.txt -
VirtualEnv • Creates isolated Python environments • Dependencies between projects
don’t mix • Like having multiple XAMPP installations -
Git • Distribute Version Control System • Developed by Linus
Torvalds • Fast, simple, non-linear, work offline • Practice: http://www.atlassian.com/git/ • $ git init • $ git status • $ git add • $ git commit -
Project • In Django, a “project” is a collection of
apps and site configurations • Can be created via command line • Auto-generates some code - init, settings, urls, wsgi -
Database • No point of using Django if site is
static • Support for PostgreSQL, SQLite3, MySQL, Oracle • GeoDjango works really well with PostgreSQL -
Summary • Pip - package manager • VirtualEnv - isolated
environments • Git - version control • Project - collection of apps • Database - supports SQLite, MySQL, PostgreSQL and Oracle -
Topics 1. Setup How to start a project 2. Models
How to define your data 3. URLs and Views How to access your data 4. Templates How to render your data ✓ -
App • A piece of functionality like articles, comments, ratings,
products in the form of a Python package • App : Django : : Package : Python • A project can have multiple apps. An app can be in multiple projects. • Can be created via command line • To convert a folder into package, add __init__.py -
App Philosophies • Write programs that do one thing and
do it well. • If an app can’t be explained in a single sentence, it should be broken up. • Write reusable, pluggable, distributable apps -
Model • Class that represents objects in db • Defines
structure of data • Class : Table : : Property : Field • Model talks to the ORM that talks to the db • ORM eliminates writing of SQL -
Model Example • Article as our model • It has
properties like: - title - category - author - body - published date • This will be translated into a db table via the command “syncdb” -
App Best Practices • Your app’s name should be the
plural version of its main model • Keep apps small, maximum of 5 models -
Admin Site • Pseudo CMS for CRUD operations • Automatic
creation of interfaces for models • Register the models you want to be editable in admin.py -
Summary • App - piece of functionality • Model -
a class representation of db table • Admin Site - pseudo CMS -
Topics 1. Setup How to start a project 2. Models
How to define your data 3. URLs and Views How to access your data 4. Templates How to render your data ✓ ✓ -
URLConf • Routes a URL pattern to a view •
Uses regex for maximum flexibility • Table of contents for site urlpatterns = patterns('', url(r'^articles/(\d{4})/$', views.year_archive), url(r'^articles/(\d{4})/(\d{2})/$', views.month_archive), url(r'^articles/(\d{4})/(\d{2})/(\d+)/$', views.article_detail), ) -
Views • Again, views do not render HTML! • Handles
requests passed on via the URLConf • Gets data from the model and passes them to the template for rendering • Determines WHAT data the user should see, not HOW data should be rendered -
Querying the Model • Retrieve all objects (aka SELECT *)
all_articles = Article.objects.all() • Retrieve objects with filters (aka WHERE clause) draft_articles = Article.objects.filter(status=1) published_articles = Article.objects.exclude(status=1) • Chaining filters (aka AND operator in WHERE) latest_paquiao_articles = Article.objects .filter(status=1) .exclude(title=’Manny Villar Wins!’) -
Querying the Model • Limiting and offsetting results articles =
Article.objects.all()[:5] articles = Article.objects.all()[5:10] • Sorting objects articles = Article.objects.all().order_by(‘title’) articles = Article.objects.all().order_by(‘-title’) • Retrieving single object article = Article.objects.get(id=1) -
Dunder Methods • __init__, __file__, __unicode__ • Pythonic, common and
idiomatic methods • Used as field lookups in filter(), exclude(), get() • Extremely powerful and intuitive -
Field Lookups • Basic model lookups syntax: field__lookuptype=value Article.objects.filter(title=‘Django is
my Pony’) Article.objects.filter(title__contains=‘Python’) Article.objects.filter(title__startswith=‘Django’) Article.objects.filter(pub_date__gte=‘2014-02-23’) • Model relationship lookups syntax: field__foreignfield__lookuptype=value Article.objects.filter(category__slug__contains=‘pony’) -
Summary • URLConf - routes URL patterns to views •
View - handles requests from URLConf • Dunder Methods - used for filtering queries -
Topics 1. Setup How to start a project 2. Models
How to define your data 3. URLs and Views How to access your data 4. Templates How to render your data ✓ ✓ ✓ -
Templates • Renders HTML and other formats like XML, CSV
and JSON • Uses custom pseudo programming syntax • Call function or do logic: {% ... %} • Print variable: {{ variable }} • Filters: {{ variable|filter }} -
Django Flow Client URL View Model Tpl 1 Client requests
a page via a URL 1 2 Django checks URLConf for URL patterns and executes view function to handle request 2 3 View requests data from model 3 4 Model queries the database and returns data to the view 4 5 View passes the data to template 5 6 Template renders data and returns HTML to the view 6 7 View returns HTML to the browser 7 -
Template Tags • {% load %} - loads custom template
tag • {% extends %} - inherits from parent or base template • {% block %} - defines a placeholder that can be overridden by child templates • includes vs extends: • extends is the “inside-out” version of server-side includes • includes: define sections that are common • extends: define sections that are unique -
Includes: define sections that are common Header Footer Extends: define
sections that are unique Content Header Footer Content -
Template Philosophies • Discourage redundancy. • Be decoupled from HTML.
• XML should not be used as a template language. -
Summary • Templates - render HTML and other formats •
load - loads template tags from other libraries • extends - inherits from base template • block - defines placeholder in templates -
Topics 1. Setup How to start a project 2. Models
How to define your data 3. URLs and Views How to access your data 4. Templates How to render your data ✓ ✓ ✓ ✓ -
Recap • What is Django? • What is MTV? •
What is Loose Coupling? • What is KISS? • What is RAD? • What is DRY? -
Recap • What is the advantage of using VirtualEnv? •
After installing a new package, what is the best thing to do next? • What is an app? • How do you convert a folder into a Python package? • After activating new apps in settings, what is the best thing to do next? -
Recap • What is the Admin site? • What do
you do if you want your models to appear in the Admin site? • What is the use of dunder methods in queries? • How does template inheritance work?