Conference Notes and Best Practices Release 1.3 ... - Read the Docs
Conference Notes and Best Practices Release 1.3 ... - Read the Docs
Conference Notes and Best Practices Release 1.3 ... - Read the Docs
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong><br />
<strong>Release</strong> <strong>1.3</strong><br />
Derek Stegelman<br />
January 04, 2014
Contents<br />
1 Meetups 3<br />
1.1 Django Deployment with Salt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3<br />
1.2 Django Class Based Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4<br />
<strong>1.3</strong> Custom User Model/Django Auth Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6<br />
2 <strong>Notes</strong> 9<br />
2.1 Django Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9<br />
2.2 Django Snippets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9<br />
2.3 Django Class Based Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10<br />
2.4 Python Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11<br />
2.5 Selenium Testing with Django . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11<br />
3 <strong>Conference</strong>s 13<br />
3.1 Django Con US 2013 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13<br />
3.2 PyCon 2012 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49<br />
3.3 Django Con US 2012 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90<br />
i
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Below is my collection of notes on general Django/Python development as well as conference <strong>and</strong> meet up notes.<br />
Contents 1
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
2 Contents
CHAPTER 1<br />
Meetups<br />
1.1 Django Deployment with Salt<br />
Presenter: Nick Lang<br />
Description:<br />
Django deployment with Salt<br />
1.1.1 Background<br />
• Developer at Lab 305<br />
• Worked at Journal World<br />
1.1.2 What is Salt<br />
• Config management in Python similar to Chef/Puppet<br />
• Remote code execution<br />
• Awesome!<br />
• salt.read<strong>the</strong>docs.org<br />
• Good install docs<br />
Master & Minion<br />
• Master server<br />
• Minions ping masters for updates or can be pushed to by Master<br />
• Has states<br />
• Masters can also be minions<br />
• Minion can be db server, app server, mail server, etc.<br />
3
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Master Configuration<br />
• Specify backends<br />
• Point it at a Git Repo! FTW.<br />
• Quick updates<br />
Minion Config<br />
• Just connect to master<br />
• Salt key to connect<br />
1.<strong>1.3</strong> Quick Dive into Config<br />
Salt State<br />
• Packages to install <strong>and</strong> versions<br />
• Files<br />
• Symlinks<br />
• Databases<br />
• Web Servers<br />
• Fine grain control<br />
• Create users/groups<br />
Remote Code Execution<br />
• Deploy scripts<br />
1.1.4 Vagrant Integration<br />
• Salty vagrant<br />
• Use salt to configure Vagrant<br />
• Pre-seed salt master with <strong>the</strong> key of your vagrant vm<br />
• Demo<br />
1.2 Django Class Based Views<br />
Presenter: Nick Lang<br />
Description:<br />
Class Based Views<br />
4 Chapter 1. Meetups
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
1.2.1 Background<br />
• Developer at Lab 305<br />
• Worked at Journal World<br />
1.2.2 Overview<br />
• Class version of generic function views.<br />
• Base, Dates, Detail, Edit, List<br />
• CRUD Views<br />
• Subclassed (Mixins)<br />
1.2.3 Mixins<br />
Object with methods that can be overridden to customize behavior.<br />
• ContentMixin<br />
• TemplateResponseMixin (Adds context variables)<br />
• Date Views, Many.<br />
1.2.4 Detail Views<br />
• Single object<br />
• Primary key or slug<br />
1.2.5 Mixins<br />
• SingleObjectMixin<br />
• SingleObjectTemplateResponsemixin<br />
1.2.6 Crud Views<br />
• Create/<strong>Read</strong>/Update/Delete<br />
• Form View/CreateView/UpdateView/DeleteView<br />
Mixins<br />
• FormMixin<br />
• MomdelFormMixin<br />
1.2.7 List view<br />
• Mixins - MultipleObjectMixin<br />
1.2. Django Class Based Views 5
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
1.2.8 Base View<br />
• ContentMixin <strong>and</strong> TemplateView<br />
• Nav item names<br />
1.2.9 Why<br />
• Custom mixins<br />
• Elegance<br />
• can push constants to <strong>the</strong> template by declaring class properties<br />
• Lots of possibilities for mixins.<br />
• Django Braces<br />
<strong>1.3</strong> Custom User Model/Django Auth Tools<br />
Presenter: Aaron Merriam, Rocky Meza<br />
Description:<br />
Django Auth Tools<br />
FusionBox<br />
<strong>1.3</strong>.1 Custom User Models<br />
• Supported in Django 1.5<br />
• MOst apps don’t use a username (use Email instead)<br />
• Not <strong>the</strong> correct pattern<br />
• More control<br />
• Adding custom methods <strong>and</strong> properties<br />
<strong>1.3</strong>.2 Adding A Custom User Model<br />
• Must implement methods <strong>and</strong> custom manager<br />
• Custom user admin won’t work<br />
• Lots of custom code needs to be written<br />
• Lots of boilerplate<br />
• Custom login logic<br />
• Custom password reset logic<br />
6 Chapter 1. Meetups
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
<strong>1.3</strong>.3 Django Auth Tools<br />
Custom user app<br />
• Add to installed apps.<br />
• Already implemented <strong>the</strong> required methods<br />
• AbstractBaseClass<br />
• Class based views so methods can be drop in replaced.<br />
• Password reset confirm <strong>and</strong> login in one view.<br />
• Generic forms<br />
• Generic model admin classes.<br />
• Email as username, but o<strong>the</strong>rs..<br />
Migrating<br />
• Take over <strong>the</strong> table. Migrations still needed.<br />
• Django’s email field on user does not enforce a unique constraint<br />
• 3rd party applications aren’t all ready.<br />
Storing Additional Information for a User<br />
• Don’t store user information in <strong>the</strong> new user model.<br />
• Mixes profile code with authorization <strong>and</strong> au<strong>the</strong>ntication.<br />
User Profiles<br />
• Just make a relationship between <strong>the</strong> profile <strong>and</strong> <strong>the</strong> user object.<br />
• Profiles for users in each app/project.<br />
• Idea is to package user profile info into an app so it can be re-used.<br />
Dos Don’ts<br />
• use get_user_model instead of django.contrib.auth.models.user<br />
• Don’t point <strong>the</strong>m directly at <strong>the</strong> user model<br />
• models.ForeignKey(settings.AUTH_USER_MODEL)<br />
<strong>1.3</strong>. Custom User Model/Django Auth Tools 7
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
8 Chapter 1. Meetups
CHAPTER 2<br />
<strong>Notes</strong><br />
2.1 Django Resources<br />
2.1.1 Common Libraries<br />
• south<br />
• sorl-thumbnail<br />
• tastypie<br />
• fabric<br />
• boto<br />
• MySQL extensions<br />
• django-taggit<br />
• factory_boy<br />
• django-crispy-forms<br />
2.1.2 Talks/Learning<br />
• http://www.youtube.com/watch?v=A-S0tqpPga4<br />
• http://djangoproject.com<br />
2.2 Django Snippets<br />
2.2.1 Pagination<br />
Inside <strong>the</strong> views:<br />
Templates:<br />
9
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
{% if is_paginated %}<br />
<br />
<br />
{% if page_obj.has_previous %}<br />
Prev<br />
{{ page_obj.previous_page_number }}
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
urlpatterns = patterns(’’,<br />
)<br />
url(r’^posts/$’, PostListView.as_view(), name="post_list_view"),<br />
url(r’^posts/(?P[-\w]+)/$’, PostDetailView.as_view(), name="post_detail"),<br />
2.3.3 Mixins<br />
Mixins can easily be added to class based views to extend <strong>and</strong> inherit common functionality:<br />
from django.utils.decorators import method_decorator<br />
from django.contrib.auth.decorators import login_required<br />
from django.core.urlresolvers import reverse_lazy<br />
from kstate.common.auth.decorators import group_required<br />
STAFF_LOGIN = reverse_lazy("login")<br />
class StaffRequiredMixin(object):<br />
"""<br />
View mixin for <strong>the</strong> staff application.<br />
Requires someone to be a staff member.<br />
"""<br />
@method_decorator(login_required(login_url=STAFF_LOGIN))<br />
@method_decorator(group_required("Staff"))<br />
def dispatch(self, *args, **kwargs):<br />
return super(StaffRequiredMixin, self).dispatch(*args, **kwargs)<br />
class AdminRequiredMixin(object):<br />
"""<br />
View mixin for staff app. Required admin group.<br />
"""<br />
@method_decorator(login_required(login_url=STAFF_LOGIN))<br />
@method_decorator(group_required("Admin"))<br />
def dispatch(self, *args, **kwargs):<br />
return super(AdminRequiredMixin, self).dispatch(*args, **kwargs)<br />
2.4 Python Resources<br />
2.4.1 Libraries<br />
2.4.2 Learning<br />
2.5 Selenium Testing with Django<br />
2.5.1 Quick Start<br />
Install python selenium:<br />
2.4. Python Resources 11
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
pip install selenium<br />
Create a new Test case:<br />
from django.test import LiveServerTestCase<br />
from selenium import webdriver<br />
from selenium.webdriver.support.ui import Select<br />
import time<br />
class SomethingAppTest(LiveServerTestCase):<br />
fixtures = [’groups.json’]<br />
def setUp(self):<br />
self.browser = webdriver.Firefox()<br />
# Use factories to create objects<br />
def tearDown(self):<br />
self.browser.quit()<br />
def test_something(self):<br />
self.browser.get(self.live_server_url)<br />
self.browser.find_element_by_id(’clickme’).click()<br />
2.5.2 Testing Tid Bits<br />
• It’s a good idea to prime your test cases with data. Ei<strong>the</strong>r prime <strong>the</strong> test case with a fixture or better yet, an<br />
object factory.<br />
12 Chapter 2. <strong>Notes</strong>
CHAPTER 3<br />
<strong>Conference</strong>s<br />
3.1 Django Con US 2013<br />
Location: Hyatt Regency Chicago, IL<br />
When: September 3rd–6th<br />
URL: http://www.djangocon.us<br />
Schedule: http://www.djangocon.us/schedule/<br />
Description:<br />
DjangoCon US is <strong>the</strong> main opportunity for djangonauts to come toge<strong>the</strong>r in <strong>the</strong> United States. It will<br />
consist of two tracks of talks over three days, <strong>and</strong> will also provide for open sessions, lightning talks, <strong>and</strong><br />
a development sprint after <strong>the</strong> conference.<br />
3.1.1 Tuesday<br />
Keynote<br />
Presenter: Russell Keith-MaGee<br />
Track: N/A<br />
Description:<br />
State of <strong>the</strong> Pony<br />
Malcolm Tredinnick Memorial Award<br />
• Monetary award.<br />
• DSF asking for donations<br />
• Email foundation@djangoproject.com<br />
13
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
State of <strong>the</strong> Pony<br />
DSF Mission<br />
• Support Development<br />
• Promote Django<br />
• Protect IP<br />
• Advance state of <strong>the</strong> art<br />
Support Development<br />
• Sponsored Events<br />
• <strong>Conference</strong>s (DjangoCon AU, Kiwi PYcon, PyCon YU, RuPy, PyArkansas)<br />
• Sprints (Stockholm, LA, Toulouse), DjangoCon US.<br />
• Grants (Getting started with Django, Travel Grants, Startup Capital)<br />
• Grants committee<br />
• Show corporate members (lots)<br />
Promote Use of Django<br />
• djangoproject.com -> not finished<br />
• Platform to show Django success<br />
• Code of Conduct now required for sponsorship<br />
• Community code of conduct for Django (djangoproject.com/conduct/)<br />
Protect IP <strong>and</strong> Long Term Viability<br />
• Copyrights (BSD)<br />
• Need to sign contributor license agreement to contribute to Django<br />
• Trademarks<br />
• Trademark licensing agreement (Describes how <strong>and</strong> when you can use it in a community.)<br />
** Merch<strong>and</strong>ise ** Groups Events ** Domain Names * Djangoproject.com/trademarks/ * Exemptions<br />
Advance <strong>the</strong> State of <strong>the</strong> Art<br />
• Django 1.5 (Initial python 3 transition)<br />
• Django 1.6 in beta<br />
• Persistent DB Connections<br />
• Transaction improvements<br />
• Django 1.7 (Schema migration, 2013 Google summer of Code, validate refactor, composite foreign keys)<br />
14 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Technical Challenges<br />
• “Real Time” web<br />
• Nothing in <strong>the</strong> box that will help you achieve this.<br />
• Rich client interfaces<br />
• Attract new users<br />
• Positive first experiences<br />
• Limit wasted effort<br />
• Improve development tools <strong>and</strong> processes<br />
• Funding open source<br />
• Hire a “django fellow” to work full time on Django. Manage <strong>the</strong> community. Funded by <strong>the</strong> DSF.<br />
https://speakerdeck.com/freakboy3742/djangocon-2013-state-of-<strong>the</strong>-pony<br />
Django Docker<br />
Presenter: Ken Cochrane<br />
Track: I<br />
Description:<br />
Docker is a new tool that makes it easy to bundle <strong>and</strong> deploy your applications to any host running Docker.<br />
In this talk I’ll show you how to get started with Docker, <strong>and</strong> how to use it to deploy your Django apps to<br />
your different server environments.<br />
Django Docker<br />
Who<br />
• Corporate Sponsor of Docker (Dot cloud)<br />
Survey<br />
• 80% heard of docker<br />
Where did Docker Come From<br />
• Docker is a rewrite of similar code that powers DotCloud<br />
• Original version in Python, new version in GO<br />
• Very Young project<br />
Timeline<br />
• Jan 2013 internal project<br />
• March PyCon talk<br />
• <strong>Release</strong>d March 27<br />
• June add OpenStack comptatibility<br />
3.1. Django Con US 2013 15
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
• 5300 Github stars<br />
• 125 Contributers<br />
What Is Docker<br />
• Docker is an OSS engine that automates deployment of containers<br />
• Linux containers<br />
• Control groups <strong>and</strong> Namespaces<br />
• AUFS (file system)<br />
Linux Containers<br />
• Mini VMs<br />
• Stacked on top of ano<strong>the</strong>r LInux system<br />
• Like a vm but very light weight<br />
Why Containers<br />
• boot in seconds<br />
• 1000s of containers on single machine<br />
• Containers all use same host OS<br />
• Share bin/libs<br />
• No guest OS.<br />
• Layered approach for file system<br />
• Build on top (diffs)<br />
Install Docker<br />
• Linux kernel 3.8 or above<br />
• AUFS<br />
• LXC<br />
• 64 Bit<br />
• (Ubuntu 13.04)<br />
• Vagrant<br />
• Docker APT repo<br />
Vagrant<br />
• Clone <strong>and</strong> vagrant up<br />
16 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Binary Install<br />
• Manage upgrades yourself<br />
• Need to install system startup script.<br />
• 5 easy steps for Digital ocean<br />
Digital Ocean Install<br />
• Docker install in one step for Digital Ocean (Official docker image)<br />
• 10$ free credit DJANGOCON2013 tinyurl.com/docker10<br />
Use Cases<br />
• Local Dev environment<br />
• Deployment<br />
• Unit Testing<br />
• Parallelize tests<br />
• one DB per test<br />
Unit Testing<br />
• Containers to isolate tests<br />
• No more worrying about tests not cleaning up<br />
• Parallelize <strong>the</strong> tests across multiple machines<br />
System Tests<br />
• Easily create all <strong>the</strong> diff system configs to test against<br />
• No need to worry about breaking or rebuilding a test server<br />
• Test fabric scripts<br />
• Agileq.com/blog/<br />
Continuous Integration<br />
• run tests after each commit<br />
• StriderCD.com open source CI server<br />
• Travis CI also playing with Docker<br />
Deployment<br />
• Dokku<br />
• flynn.io<br />
• deis.io<br />
• chef, puppet, salt, ansible, etc.<br />
3.1. Django Con US 2013 17
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Dokku<br />
• Open source<br />
• Docker powered mini-heroku<br />
• less than 100 lines of bash<br />
• Heroku build packs<br />
• git push deployment<br />
Flynn.io<br />
• Open source PASS written in Go<br />
Deis.io<br />
• Python<br />
• Git push<br />
• Docker images, chef recipes<br />
• Scaling<br />
O<strong>the</strong>r Projects<br />
• Chef-docker<br />
• chef-cookbook<br />
• Salt stack<br />
• Ansible<br />
Local Dev<br />
• VMS heavy, containers not so much<br />
• RUn 100s of containers on laptop<br />
• Easy to duplicate prod environment if you have a complex setup<br />
Projects using Docker<br />
• Node.js module testing<br />
• Plone/jiffylab - web based enviroment for instruction<br />
• Kitchen-docker - Run unit tests in isolated environment<br />
• npmt.abru.pt - Auto testing all NPM modules, one container per module <strong>and</strong> destroyed when finished.<br />
• memcached SAAS - Memcached SASS built on Docker<br />
• Try out Rethink DB, containers killed in 24 hrs. 1000s of containers on one host<br />
• Open-stack-docker, deploy to linux containers instead of VMs<br />
18 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Use Docker<br />
• Container: linux container<br />
• Image: snapshot<br />
• index: public docker image directory<br />
• Dockerfile: auotmated script used to create an image<br />
• push/pull : comm<strong>and</strong>s to get images <strong>and</strong> push <strong>the</strong>m<br />
• Run: start a docker image to run<br />
• Docker run (start image with comm<strong>and</strong>s)<br />
DockerFile<br />
• Simple scripting language<br />
• Automate creation of images<br />
• built in cache<br />
• Add <strong>the</strong>m to any project repo to dockerize <strong>the</strong> project<br />
• Online tut - docker.io/learn/dockerfile<br />
Docker Index<br />
• Similar to Pypi but for docker images<br />
• Written in Django<br />
• Public directory to store <strong>and</strong> download re-useable images<br />
• Docker image meta data<br />
• Account required to publish images<br />
• index.docker.io<br />
Docker Registry<br />
• Open source python flask app<br />
• Manages <strong>the</strong> storages of <strong>the</strong> images<br />
• Install private registry for private images<br />
Docker API<br />
• rest API<br />
• Docker CLI uses <strong>the</strong> same API<br />
• Clients for most languages<br />
• Docker clients (docker-py)<br />
• Docker UI (Shipyard) Docker UI (angular.js) Dockl<strong>and</strong> Ruby<br />
Demo (https://github.com/kencochrane/django-docker)<br />
3.1. Django Con US 2013 19
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Scaling Your Write-Heavy Django App<br />
Presenter: Tobias McNulty<br />
Track: II<br />
Description:<br />
<strong>Notes</strong>:<br />
Content management systems <strong>and</strong> o<strong>the</strong>r read-heavy Django apps are relatively easy to scale. Scaling<br />
write-heavy apps is ano<strong>the</strong>r matter. In this talk I’ll walk through our experience scaling <strong>the</strong> University of<br />
Chicago’s custom school survey application to h<strong>and</strong>le over 75,000 requests per minute <strong>and</strong> upwards of<br />
9,500 PostgreSQL transactions per second.<br />
1. Project Overview<br />
(a) 5Essential survey module for UChicago<br />
(b) Not about making app fast but scalable, i.e. multiple users at once<br />
2. Scaling Phase 1: Chicago Public Schools<br />
(a) Main issue is bottle-neck entering data to DB<br />
(b) Need an easy way to generate load ... JMeter<br />
(c) Record yourself testing a complex process<br />
(d) HTTP Cookie Manager built into JMeter<br />
(e) pgfouine –> log postgres performance<br />
(f) django-cache-machine for specific caching<br />
(g) Choose what you cache via ‘cached =’ property on a model<br />
(h) use read database to avoid load on write DB<br />
(i) Streaming replication hit PG in 9.1 – try django-balancer<br />
3. Scaling Phase 2: The State of Illinois<br />
(a) gevent worker terrible for CPU-bound applications<br />
(b) NewRelic makes I/O looks expensive, but each worker is processing too many reqs at once<br />
(c) Use a sync worker in gevent <strong>and</strong> it will open up <strong>the</strong> CPU bottleneck<br />
(d) Database was <strong>the</strong> bottleneck, still overloaded<br />
(e) Increased size of EC2 instance, still slow<br />
(f) Figuring out max_connections: not web server count ... Machine resources<br />
(g) Use pgbouncer to share a small number of presistent connections<br />
(h) Run pgbouncer on your web servers using supervisord<br />
(i) Don’t need max_conn to be so low, but know what you’re changing when you change that<br />
4. Slides: http://cakt.us/djangocon-scaling<br />
20 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Performance Optimization<br />
Presenter: Joseph Jasinski<br />
Track: II<br />
Description:<br />
Your site is slow. But why is your site slow? There are a myriad of different problems that can cause<br />
this slowness. Drawn from real world experiences, this talk will help identify different problem areas <strong>and</strong><br />
techniques for increasing performance. This involves both evaluating your performance on <strong>the</strong> backend<br />
<strong>and</strong> underst<strong>and</strong> bottlenecks on <strong>the</strong> frontend.<br />
Performance Optimization<br />
Front End<br />
• Large <strong>and</strong> unoptimized payloads<br />
• Static medai/images<br />
• slow load of CSS<br />
• Slow third party resources loading<br />
• Blocking IO<br />
• Chrome Tools<br />
• External Analyizers (Google pagespeed insights)<br />
• Browser Plugin<br />
• Pingdom speed tools (DNS checker)<br />
• Yslow browser plugin<br />
Backend<br />
• SQL Quantities<br />
• Blocking code<br />
• Django Debug Toolbar<br />
• Extending Django Debug toolbar (Cache panel & template timings)<br />
• See what blocks take <strong>the</strong> longest<br />
• Profiling middleware<br />
• Get information on calls.<br />
Improve Front End<br />
• Remove comments/whitespace<br />
• HTML Minification<br />
• Django=htmlmin<br />
• Combine <strong>and</strong> compress css/js<br />
• django compressor<br />
3.1. Django Con US 2013 21
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
• Compress images/Cache<br />
• Image sprites/logos/icons<br />
Resource Order<br />
• Load first styles in critical path<br />
• Place JS after o<strong>the</strong>r resources, ideally at <strong>the</strong> end of <strong>the</strong> file.<br />
• Inline some CSS at <strong>the</strong> top.<br />
• Lazy loading (Load images/assets only if <strong>the</strong> user gets <strong>the</strong>re)<br />
Assets CDNS<br />
• Geographically serve assets<br />
• Improve load time<br />
Improve Backend<br />
• SQL Queries<br />
• Use “values_list”<br />
• Verify same queries aren’t running multiple times<br />
• Select_related <strong>and</strong> prefetch_related<br />
Select Related <strong>and</strong> Prefetch Related<br />
• Get foreign keys<br />
• If getting foreign keys use select_related<br />
• Prefetch related can work for many to many queries<br />
Cache<br />
• How should I cache?<br />
• Memcache<br />
• Use low level cache?<br />
Low Level<br />
• Flexibility<br />
• Reduce lookups<br />
• get() set() delete() methods<br />
• Flexibilty to develop your own cache scheme<br />
• Template fragment cache<br />
• Can accept context variables<br />
• example (Get cache template for different users)<br />
22 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Per Site Cache<br />
• Great for heavy read sites<br />
• Not really approprate for immediate change sites<br />
• Difficult to delete cache backend<br />
• Google analytics can have issues<br />
Cache Frameworks<br />
• Johnny Cache<br />
• Cache Machine<br />
• ORM Model cacheing<br />
CDNs<br />
• Browsers support 6 connections per hostname<br />
• More maximum connections<br />
• Hashring with CDN domains<br />
• Each domain is a seperate DNS lookup.<br />
• Limit what you need to do inside of a request.<br />
• Defer<br />
Job Queue<br />
• Process queues off line<br />
• Requires more configuration<br />
Server Level<br />
• Set expires header<br />
• Cache control headers<br />
• Gzip responses<br />
More Requests Less Money<br />
Presenter: Nick Catalano<br />
Track: I<br />
Description:<br />
Hear how in under 2 weeks Ain’t it Cool News, a movie news <strong>and</strong> review website with over 15 years of<br />
raw HTML content <strong>and</strong> hundreds of thous<strong>and</strong>s of daily visits, was moved from an expensive custom Ruby<br />
on Rails App on an EC2 cluster to a dedicated server running Django. All with zero downtime.<br />
3.1. Django Con US 2013 23
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
More Requests Less Money<br />
History<br />
• Old, Old, HTML<br />
• Perl, Drupal, Rails<br />
Problem<br />
• Ads were gradually going down.<br />
• AWS bills were growing<br />
• Active scaling horizontally<br />
• Had to pay licensing fees for using software<br />
Realizations<br />
• Can’t offer commenting as well as Disqus<br />
• OK if articles dont’ appear right way for entire world as long as it eventually shows up<br />
• A little down time is manageable<br />
Solution<br />
• Managed dedicated server behind Amazon cloudfront<br />
• Use disqus<br />
Arch<br />
• Old arch, multiple high=cpu medium instances, extra large RDS instance<br />
• Over 3000/month<br />
New Arch<br />
• Dedicated server, 16gb RAM, mysql, SSD, Apache Modwsgi<br />
• Cloud instances for forums <strong>and</strong> domains redirects<br />
• Disqus<br />
• Additional cloud instances<br />
• Managed operations services<br />
• 1325/month<br />
Migrating Content<br />
• 60000 raw html articles<br />
• 4.5 million non spam comments<br />
• SQL dump <strong>and</strong> public facing templates only way to get content<br />
24 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Inspect DB<br />
• Based on SQL dump<br />
• set production DB as secondary DB<br />
• Rebuilt <strong>the</strong> site using view source files <strong>and</strong> simple django views<br />
Migration<br />
• Left talkbacks alone<br />
• Built a management comm<strong>and</strong> to migrate articles from secondary database first<br />
• Get or create runs without duplicate data on both machines<br />
• Management comm<strong>and</strong> also stripped out html to generate meta tags<br />
• Find <strong>and</strong> replace for image URLs <strong>and</strong> h<strong>and</strong>ling weird unicode in DB<br />
• Simple cleanup with beautiful soup<br />
Cloud Front<br />
• HTTP POST is not supported<br />
• Do pay for requests<br />
• Bring your own analytics<br />
• No full site purge<br />
• Do not assume every cloudfront request will have a cloudfront user agent.<br />
• Cloudfront will not continue to serve your site indefinitely if your origin goes down.<br />
Scaling Up<br />
• Scaled from 10,000 visits/hour to 90,000 visits/hour. No downtime<br />
http://bit.ly/aicndjangocon<br />
Getting Started with Salt<br />
Presenter: Peter Baumgartner<br />
Track: II<br />
Description:<br />
Salt is <strong>the</strong> new kid on <strong>the</strong> block in <strong>the</strong> configuration management space. Unlike <strong>the</strong> Ruby=based Chef <strong>and</strong><br />
Puppet, Salt is written in Python, making it easy to debug <strong>and</strong> extend for Django developers. This talk<br />
will introduce Salt as well as explore some of <strong>the</strong> things that make it unique.<br />
Getting Started with Salt<br />
What is Salt<br />
• Configuration Management<br />
• Remote execution<br />
3.1. Django Con US 2013 25
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Configuration Management<br />
• Similar to Chef/Puppet<br />
• Ansible<br />
• Configuration through code<br />
• Version control your servers<br />
• Self documenting<br />
• Repeatbale<br />
• Reuseable<br />
Remote Execution<br />
• Run comm<strong>and</strong>s against remote servers<br />
• Similar to Fabric<br />
• Deploying<br />
• Run one=off scripts<br />
• Package updates<br />
• System monitoring/alerting<br />
Familiar Tool<br />
• Python<br />
• YAML<br />
• Jinja2<br />
Community<br />
• Great docs<br />
• Responsive to IRC <strong>and</strong> Github<br />
• Backed by for=profit org<br />
Why Not<br />
• Young project<br />
• Moves Fast<br />
• Not SSH (ssh support soon)<br />
Terminology<br />
• Chef, knife, cookbook<br />
• Ansible, playbook, inventory<br />
• Salt = Master<br />
26 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Salt Terminology<br />
• Master = Server that manages <strong>the</strong> whole stack<br />
• Minion = A server controlled by master<br />
• State = A declaritive Representation of <strong>the</strong> system state<br />
• Grain = Static information about a minion (RAM, CPU cores, OS, etc)<br />
• Pillar = Variables for one or more minions<br />
• Top File = Matches states or pillars to minions<br />
• High state = All <strong>the</strong> state data for a minion<br />
Install<br />
• pip install for bleeding edge<br />
• bootstrap.saltstack.org<br />
• apt=get install salt=master<br />
• apt=get install salt=minion<br />
• Accept minion key on <strong>the</strong> master<br />
Install a package<br />
In /srv/salt/mystate.sls<br />
ngingx:<br />
pkg.installed<br />
High State<br />
• Push from master<br />
• Pull from minion<br />
• Masterless<br />
States<br />
• 50 Built in states<br />
• Build your own<br />
• pip, virtualenv, mysql, postgres, files, cron<br />
Using Pillars<br />
• Code examples<br />
• Can use templating language to configure pillar.<br />
3.1. Django Con US 2013 27
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Advanced<br />
• Salt cloud<br />
• Custom modules<br />
• Scheduler<br />
• Renderers<br />
• Returners<br />
Tips <strong>and</strong> Tricks<br />
output_mode: mixed<br />
• Show me full traceback if error, only respond verbose with errors<br />
• Jinja2 is powerful, don’t go nuts.<br />
• Update often <strong>and</strong> review <strong>the</strong> change log<br />
• Test before you deploy<br />
https://speakerdeck.com/ipmb/getting=started=with=salt<br />
Finding The Needle: Search <strong>and</strong> Django<br />
Presenter: Ben Lopatin/Wellfire Interactive<br />
Track: II<br />
Description:<br />
Most websites share at least two things in common: content <strong>and</strong> users who want to find content. This<br />
talk will cover <strong>the</strong> basics of site search using search engines (<strong>the</strong> kind you run, not Google), setting up<br />
a Django project with Haystack, highlight some of <strong>the</strong> gotchas you might encounter, <strong>and</strong> touch on some<br />
more advanced functionality.<br />
Finding The Needle<br />
Overview<br />
• Underst<strong>and</strong> Search<br />
• role of search engine<br />
• Nifty search features<br />
• Adding search with Haystack<br />
• Implementation Strategies<br />
• Limitations <strong>and</strong> Options<br />
Search Problem<br />
• Trying to search text content<br />
• Distinction between searching for <strong>and</strong> looking for.<br />
• Trying to find information<br />
28 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Search Engines<br />
• Stop words (remove common words)<br />
• Indexing tokens<br />
• Document data store based on filtered tokens.<br />
• ElasticSearch/Solr/Whoosh/Xapian/Sphinx<br />
• What about SQL full=text indexing? = Can do it, won’t get as many features as a search engine.<br />
Data in/Data out<br />
• Analyzers = Tokenizer + Filters<br />
• Tokenizers<br />
– Whitespace/N=grams/word delimters<br />
• Filters<br />
– ASCII/Stemming/Lowercase/stop words/synonyms<br />
• Language specific filters.<br />
• Querying (Data Out)<br />
• Match tokens against tokens<br />
• Faceting = Characteristics of a set.<br />
• Spell checking<br />
• Geospatial search<br />
• Autocomplete<br />
Django/Haystack<br />
• Haystack is a pythonic abstraction<br />
• ORM Oriented<br />
• SearchQuerySet<br />
• SearchForm<br />
• Search View<br />
Index Strategies<br />
• One Time<br />
• Real Time<br />
• Real time=ish (queued)<br />
• Periodic<br />
3.1. Django Con US 2013 29
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Building Search<br />
• Model attribute<br />
• Templates<br />
• Field method (Method that refers to a field)<br />
• Queryset to define a search index (Specify what gets added to <strong>the</strong> index)<br />
Help Users<br />
• Improve quality of search<br />
• Adjust relevance<br />
• Boot fields, documents, terms<br />
• Log searches, results, <strong>and</strong> <strong>the</strong>ir success<br />
• Use search engine as cache<br />
Doing More with Search<br />
• ElasticSearch can configure index analysis.<br />
• Can configure tokenizers <strong>and</strong> filters<br />
• Write a custom backend/New Default analyzer/Update search mapping<br />
Some Gotchas<br />
• Don’t index fields used for sorting<br />
• Debug search issues (Is this plugged in, is anything indexed?)<br />
• Haystack debug pannel for django debug toolbar<br />
SearchIndex = data mapping<br />
Writing Fast <strong>and</strong> Efficient Unit Tests For Django<br />
Presenter: Casey Kinsey<br />
Track: I<br />
Description:<br />
Many developers have difficulty finding clear guidelines <strong>and</strong> best practices for how to test efficiently,<br />
leading to a flimsy, slow, <strong>and</strong> ineffective test suite. This talk will cover some basic (but oft overlooked)<br />
principles of unit <strong>and</strong> integration testing, <strong>and</strong> dive into more advanced topics such as testing with read<br />
only data <strong>and</strong> using Mock ultra-focused <strong>and</strong> fast testing.<br />
Writing Faster Tests<br />
A real need for test speed<br />
• Made an initial production release of a real product for a national media company<br />
• Test Coverage not great<br />
30 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
• Started seeing regressions<br />
• Aggressively pursue greater test coverage<br />
• Results were successful, but needed faster tests.<br />
Should I be concerned?<br />
• You probably have lots of tests<br />
• You probably run <strong>the</strong>m frequently<br />
• Slow tests will cause developers to stop running <strong>the</strong>m<br />
• Preparing code for integration becomes painful<br />
• Deployment speed is directly affected<br />
How to write better tests<br />
• Many project suites are comprised of integration tests<br />
• Write unit tests<br />
• Unit test calls a small “unit” of code<br />
• Integration tests, test <strong>the</strong> contracts between <strong>the</strong> units<br />
• Using <strong>the</strong> django test client is a giveaway that its an integration test.<br />
• Write unit tests that are very limited in functionality/scope<br />
Unit Vs Integration<br />
• For each function that contains business logic, <strong>the</strong>re should be a unit test<br />
• for each page/view/user path of your project <strong>the</strong>re should exist an integration test.<br />
• Setup tests<br />
Set up tests cautiously<br />
• Be judicious about how you use setUp/tearDown<br />
• Think like middleware. Do I really need this for every test in this case?<br />
• One inefficient computation can cripple <strong>the</strong> whole test case.<br />
• Add @classmethod. very effective for read only data. Data will persist between tests!<br />
The Database is Hot Lava<br />
• If you touch it, you will die<br />
• Not really, but its one of <strong>the</strong> slowest things your application will do in a unit test.<br />
• Work with read only, non persisted data.<br />
• Use in memory model instances<br />
model = ModelName(attribute=x)<br />
• Avoid fixtures<br />
3.1. Django Con US 2013 31
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
• Fixtures don’t adapt<br />
• Schema changes will result in failures<br />
Fake it Till You Make It With Mock<br />
• Library that lets you create stub objects<br />
• Configure behavior for testing<br />
• Use mock to emulate model instances<br />
• No model/ORM overhead<br />
• Use mock.patch to focus your tests<br />
• Patch sys.modules with your own module<br />
• Use mock in more complex situations<br />
• Track <strong>the</strong> way objects are used - test assertions, know which attributes that have been called <strong>and</strong> can report on<br />
it.<br />
It’s OK to engineer when testing<br />
• Don’t be afraid to invest engineering effort into <strong>the</strong> test suite.<br />
• Your tests are Python code, take advantage of it.<br />
• Write tools to help you<br />
• Mock, Django Nose<br />
• Custom test runners<br />
• If you can’t test <strong>the</strong> code efficiently, refactor <strong>the</strong> code.<br />
3.1.2 Wednesday<br />
Agile Not Vulnerable<br />
Presenter: Jacob Kaplan-Moss<br />
Track: I<br />
Description:<br />
Startups like to “move fast <strong>and</strong> break things”. . . but how do you ensure that what breaks isn’t security?<br />
How do you strike a balance <strong>and</strong> make sure you’re able to ship quickly while still ensuring that what goes<br />
out <strong>the</strong> door doesn’t have vulnerabilities? The answer begins by recognizing that security is a process, not<br />
a feature, <strong>and</strong> this has ramifications throughout <strong>the</strong> organization. It means that security engineering needs<br />
to be everyone’s responsibility (instead of a select few), <strong>and</strong> it means that when security vulnerabilities<br />
crop up — <strong>and</strong> <strong>the</strong>y will — <strong>the</strong> organization needs to be prepared <strong>and</strong> aligned to act quickly.<br />
Security<br />
Shipping Often With Security/Agile<br />
• Ability to ship is incredibly valuable but also dangerous.<br />
32 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Overview<br />
• Security is a process not a product.<br />
• Security is a part of everything you do, every day.<br />
• Similar to testing, documentation, daily activity.<br />
• Heroku has two man security team.<br />
• Security is everyone’s responsibility.<br />
• Every developer should have some underst<strong>and</strong>ing of what can go wrong<br />
The OWASP Top 10 (Paste in later)<br />
Example<br />
• Building a REST API<br />
• Should you support all major (common) formats?<br />
• Does this decision have security ramifications?<br />
Ex 2:<br />
• You need to store data. One format is common, one is less common, harder to read <strong>and</strong> write <strong>and</strong> isn’t used as<br />
often<br />
• Which do you choose?<br />
• Does this decision have security ramifications?<br />
A security vulnerability has been created.<br />
2013 Ruby/Rails YAML Vulnerabilities<br />
• Real world security issues are multifaceted.<br />
• This can happen to anyone. Django/Python is not exempt.<br />
More on Security<br />
• Secure by default matters. Defaults matter!!<br />
• YAML “load” <strong>and</strong> “load_safe”<br />
• You can’t really prove that software is secure. You can only prove that it’s insecure.<br />
• Unknown Unknowns<br />
• If an issue of this magnitude was discovered in your stack would you be prepared to respond?<br />
• Need to define terminology to refer to severity of security issues<br />
A good security policy<br />
• Lays out st<strong>and</strong>ard terminology used when talking about security issues<br />
• Explains <strong>the</strong> expectations <strong>and</strong> commitments around vulnerability h<strong>and</strong>ling.<br />
• Creates a transparent repeatable assessment mechanism.<br />
3.1. Django Con US 2013 33
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Terminology<br />
• Advisory<br />
• Low<br />
• Medium<br />
• High<br />
• Critical<br />
Advisory<br />
• Issues that <strong>the</strong> security team wishes to communicate but carry no specific required action.<br />
• May contain recommended actions, but no specific response is required.<br />
Low<br />
• Issues that are expected to be resolved, but have low risk, or low consequences. Should not interrupt<br />
day to day operations.<br />
Medium<br />
• Carry some risk, but have low impact. May have someone work on.<br />
High<br />
• Carry substantial risk, publicly disclosed issues. Will probably interrupt several developers from multiple teams.<br />
Critical<br />
• Threaten <strong>the</strong> integrity of <strong>the</strong> company. Great financial risk or o<strong>the</strong>rwise “sky is falling” level issues.<br />
• “All h<strong>and</strong>s on deck”<br />
Assessment<br />
• Start with OWASP for risk rating<br />
• Risk = Likelihood x Impact<br />
• How likely is that this issue will be discovered <strong>and</strong> exploited?<br />
Examples of Vulnerabilities<br />
• http://bit.ly/13ds9X0 (PostgreSQL)<br />
• Likelyhood: threat agent<br />
• Calculate Threat<br />
• Calculate your impact<br />
• Matrix of likelyhood <strong>and</strong> impact<br />
• This case came out to High level.<br />
34 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Transactions for Web Developers<br />
Presenter: Aymeric Augustin<br />
Track: I<br />
Description:<br />
Django has since long outgrown its roots in publishing. It’s used in enterprise systems, under write-heavy<br />
workloads <strong>and</strong> strong data integrity requirements. But transaction management barely changed since <strong>the</strong><br />
0.9x days. Even veterans pull <strong>the</strong>ir hair out fighting DatabaseErrors when <strong>the</strong>y use it. At last transaction<br />
h<strong>and</strong>ling will be overhauled in Django 1.6. How does <strong>the</strong> new system work, <strong>and</strong> why?<br />
Transaction Management<br />
• SQL-92 st<strong>and</strong>ard<br />
• A transaction is a sequence of SqL statements that is atomic with respect to recovery.<br />
• All or nothing.<br />
• Lifecycle (Transaction initiating statement -> commit, explicit rollback)<br />
SQL-1999<br />
• Save points (Like sub-transactions)<br />
• Statements always run in a transactions<br />
• Transactions are opened automatically<br />
• Transactions are advanced technology.<br />
Dreaded Error<br />
• Current Transaction is aborted, comm<strong>and</strong>s ignored until end of transaction block<br />
• Means - A previous statement failed, <strong>the</strong> application must perform a rollback<br />
• Recovery must be done in <strong>the</strong> application (Any auto-recovery scheme breaks transactional integrity)<br />
Auto Commit<br />
• Commit implicitly after each statement.<br />
• Wrap each statement in ints own transaction<br />
• Just execute my query!<br />
• Most databases default to auto commit.<br />
Auto Commit in PostgreSQL<br />
• Server always auto commit<br />
• Client libs can emulate st<strong>and</strong>ard behavior<br />
• in psql: set autocommit off<br />
3.1. Django Con US 2013 35
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Auto Commit in SQLite<br />
• Transaction semantics are tightly related to <strong>the</strong> implementation of atomic commit<br />
• Sqlite automatically starts a transaction before all statements except select<br />
• It automatically commits such transactions as soon as all statements finish executing<br />
• Transactions are always serializable<br />
Python client libraries<br />
• PEP 249<br />
• Connection, performs commits <strong>and</strong> rollbacks<br />
• Cursor, Executes queries, fetches results.<br />
• Auto-commit should be initially off<br />
• Interface should be provided to turn it back on<br />
• Closing a connection without committing <strong>the</strong> changes first will cause an implicit rollback to be performed.<br />
Transactions in psycopg2<br />
• Tracks transaction state<br />
• Inserts a BEGIN before each statement unless <strong>the</strong>re is already a transaction in progress<br />
• Even before select statements<br />
• Idle in transactions<br />
• cnx.autocommit = True disables this behavior.<br />
Transactions in SQLite<br />
• Track state<br />
• Parses statements to insert BEGIN or COMMIT<br />
• SELECT:COMMIT, INSERT, UPDATE, DELETE, REPLACE: Begin<br />
• Any o<strong>the</strong>r statement uses COMMIT<br />
• Broken by design<br />
Key Learnings<br />
• DB API requires <strong>the</strong> same transactional behavior as <strong>the</strong> SQL st<strong>and</strong>ard<br />
• Client libraries for Databases that always auto commit have to emulate this behavior<br />
• You can turn it off<br />
Django
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Transaction middleware<br />
• One HTTP request = one transaction. Commit on success, roll back on exception.<br />
• High level apis transaction.autocommit() transaction.commit_on_success()<br />
Behind <strong>the</strong> Scenes<br />
• Django maintains a stack of transaction management states<br />
• Auto: <strong>the</strong> ORM commits every change<br />
• Managed: Django doesn’t commit<br />
• Django maintains a “dirty” flag: set automatically by <strong>the</strong> ORM after writes, must be set manually after raw SQL<br />
queries.<br />
• Nesting doesn’t work well<br />
Default Django 1.6<br />
• Database-level auto commit<br />
• ATOMIC_REQUESTS<br />
• ATOMIC can be used as decorator or as context manager<br />
• commit on success, roll back on exceptions<br />
• Guarantees atomicity.<br />
• Low level API to implement your own transaction management<br />
Key Learnings<br />
• If you don’t underst<strong>and</strong> transactions read <strong>the</strong> docs in django 1.6<br />
• ATOMIC_REQUESTS is still a reasonable idea<br />
• Use <strong>the</strong> atomic decorator when you need aotmicity.<br />
Django Auth User<br />
Presenter: Russell Keith-MaGee<br />
Track: I<br />
Description:<br />
An exploration of one of <strong>the</strong> banner features of Django 1.5 – Custom User models. Includes worked<br />
examples, a discussion of design decisions that must be made, <strong>and</strong> a look at <strong>the</strong> internal architecture that<br />
makes it all possible.<br />
Auth User Model<br />
Why Should We Care?<br />
• Login with email address<br />
• Associating profile data with <strong>the</strong> user model<br />
3.1. Django Con US 2013 37
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
• Not clearly understood<br />
Whats in a name?<br />
• Names are different (not just first <strong>and</strong> last)<br />
• Non western names<br />
• Some last names do not have family names<br />
• Some do not have last names at all.<br />
• Django assumes that you have a distinct first <strong>and</strong> last name, is wrong.<br />
Names are Hard<br />
• Do you need separate fields<br />
• Just use a Full name?<br />
• If you need to seperate <strong>the</strong>m, use “Family name” <strong>and</strong> “O<strong>the</strong>r/given name”<br />
• Ask “How would you like to be addressed”?<br />
Tips<br />
• Don’t assume a single letter is an initial<br />
• Be wary of name-part algorigthms<br />
• Spaces, Apostrpohes, <strong>and</strong> Hypens are all level characters in names<br />
• Don’t require a “Family Name”<br />
• “previous name”, not “maiden name”<br />
• Honorifics are even more complex. Can’t just add “mr” in front of a name<br />
On <strong>the</strong> subject of “do you need to ask”?<br />
• Why do you ask for certain things? (Gender?)<br />
• Kuzdu <strong>and</strong> <strong>the</strong> California Marriage amendment<br />
When it comes to identity you need to think:<br />
• Do I need to ask at all?<br />
I. Define User Model<br />
• 2 possible base classes (Abstract base user, abstract user)<br />
• Define username field<br />
• Define required-fields<br />
• Define get_full_name <strong>and</strong> get_short_name<br />
38 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
II. Define Manager<br />
• Need to describe how to create users.<br />
• Describe how to create superusers.<br />
III. Define Forms<br />
• usercreationform<br />
• userchangeform<br />
• passwordresetform<br />
VI. Register with Admin<br />
• Only need to do this if your using <strong>the</strong> admin<br />
• subclass contrib.admin.UserAdmin<br />
V. Register <strong>the</strong> model<br />
• AUTH_USER_MODEL = ‘myapp.MyUser’<br />
IV. Update Foreign Keys<br />
• NOT ForeignKey(User)<br />
• ForeignKey(settings.AUTH_USER_MODEL)<br />
• USERNAME_FIELD must be unique <strong>and</strong> not in REQUIRED_FIELDS<br />
Signal Registration<br />
• Register signals with <strong>the</strong> actual model that is being used, not hte setting.<br />
What Isn’t in <strong>the</strong> <strong>Docs</strong><br />
• Reverse lookup naming.<br />
• The “User Contract” - You must be explicit about what a user object has.<br />
Email Based Login<br />
• Define a user model with email<br />
• Username_field = ‘email’<br />
• Define forms, admin.<br />
Don’t reinvent <strong>the</strong> wheel<br />
• Ticket: #20824<br />
• API-based login<br />
• Kerberos single sign-on<br />
• Au<strong>the</strong>ntication backends, can have multiple auth backends.<br />
3.1. Django Con US 2013 39
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
• roguelynn.com/words/<br />
Profile Data<br />
• Option 1, put everything in <strong>the</strong> user model<br />
• Option 2, keep user separate, link to it with a foreignkey<br />
• In option 2, you can provide your own profile model to hook in to <strong>the</strong> user model.<br />
• Which should you use?<br />
It Depends<br />
• Profiles are better architecture. Makes no assumptions about user model<br />
• Long term user objects.<br />
• Cost of getting a foreign key<br />
• Where do draw <strong>the</strong> line.<br />
One More Thing<br />
• How does it all work.<br />
• No references to auth.User<br />
• Meta property: Swappable = ‘auth_user_model’<br />
• Inspected at run time for <strong>the</strong> real model class<br />
• The rest is validation<br />
• No new features in ForeignKey() or M2M<br />
• Validation that ForeignKey doesn’t point at a swapped models.<br />
• You can make your own models swappable.<br />
https://speakerdeck.com/freakboy3742/red-user-blue-user-myuser-auth-dot-user<br />
Building Rich Applications with Django <strong>and</strong> Ember<br />
Presenter: Gabriel Grant<br />
Track: I<br />
Description:<br />
Ember.js is <strong>the</strong> most advanced client=side JavaScript framework available: it provides optimistic server<br />
updates, automatically=updating templates <strong>and</strong> sensible defaults to dramatically increase developer productivity.<br />
Building Rich Apps with Django <strong>and</strong> Ember<br />
Ember <strong>and</strong> Django Dot Cloud Example<br />
• used jquery to return async views<br />
• Django stack<br />
40 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
• JSON Bypassing template layer<br />
• Ember!<br />
Ember<br />
• Client side mvc framework<br />
• Data that would go to template views, now goes to Ember to h<strong>and</strong>le on <strong>the</strong> client side.<br />
Demo<br />
• Expose an API<br />
• Django Rest Framework<br />
Ember<br />
• Advanced Client side framework<br />
• MVC <strong>and</strong> App structure<br />
• St<strong>and</strong>ards library<br />
• Bindings<br />
St<strong>and</strong>ards Library<br />
• Object system<br />
• Eliminate busy work<br />
• Ember Bindings == @property + dependencies<br />
Components <strong>and</strong> Controllers<br />
• Web components<br />
• Ember components<br />
• Controllers store transient application state<br />
• Controllers can be contrlled by components<br />
Everybody Loves Migrations<br />
Presenter: Andrew Godwin<br />
Track: II<br />
Description:<br />
Times are changing - schema migrations are finding <strong>the</strong>ir way into core Django <strong>and</strong> becoming quite<br />
different in <strong>the</strong> process. Come <strong>and</strong> learn what’s happening, why it’s being done this way, <strong>and</strong> how you<br />
can best start using <strong>the</strong>m.<br />
3.1. Django Con US 2013 41
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Migrations<br />
Why is it so hard<br />
• Versioning not easy in Dbs<br />
• hard to roll back<br />
• every change has a side effect<br />
• Difference databases (Mysql, Postgres, etc.)<br />
• Not necessarily up front.<br />
South<br />
• <strong>Release</strong>d 2008<br />
• Most popular solution<br />
• Not without issues<br />
• 6 or 7 year old design<br />
Basic Layout<br />
• schemamigration (have to always add –auto)<br />
• datamigration<br />
• migrate apply only migrations<br />
• syncdb<br />
• complex <strong>and</strong> evolved design<br />
Issues<br />
• Migrations build up over time<br />
• VCS merges suck OUCH<br />
• That file format<br />
django.db.migrations<br />
• 5 years in <strong>the</strong> making.<br />
Design Goals<br />
• Clean migrations - <strong>Read</strong>able diffs are really important.<br />
• Squashable migrations - No need for those hundreds of old ones.<br />
• Better merge protection<br />
• Better comm<strong>and</strong>s –auto is pointless<br />
• Automatic dependencies - stops silent errors<br />
• Reuseable schema API - There are valid reasons to change tables<br />
42 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
• Third-party compatability<br />
Migrations<br />
• Make migrations<br />
• migrate - Applies migrations <strong>and</strong> legacy collection. Syncdb removed<br />
• Autodetector - Makes new migrations<br />
• Executor - Plans <strong>and</strong> runs migrations<br />
Better Format<br />
• Compound history<br />
• Stores history as statements in a list<br />
• Series of Operations<br />
• Nicer way of serializing fields<br />
• Fields need a deconstruct() method.<br />
Multiple AppCaches<br />
• Basically, you can make multiple versions of <strong>the</strong> same model in memory at once.<br />
Don’t Panic<br />
• Will be upgrade path to new migrations<br />
• South 2 to backport new format.<br />
• South 2 out a little after django 1.7<br />
Future Ideas<br />
• Better autodetection<br />
• Renames now work<br />
• Percona support<br />
• Nonrelational support<br />
Overview<br />
• New migration Format<br />
• Even easier to use<br />
• Django models through <strong>and</strong> through<br />
• Use a proper database<br />
• Schemas are your friend<br />
3.1. Django Con US 2013 43
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
3.<strong>1.3</strong> Thursday<br />
Guerilla APIs<br />
Presenter: Russell Keith-Magee<br />
Track: I<br />
Description:<br />
In an ideal world, every web system would provide a well designed REST API with oAuth au<strong>the</strong>ntication.<br />
But what do you do when those things don’t exist?<br />
Guerilla APIs<br />
• Big companies do not embrace API centric development<br />
• In order to get this data you have to use unconventional tactics.<br />
• Can build user facing API that works how we want to<br />
• Not productized (but could be)<br />
RSS h<strong>and</strong>ling<br />
• FeedParser<br />
• Time tasks/cron to retrieve content<br />
• Pythonic interface for RSS h<strong>and</strong>ling<br />
Email H<strong>and</strong>ling<br />
• Get pure text<br />
• HTML<br />
• Attachments<br />
• Emails may be recursive<br />
• Mimetype<br />
• DOCX<br />
• DOC<br />
PDF Processing<br />
• PDF is a printing format<br />
• Internally, vector based drawing instructions<br />
• May contain attachments<br />
• PDFMiner<br />
• Some PDFs are locked down<br />
Use Selenium to open a browser session to actually submit forms programatically.<br />
44 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Making Django Play Nice with Third Party Services<br />
Presenter: Matt Makai<br />
Track: II<br />
Description:<br />
Modern Django projects combine custom apps with third party services, such as Twilio <strong>and</strong> Stripe, to create<br />
a complete product. Choosing <strong>the</strong> right services for your application can make or break its usefulness<br />
to users as well as your sanity during maintenance. This talk will show you how to properly evaluate,<br />
integrate, <strong>and</strong> maximize what you get out of SaaS products in your Django projects.<br />
Making Django Play Nice with Third Party Services<br />
@mattmakai<br />
Why<br />
• Your app, your responsibility<br />
• Service usage is increasing<br />
• Little effort to prevent big headaches<br />
What will you learn<br />
• Discover new services<br />
Third Party Service Usage<br />
• Discover<br />
• Evaluate<br />
• Integrate<br />
• Maintain<br />
Discover<br />
• Research when not under pressure to immediately integrate<br />
• What problem can this service potentially solve.<br />
Mindset<br />
• Background <strong>and</strong> philosophy<br />
• Openness about <strong>the</strong>ir solution approach<br />
• Bookmark services <strong>and</strong> arguements for <strong>and</strong> against<br />
3.1. Django Con US 2013 45
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Push Sources<br />
• Leanstack<br />
• Python Weekly<br />
• PyCoders’s Weekly<br />
• Django Round-up<br />
• Heroku Addons<br />
• Geckoboard Widgets<br />
Evaluate<br />
• Platform ecosystem<br />
• Is <strong>the</strong>re a python resource at <strong>the</strong> ruby shop?<br />
• Developer evangelists?<br />
• Data gravity? - How much of your critical data is going into <strong>the</strong> service? Can you get your data out easily?<br />
• Stack exchange<br />
• Long term viability<br />
• Project <strong>Read</strong>me/<strong>Docs</strong><br />
Example<br />
Twillio<br />
• Tutorials in Python<br />
• Platform is on Python<br />
• Open source Django Examples<br />
• Developer evangelists active<br />
First Party Binding<br />
• Ideal<br />
• Update Frequency?<br />
• Outst<strong>and</strong>ing issues<br />
Creating Your Own Third Party Binding<br />
• Learning<br />
• python-requests<br />
46 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Tools<br />
• Pypi-notifier (Notify when new packages come out)<br />
• Full stack Python<br />
• Discovering Third Party Services for Django<br />
• mattmakai.com<br />
• Geckoboard widget directory<br />
State of <strong>the</strong> real-time web with Django<br />
Presenter: Aymeric Augustin<br />
Track: I<br />
Description:<br />
In 2013, “real-time” is more than a buzzword: it’s a reality on <strong>the</strong> Web. Unfortunately, for users of Django,<br />
it’s still a foreign world that involves new concepts <strong>and</strong> new components, <strong>and</strong> it doesn’t integrate well with<br />
traditional infrastructure. What is <strong>the</strong> real-time web? Why is it hard to support in Django? What are our<br />
options today? What can we expect in <strong>the</strong> future?<br />
State of <strong>the</strong> real-time web with Django<br />
Real Time<br />
• Systems responding within deadlines<br />
• Simulations running at wall clock time<br />
• Processing events without perceivable delay<br />
• Set of technologies <strong>and</strong> practices taht enable users to recive info as soon as its published, ra<strong>the</strong>r than refreshing.<br />
Use Cases<br />
• chat<br />
• games<br />
• VOIP<br />
• Notifications<br />
• Live Data<br />
• Social feeds<br />
• PUSH information<br />
Request - Response model doesn’t allow for this.<br />
Early Solutions<br />
• Java Applets<br />
• Pushlets - call back from java apps into DHTML<br />
• Comet - Long lived HTTP connections to reduce latency.<br />
3.1. Django Con US 2013 47
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
HTTP Long Polling<br />
• Server keeps request onhold <strong>and</strong> only send respond when an event to deliver<br />
• As soon as client gets <strong>the</strong> response it sends ano<strong>the</strong>r request<br />
HTTP Streaming<br />
• Server sends a series of events ina single HTTP response<br />
• Chunked<br />
• Client processes each incoming event.<br />
Server Sent Events<br />
• Built on top of HTTP Streaming<br />
• Format text/event-stream<br />
• Javascript API<br />
Web Socket<br />
• Provides bidirectional communication in <strong>the</strong> context of <strong>the</strong> existing HTTP infrasturcutre<br />
• RFC 6455<br />
• Binary<br />
• Socket.IO<br />
• SockJS<br />
Long Polling<br />
• Locks up a gunicorn worker<br />
Web Sockets<br />
Execution Model<br />
• Based on an event loop<br />
• H<strong>and</strong>le multiple socket connections in a single thread<br />
• More efficient than one thread per connection<br />
• Suitable for network prgoramming<br />
Programming Model<br />
• Callbacks<br />
• coroutines<br />
• Based on explicit cooperative multi-threading<br />
• In python: yeild (from)<br />
• Suitable for concurrent applications<br />
48 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Pep 3156<br />
• Pluggable event loop API<br />
• Callbacks, transports, protocols<br />
• High level scheduler based on coroutines<br />
• REference implementation code-named Tulip<br />
• Effort led by Guido<br />
Django C10k Demo<br />
https://github.com/aaugustin/django-c10k-demo<br />
Django isn’t async<br />
• @websocket<br />
HTTP != real-time<br />
• Execution - threads vs events<br />
• Programming preemptive vs cooperative<br />
• Stateless vs stateful<br />
• CPU vs I/O Bond<br />
• Request-response vs message streaming<br />
Key<br />
• Django isn’t designed for explicitly cooperative multi threading <strong>and</strong> its unlikely to change<br />
• Robust client <strong>and</strong> server stacks are emerging<br />
• Better best practices<br />
• Simplified development setups<br />
• Getting more useable.<br />
https://speakerdeck.com/nduthoit/denormalize-all-<strong>the</strong>-things https://speakerdeck.com/nduthoit/<strong>the</strong>-path-to-smoo<strong>the</strong>rdatabase-migrations<br />
3.2 PyCon 2012<br />
3.2.1 Tuts<br />
Python Epiphanies<br />
March 8 2012<br />
• Instructor - Stuart Williams<br />
3.2. PyCon 2012 49
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Introduction<br />
• Static vs Dynamically typed language.<br />
• Compiler must now ahead of time what type an object is<br />
• In python you do not have to do that, because is not a static type language<br />
• Type is checked at run time, not typed at compile time. It is a dynamic language<br />
• Compiler allocates memory.<br />
• In python creates types <strong>and</strong> assigns names to <strong>the</strong>m (not variables)<br />
• These are references to o<strong>the</strong>r objects not actual objects <strong>the</strong>mselves.<br />
• Names are implemented like ditionaries<br />
Dictionaries <strong>and</strong> Namespaces<br />
Python Objects <strong>and</strong> Vars<br />
• Things like a = 17 are essentially dictionaries. These are added to object l<strong>and</strong>.<br />
• Python object has<br />
• Single value<br />
• Single Type<br />
• Some number of attributes<br />
• Single ID<br />
• Zero or one or more names in one or more namespaces<br />
• One or more base classes<br />
• When lists are appened IDs do not change, strings do.<br />
• Can’t set attributes of built in types.<br />
• IDs match because <strong>the</strong>re only needs to be one actual object in memory<br />
Namespaces<br />
• _namespace[’s] - Directly accessble namespace<br />
• indirect, using dot notation dict.__doc__ or sys.version.major<br />
Namespace Search Order<br />
• Local names<br />
• Namespaces of encolsing function, search starting with <strong>the</strong> nearst closing scope<br />
Exercise:<br />
locals().keys()<br />
globals().keys()<br />
locals() == globals()<br />
locals() is globals()<br />
In this case locals() is globals()<br />
50 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Namespace Changes<br />
• assignment<br />
• del<br />
• (globals() <strong>and</strong> locals())<br />
• import<br />
• def<br />
• class<br />
When you make an assignment you are just assigning a second name (alias) to <strong>the</strong> original function:<br />
from pprint import pprint as pprint_function<br />
• __init__.py required for modules<br />
Functions<br />
• You can add arbitrary attributes to functions<br />
• Passing in a dictionary as an argument<br />
>>> def f(a1, a2, kw1=’k1’, kw2=’k2’):<br />
... print(repr((a1, a2, kw1, kw2)))<br />
...<br />
>>> f(1)<br />
Traceback (most recent call last):<br />
File "", line 1, in <br />
TypeError: f() takes at least 2 arguments (1 given)<br />
>>> f(1, 2)<br />
(1, 2, ’k1’, ’k2’)<br />
>>> f(1, 2, 3)<br />
(1, 2, 3, ’k2’)<br />
>>> t = 1, 2<br />
>>> t<br />
(1, 2)<br />
>>> d = dict(kw1=3, kw2=4)<br />
>>> d<br />
{’kw1’: 3, ’kw2’: 4}<br />
>>> f(*t)<br />
(1, 2, ’k1’, ’k2’)<br />
>>> f(**d)<br />
Traceback (most recent call last):<br />
File "", line 1, in <br />
TypeError: f() takes at least 2 non-keyword arguments (0 given)<br />
>>> f(1, 2, **d)<br />
(1, 2, 3, 4)<br />
Ano<strong>the</strong>r example:<br />
>>> name = ’Dad’<br />
>>> ’Hi {name}’.format(**locals())<br />
’Hi Dad’<br />
Lists are Mutable, Strings are Not<br />
• Lists can be changed. Strings create new objects.<br />
3.2. PyCon 2012 51
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Class Statement<br />
• single ID<br />
• Single value<br />
• Number of attributes<br />
• Single Type<br />
• one or more namespaces<br />
• One or more base classes<br />
ClassName()<br />
ClassName().__init__()<br />
Class Num(object):<br />
def __init__(self, amount):<br />
self.amount = amount<br />
def add(self, value):<br />
return self.amount + value<br />
• You can add a method as an attribute of a class by simply assigning it.<br />
• is comparison has been helpful<br />
Class Prefixer(object):<br />
def __init__(self, prefix):<br />
self.prefix = prefix<br />
def prepend(self, listing):<br />
for l in listing:<br />
l = l + self.prefix<br />
• Need to brush up on some basic python iterators, loops, etc.<br />
• Metaclasses<br />
Iterators<br />
• A for loop evaluates <strong>and</strong> expressiosn to get an iterable <strong>and</strong> <strong>the</strong>n calls iter() to get an iterator.<br />
• The iterators next() method is called until StopITeration is raised.<br />
• Iterable items get <strong>the</strong> iter() method called.<br />
m = [1, 2, 3]<br />
it = iter(m)<br />
it.next()<br />
it.next()<br />
it.next()<br />
Generators<br />
def list123():<br />
yield 1<br />
yield 2<br />
yield 3<br />
52 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
it = list123()<br />
it.next()<br />
it.next()<br />
it.next()<br />
• Look at next (David Beazley talk on Generators)<br />
import operator<br />
ops = {<br />
’+’: operator.add,<br />
’-’: operator.sub,<br />
}<br />
ops[op] (lhs, rhs)<br />
def calc(expr):<br />
lhs, op, rhs = expr<br />
lhs, rhs = int(lhs), int(rhs)<br />
return ops[op] (lhs, rhs)<br />
3.2.2 Friday<br />
Stop Writing Classes<br />
Classes are overused<br />
• Obfuscated function calls<br />
• Classes with an __init__ <strong>and</strong> one o<strong>the</strong>r method.<br />
• SHouldn’t instantiate use <strong>the</strong>m once, <strong>and</strong> <strong>the</strong>n throw <strong>the</strong>m away.<br />
• Namespaces are <strong>the</strong>re to help <strong>and</strong> prevent naming collisions.<br />
• Containers are great use case for classes.<br />
Exceptions<br />
• Don’t make new exceptions, you don’t need to.<br />
Advanced Security Topics<br />
Presenter: Paul McMillan - Django Security Developer<br />
Track: II<br />
Description:<br />
If your Python application has users, you should be worried about security. This talk will cover advanced<br />
material, highlighting common mistakes. Topics will include hashing <strong>and</strong> salts, timing attacks, serialization,<br />
<strong>and</strong> much more. Expect eye opening demos, <strong>and</strong> an urge to go fix your code right away.<br />
https://us.pycon.org/2012/schedule/presentation/467/<br />
3.2. PyCon 2012 53
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Hasing <strong>and</strong> Encryption<br />
• MD5, SHA1, SHA256<br />
• If you are typing md5 you are doing it wrong<br />
• Did this file get corrupted?<br />
• Use has for Message signing.<br />
• It is hard to generate a file that duplicates your stored hash.<br />
• Use HMAC for message signing.<br />
hash(secret + hash)<br />
• Salt your secret key<br />
salt = ’session_cookie_signing’<br />
hmac.new(salt + secret_key, msg)<br />
• When using has algorithims do not use MD5.<br />
• SHA1 is better, but use SHA256<br />
• Web could use SHA512 as its not 32 bit.<br />
Why Need Encryption<br />
• Do not implement yourself.<br />
• Use SSL/TLS<br />
R<strong>and</strong>om Numbers<br />
• Default r<strong>and</strong>om number is predictable.<br />
• Use SystemR<strong>and</strong>om() instead<br />
from r<strong>and</strong>om import SystemR<strong>and</strong>om()<br />
Timing attacks<br />
• String comparison does not compare <strong>the</strong> entire string at once.<br />
• Not safe<br />
• Compare <strong>the</strong> length first<br />
• Compare different sets of characters, even if <strong>the</strong> previous ones worked.<br />
Pickle<br />
• Do not put data straight into pickle.<br />
• Use JSON for untrusted data<br />
54 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Always verify your assumptions<br />
• PIP installing.<br />
• I trust django developers<br />
• I truse <strong>the</strong> people who wrote pip<br />
• PIP verifies MD5 hash<br />
Am I Safe?<br />
• All <strong>the</strong>se things require you to trust everyone on <strong>the</strong> internet<br />
• You must verify<br />
• Python doesn’t make it easy to check SSL certs.<br />
• Consider using Crate.io<br />
Interfaces <strong>and</strong> Python<br />
Presenter: Eric Snow<br />
Track: IV<br />
Description:<br />
In 2.6, Python introduced <strong>the</strong> Abstract Base Classes. Before that we had “protocols” (<strong>and</strong> we still do).<br />
In this talk we’ll look at how <strong>the</strong> general concept of interfaces fits into today’s Python. We’ll also look<br />
at some of <strong>the</strong> alternate proposals of <strong>the</strong> past, some of <strong>the</strong> controversies around ABCs, <strong>and</strong> <strong>the</strong> direction<br />
interfaces might go in <strong>the</strong> future.<br />
https://us.pycon.org/2012/schedule/presentation/126/<br />
http://goo.gl/hwkTy<br />
Object Interfaces<br />
• Code as documentation<br />
• Adaption<br />
• Static analysis<br />
What is it<br />
• Communication<br />
• Documentation<br />
• Doc strings<br />
• Comments<br />
• Progromatic Interfaces<br />
3.2. PyCon 2012 55
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
What is it in Python<br />
• Abstract base classes<br />
• Protocols<br />
• Build your own<br />
Protocols<br />
• iterator<br />
• context manager<br />
• sequence<br />
• descriptor<br />
• No Validation is done to make sure <strong>the</strong>y are following <strong>the</strong> protocol<br />
EAFP vs LBYL<br />
It’s easier to ask forgiveness than permission<br />
Call it <strong>and</strong> worry about <strong>the</strong> failing later.<br />
# EAFP<br />
def is_dead(obj):<br />
try:<br />
obj("only a flesh wound")<br />
except TypeError:<br />
raise MyError("expected a callable object")<br />
Look before you leap<br />
Check a variable/method for something before you call it.<br />
# LBYL<br />
def is_dead(obj):<br />
if not hasattr(obj, "__call__"):<br />
raise MyError("expected a callable object")<br />
obj("only a flesh wound")<br />
Duck-typing<br />
polymorphism by capability vs polymorphism by type<br />
Requiring a specific interface instead of a specific type.<br />
Abstract Base Classes<br />
Write Your Own<br />
class Entree(metaclass=ABCMeta):<br />
@abstractmethod<br />
def with_spam(self):<br />
"""spam spam spam spam"""<br />
@abstractproperty<br />
def spamcontent(self):<br />
"""Lovely spam! Wonderful spam!"""<br />
• Decorators make your methods Abstract.<br />
56 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
• If a class has abstract methods <strong>the</strong>n that class will be abstract.<br />
• ABCMeta marks class as abstract<br />
Use Existing<br />
• Register an existing class as an implementation<br />
>>> class MyDict(Mapping): pass<br />
...<br />
>>> issubclass(MyDict, Mapping)<br />
True<br />
>>> isinstance(MyDict(), Mapping)<br />
True<br />
>>> MyDict.__bases__<br />
(,)<br />
Decorators <strong>and</strong> Context Managers<br />
Presenter: Dave Brondsema<br />
Track: IV<br />
Description:<br />
Learn how decorators <strong>and</strong> context managers work, see several popular examples, <strong>and</strong> get a brief intro to<br />
writing your own. Decorators wrap your functions to easily add more functionality. Context managers<br />
use <strong>the</strong> ‘with’ statement to make indented blocks magical. Both are very powerful parts of <strong>the</strong> python<br />
language; come learn how to use <strong>the</strong>m in your code.<br />
https://us.pycon.org/2012/schedule/presentation/131/<br />
Decorators<br />
• Pass functions to o<strong>the</strong>r functions<br />
• Example<br />
@property<br />
Instead of<br />
var = property(method)<br />
def expose(func):<br />
func.exposed = True<br />
return func<br />
• Do this:<br />
@expose("template.html")<br />
def expose(template):<br />
def mark_exposed(func):<br />
return func<br />
return mark_exposed<br />
3.2. PyCon 2012 57
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
• Decorators replace <strong>the</strong> original function in memory.<br />
• Decorator for decorators<br />
• Allows you to not nest methods<br />
• Classes can be decorators<br />
• Decorators can be placed on classes<br />
• @classmethod decorator -<br />
• Restrict.post or something<br />
pip install decorator<br />
Context Managers<br />
• __enter__ <strong>and</strong> __exit__ methods<br />
• @contextlib.contextmanager<br />
• contextlib<br />
http://speakerdeck.com/u/brondsem<br />
Certainty in an Uncertain World: Gaining Confidence through Security Testing<br />
Presenter: Geremy Condra<br />
Track: I<br />
Description:<br />
Nobody thinks you have to be a performance expert to write performance tests- why assume that you have<br />
to be a security expert to write security tests? During this presentation I’ll show you how to use fuzzers,<br />
attack tools, <strong>and</strong> o<strong>the</strong>r simple techniques to help protect your users, improve <strong>the</strong> strength of your existing<br />
tests, <strong>and</strong> gain confidence in <strong>the</strong> security of your code. There will be demos!<br />
https://us.pycon.org/2012/schedule/presentation/48/<br />
Introduction<br />
• User behavior<br />
• Normal tests + adversary = security tests<br />
Common Attacks<br />
• Common Weakness Enumeration cwe.mitre.org/top25<br />
• Protect against <strong>the</strong>se<br />
• OS Comm<strong>and</strong> Injection<br />
• Cross Site Scripting<br />
• Path Traversal<br />
58 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
OS Comm<strong>and</strong> Injection<br />
from comm<strong>and</strong>s import getoutput<br />
def list_directory(attacker_input):<br />
return getoutput("ls -la " + attacker_input)<br />
• Avoid shell<br />
• Sanitize<br />
• FuzzDB http://code.google.com/p/FuzzDB<br />
Cross Site Scripting<br />
• Inputing script straight into a page.<br />
• Can’t put client data straight into an html page<br />
• Removing tags does not work.<br />
• Sanitizing library, Bleach<br />
• Problems with CMS’s, blogs, etc.<br />
• Django has built in escaping.<br />
Directory Traversal<br />
A directory traversal (or path traversal) consists in exploiting insufficient security validation / sanitization of usersupplied<br />
input file names, so that characters representing “traverse to parent directory” are passed through to <strong>the</strong> file<br />
APIs.<br />
The goal of this attack is to order an application to access a computer file that is not intended to be accessible.<br />
Fixing<br />
• Find attack tool<br />
• Testing<br />
• Integrate<br />
• Fix<br />
• Repeat<br />
What Doesn’t Work<br />
• Finding really app specific bugs<br />
• Large search spaces slow it down<br />
• Hard to define problems<br />
• Heavily analytic problems.<br />
3.2. PyCon 2012 59
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Wrap Up<br />
• Security testing isn’t hard<br />
• Can be very effective<br />
• You don’t have to be an expert<br />
Practicing Continuous Deployment<br />
Presenter: David Cramer of Disqus. Wrote Sentry.<br />
Track: I<br />
Description:<br />
Practice iterative development like <strong>the</strong> pros. <strong>Release</strong> sooner, faster, <strong>and</strong> more often.<br />
https://us.pycon.org/2012/schedule/presentation/12/<br />
Workflow<br />
• Continuous integration server runs test suites<br />
• Fast rollback (Why not rollforward <strong>and</strong> fix)<br />
Good<br />
• Develop features incrementally<br />
• <strong>Release</strong> frequently<br />
• Smaller doses of QA<br />
• Because manual tests are awful<br />
Bad<br />
• Culture shock<br />
• Statbility depends on test coverage<br />
• Time investment<br />
Keep Development Simple<br />
• Automated testing is required.<br />
• Simple can be better than complete<br />
• Puppet, Chef, Buildout, Fabric<br />
• Packaging your App as tag 1.0?<br />
CI Server<br />
• Can be stripped down, don’t need to test apache, nginx<br />
60 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Bootsrapping Local<br />
• Git clone it<br />
• Simple comm<strong>and</strong> to make everything work<br />
• Next step would be python manage.py runserver<br />
• Need to test dependencies? - Virtualbox + vagrant<br />
Progressive Rollout<br />
• Actively release to smaller group before public<br />
• Feature flipping (Gargoyle)<br />
• Bump up features<br />
• Early adopters are free QA<br />
• Sign up to get new stuff<br />
Review All Commmits<br />
• Phabricator from facebook<br />
Integration<br />
• Jenkins<br />
• Painless setup<br />
• Suppoer proper reporting - Coverage.py<br />
Bad<br />
• False positives<br />
• Bad tests<br />
• Services fail<br />
• Feedback delay<br />
• Integration tests vs Unit Tests<br />
http://jenkins-ci.org/<br />
Fixing False Positives<br />
• Rerun tets several times on a failure<br />
• Report continually failing tests to dev<br />
3.2. PyCon 2012 61
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Maintain Coverage<br />
• Commit tests with code<br />
• Utilize code review<br />
• Coverage against a single diff.<br />
Speed up Tests<br />
• Write true unit tests<br />
• Mock external services<br />
• Distruted <strong>and</strong> parallel testing<br />
Reporting<br />
• Rate of traffic (not just hits)<br />
• Response time (database, web)<br />
• Exceptions<br />
• Social Media/Twitter<br />
Sentry!<br />
Getting Started<br />
• Package your app<br />
• Value code review<br />
• Ease deployment/fast rollbacks<br />
• Setup automated Tests<br />
• Ga<strong>the</strong>r some easy metrics<br />
• Automate deploys<br />
• Continueous deployment doesn’t mean deploy all <strong>the</strong> time, it means deploy any time.<br />
• Consider <strong>the</strong> ramifications of schema changes. DO NOT DROP columns<br />
3.2.3 Saturday<br />
Django Templating: More Than Just Blocks<br />
Presenter: Christine Cheung<br />
Track: V<br />
Description:<br />
Django’s template language is designed to strike a balance between power <strong>and</strong> ease of use; learn how to<br />
use this balance to create awesome looking websites. This talk will cover <strong>the</strong> basics <strong>and</strong> best practices<br />
of Django templating, from custom tag <strong>and</strong> filter creation, to <strong>the</strong> finer points of template rendering <strong>and</strong><br />
loading, <strong>and</strong> even to replacing <strong>the</strong> default templating engine itself.<br />
62 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
https://us.pycon.org/2012/schedule/presentation/80/<br />
http://www.xtine.net @plaidxtine<br />
Intro<br />
• Front End Developer<br />
• PyLadies!<br />
• Introduction to Templating<br />
• Effective use of Built In Tags<br />
• Extending Templates<br />
• Template Loading<br />
• Extending Current Django Templating<br />
Basics<br />
• This is <strong>the</strong> end user experience<br />
• Balance between power <strong>and</strong> ease<br />
• By Design it is seperated so that backend/front end can be developed seperately<br />
• Start with a base template, <strong>and</strong> have pages inherit from it.<br />
Tools<br />
• Syntax highlighting, autocompletion<br />
• django-debug-toolbar<br />
• Print out tag/filter reference guide.<br />
Structure<br />
• Root template folder, argues against seperate apps/templats<br />
St<strong>and</strong>ards<br />
• Consistent Spacing<br />
• Put all loads at <strong>the</strong> top<br />
• Use {% comment %} instead of <br />
Common Blocks<br />
• Title<br />
• Meta tags<br />
• Extra_head<br />
3.2. PyCon 2012 63
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
• Content<br />
• Extra_JS<br />
Block <strong>Best</strong> <strong>Practices</strong><br />
• End {% block title %} with {% endblock title %}<br />
• Blocks cannot be repeated<br />
• DOn’t over block, only write one if you need one.<br />
• Use include {% include “snippet.html” %}<br />
• Do not over use includes<br />
Variables<br />
• Modify objects with filters {{ var|filter }}<br />
• loop through <strong>the</strong>m useing tags<br />
Security<br />
• Make sure you sanitize data if you are using {% autoescape %}<br />
General <strong>Best</strong> <strong>Practices</strong><br />
• Name URLs<br />
• Do not hard code static<br />
• Django-floppyforms (html5)<br />
• django-crispy-forms - More semantic forms<br />
• {% include form.html %}<br />
• Use {{ form.as_ul }}<br />
• Firstof tag, removing un-necssary if statements<br />
• Custom tags live in application module<br />
• Write simple, basic filters<br />
Example Custom Tag<br />
from django import template<br />
register = template.Library()<br />
@register.filter(name="remove")<br />
def cut(value, argument):<br />
return value.replace(argument, ’’)<br />
64 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
O<strong>the</strong>r Types of Tags<br />
@register.simple_tag<br />
@register.tag(name="current_time")<br />
• django-templatag-sugar<br />
• django-classy-tags - Class based template tags<br />
Do Not<br />
• Application logic<br />
• Dangerous, Difficult to support<br />
• Do not replicate python logic in <strong>the</strong> templates<br />
Loading <strong>and</strong> Changing Templates/Loaders<br />
• Template Loaders<br />
Replacing <strong>the</strong> Template Engine<br />
• Jinga2, Mako, Cheetah<br />
• Django is a bit slower<br />
• Different logic control <strong>and</strong> h<strong>and</strong>ling<br />
• Lots of risk switching becuase you are separting django from its template engine.<br />
Jinja<br />
• Functions callable from templates<br />
• Loop controls<br />
• Multiple filter arguments<br />
• Performace Increase<br />
• More dependencies<br />
• Lose built-in support<br />
• Too much logic in your templates<br />
• Speed increase is minimal<br />
Speeding Up Templates<br />
• Cache -Django-template-preprocessor<br />
• django-pancake - Flatten template files<br />
• Remember o<strong>the</strong>r bottlenecks (Cache, load balancing)<br />
3.2. PyCon 2012 65
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
New in 1.4<br />
• Custom project <strong>and</strong> App templates<br />
• Startapp/start project<br />
• Combine with your favorite boilerplate<br />
• {% elif %}<br />
Django Form Processing Deep Dive<br />
Presenter: Nathan Yergler<br />
Track: V<br />
Description:<br />
Django Form processing often takes a back seat to flashier, more visible parts of <strong>the</strong> framework. But<br />
Django forms, fully leveraged, can help developers be more productive <strong>and</strong> write more cohesive code.<br />
This talk will dive deep into <strong>the</strong> stock Django forms package, as well as discuss a strategy for abstracting<br />
validation for forms, <strong>and</strong> <strong>the</strong> use of unit <strong>and</strong> integration tests with forms.<br />
https://us.pycon.org/2012/schedule/presentation/420/<br />
http://yergler.net/2012/pycon-forms<br />
Basics<br />
Forms in Context<br />
business logic<br />
VIews - Convert request to response forms = Conert input to python objects models - Data <strong>and</strong><br />
Forms<br />
• Forms are composed of fields, which have a widget<br />
• Ubound forms dont have data associated with <strong>the</strong>m but can be rendered<br />
form= ContactForm()<br />
• bound forms have specifid data assoicated which can be validated, can be any dict of data<br />
form = ContactForm(request.POST)<br />
Two ways to access fields<br />
form.fields[’name’]<br />
#Field Object<br />
form[’name’]<br />
# outputs html widget<br />
Forms can be given initial data<br />
66 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Validation<br />
• Only bound forms can be valided<br />
• Fields are validated, <strong>the</strong>n <strong>the</strong> form itself<br />
• Validation, <strong>the</strong>n cleaning<br />
• Validation Error<br />
Field Cleaning<br />
• To PYthon, Validation, Cleaning<br />
• .clean_fieldname() method is called after validators<br />
• already converted to python<br />
• methods must return a clean value<br />
def clean_email(self):<br />
if (self.cleaned)data.get(’email’, ’’).endswith(’hotmail.com’))::<br />
raise ValidationError()<br />
return self.cleaned_data.get(’email’, ’’)<br />
• Using get is safer if not a required field.<br />
Form Validation<br />
• .clean<br />
• Called even if errors raised by fields<br />
• Must return <strong>the</strong> cleaned data dictionary<br />
• Initial data != default data<br />
• Defaults for non-required fields should be specified when accessing <strong>the</strong> dict.<br />
Changes<br />
• form.has_changed()<br />
• form.changed_fields<br />
Testing<br />
• Remember whats forms are for<br />
• Testing intial states, field validation, final state of cleaned data<br />
class FormTests(TestCase):<br />
def test_validation(self):<br />
form_data = {<br />
’name’: ’x" * 300,<br />
}<br />
form = ContactForm(data=form_data)<br />
self.assertFalse(form.is_valid())<br />
3.2. PyCon 2012 67
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
• Rebar, open source. Couldn’t find <strong>the</strong> link.<br />
from rebar import flatten_to_dict<br />
form_data = flatten_to_dict(ContactForm())<br />
form_data.update({<br />
’name’: ’x’ * 300,<br />
})<br />
Rendering Forms<br />
• Class based views with forms is excellent<br />
Form Output<br />
• as_p()<br />
• as_ul()<br />
• as_table()<br />
• field.label<br />
• field.label_tag<br />
• field.html_id<br />
• field.help_text<br />
• field.errors<br />
• required_css_class<br />
• error_css_class<br />
name = forms.CharField(error_messages={’required’: ’something’})<br />
Error Class<br />
• Error list is used as <br />
• Specify <strong>the</strong> error_class kwarg<br />
from django.forms.util import ErrorList<br />
form = ContactForm(data, error_class=ErrorListClass)<br />
• Avoid name collisions with prefix<br />
contact_form = ContactForm(prefix="contact")<br />
O<strong>the</strong>r <strong>Notes</strong><br />
• Model forms have an additional method, _post_clean()<br />
• FormSets to put many of <strong>the</strong> same form on <strong>the</strong> same page<br />
• Same validation structure<br />
• http://yergler.net/2012/pycon-forms<br />
68 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Testing <strong>and</strong> Django<br />
Presenter: Carl Meyer<br />
Track: V<br />
Description:<br />
A deep dive into writing tests with Django, covering Django’s custom test-suite-runner <strong>and</strong> <strong>the</strong> testing<br />
utilities in Django, what all <strong>the</strong>y actually do, how you should <strong>and</strong> shouldn’t use <strong>the</strong>m (<strong>and</strong> some you<br />
shouldn’t use at all!). Also, guidelines for writing good tests (with or without Django), <strong>and</strong> my least<br />
favorite things about testing in Django (<strong>and</strong> how I’d like to fix <strong>the</strong>m).<br />
https://us.pycon.org/2012/schedule/presentation/412/<br />
github.com/carljm/django-testing-slides<br />
• Tests are slow<br />
• Not necessary to run some third party tests<br />
• Django test discovery is broken<br />
• unittest2 discovery<br />
• Test_RUNNER setting (code example)<br />
"""<br />
An alternative Django ‘‘TEST_RUNNER‘‘ which uses unittest2 test discovery from<br />
a base path specified in settings, ra<strong>the</strong>r than requiring all tests to be in<br />
‘‘tests‘‘ module of an app.<br />
"""<br />
from django.conf import settings<br />
from django.test import TestCase<br />
from django.test.simple import DjangoTestSuiteRunner, reorder_suite<br />
from django.utils.importlib import import_module<br />
from django.utils.unittest.loader import defaultTestLoader<br />
class DiscoveryDjangoTestSuiteRunner(DjangoTestSuiteRunner):<br />
"""A test suite runner that uses unittest2 test discovery."""<br />
def build_suite(self, test_labels, extra_tests=None, **kwargs):<br />
suite = None<br />
discovery_root = settings.TEST_DISCOVERY_ROOT<br />
if test_labels:<br />
suite = defaultTestLoader.loadTestsFromNames(test_labels)<br />
# if single named module has no tests, do discovery within it<br />
if not suite.countTestCases() <strong>and</strong> len(test_labels) == 1:<br />
suite = None<br />
discovery_root = import_module(test_labels[0]).__path__[0]<br />
if suite is None:<br />
suite = defaultTestLoader.discover(<br />
discovery_root,<br />
top_level_dir=settings.BASE_PATH,<br />
)<br />
if extra_tests:<br />
for test in extra_tests:<br />
3.2. PyCon 2012 69
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
suite.addTest(test)<br />
return reorder_suite(suite, (TestCase,))<br />
• unit test<br />
• system/integration/functional tests<br />
Unit Tests<br />
• Test one single piece of code<br />
• Should be fast<br />
Integeration Tests<br />
• Integration is slow, less usefull failures<br />
• Database makes your tests slow<br />
• Write tests that don’t hit <strong>the</strong> database<br />
Don’t hit <strong>the</strong> DB<br />
• Slow<br />
• self.save()<br />
def frobnicate_thing(thing):<br />
# ... do something complicated<br />
return thing<br />
class Thing(models.Model):<br />
def frobnicate(self):<br />
"""Frobnicate <strong>and</strong> save <strong>the</strong> thing."""<br />
frobnicate_thing(self)<br />
self.save()<br />
No to Fixtures<br />
• Hard to maintain<br />
• Increase test interdependence<br />
• Slow<br />
Model Factories<br />
def create_profile(**kwargs):<br />
defaults = {<br />
"likes_cheese": True,<br />
"age": 32,<br />
"address": "3815 Brookside Dr",<br />
}<br />
defaults.update(kwargs)<br />
70 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
if "user" not in defaults:<br />
defaults["user"] = create_user()<br />
return Profile.objects.create(<br />
**defaults)<br />
• Using<br />
def test_can_vote(self):<br />
"""A user age 18+ can vote in <strong>the</strong> US."""<br />
profile = create_profile(age=18)<br />
self.assertTrue(profile.can_vote)<br />
Factory Boy<br />
class ProfileFactory(factory.Factory):<br />
FACTORY_FOR = Profile<br />
likes_cheese = True<br />
age = 32<br />
address = "3815 Brookside Dr"<br />
user = factory.SubFactory(UserFactory)<br />
profile = ProfileFactory.create(<br />
age=18, user__username="carljm")<br />
Why Use Factories<br />
• Test data local to test code (explicit).<br />
• Easy to maintain.<br />
• Don’t create any data you don’t need for that test.<br />
• Works great even for large/complex test data sets (helper functions).<br />
• Mock Library<br />
from django.utils.unittest import TestCase<br />
import mock<br />
cursor_wrapper = mock.Mock()<br />
cursor_wrapper.side_effect = \<br />
RuntimeError("No touching <strong>the</strong> database!")<br />
@mock.patch(<br />
"django.db.backends.util.CursorWrapper",<br />
cursor_wrapper)<br />
class NoDBTestCase(TestCase):<br />
"""Will blow up if you database."""<br />
Views<br />
• Write less view code<br />
• Use RequestFactory()<br />
3.2. PyCon 2012 71
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
• Call <strong>the</strong> view callable directly<br />
Web Test<br />
url = "/case/edit/{0}".format(case.pk)<br />
form = self.app.get(url).forms["case-form"]<br />
form["steps-1-step"] = "Click link."<br />
form["steps-1-expected"] = "Account active."<br />
response = form.submit()<br />
• Markup matters<br />
• If it can break, it should be tested<br />
self.assertEqual(<br />
response.json, ["one", "two", "three"])<br />
self.assertEqual(<br />
resp.html.find("a", title="Login").href,<br />
"/login/"<br />
)<br />
Selenium<br />
• pip install selenium<br />
• Django 1.4<br />
from django.test import LiveServerTestCase<br />
from selenium.webdriver.firefox.webdriver import WebDriver<br />
class MySeleniumTests(LiveServerTestCase):<br />
@classmethod<br />
def setUpClass(cls):<br />
cls.selenium = WebDriver()<br />
super(MySeleniumTests, cls).setUpClass()<br />
@classmethod<br />
def tearDownClass(cls):<br />
super(MySeleniumTests, cls).tearDownClass()<br />
cls.selenium.quit()<br />
def test_login(self):<br />
self.selenium.get(<br />
"%s%s" % (self.live_server_url, "/login/"))<br />
username_input = self.selenium.find_element_by_name(<br />
"username")<br />
username_input.send_keys("myuser")<br />
password_input = self.selenium.find_element_by_name(<br />
"password")<br />
password_input.send_keys("secret")<br />
self.selenium.find_element_by_xpath(<br />
’//input[@value="Log in"]’).click()<br />
O<strong>the</strong>r<br />
72 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
• Write system tests for your viwes<br />
• Write selenium tests for ajax o<strong>the</strong>r js<br />
• Write unit tests for everything else.<br />
• Avoid multiple step tests<br />
@override_settings(ALLOW_COMMENTS=True)<br />
def test_comments_allowed(self):<br />
# ...<br />
Web Server Bottlenecks And Performance Tuning<br />
Presenter: Graham Dumpleton<br />
Track: V<br />
Description:<br />
New Python web developers seem to love running benchmarks on WSGI servers. Reality is that <strong>the</strong>y<br />
often have no idea what <strong>the</strong>y are doing or what to look at. This talk will look at a range of factors which<br />
can influence <strong>the</strong> performance of your Python web application. This includes <strong>the</strong> impact of using threads<br />
vs processes, number of processors, memory available, <strong>the</strong> GIL <strong>and</strong> slow HTTP clients.<br />
https://us.pycon.org/2012/schedule/presentation/275/<br />
Big Picture<br />
• Many moving parts in <strong>the</strong> whole system<br />
• Main User grief is on teh front end. (Static, Network isues)<br />
• 80% - 90% of <strong>the</strong> end user reponse time is spent on <strong>the</strong> front end. Start There.<br />
• Database/Application Server<br />
Are Benchmarks Stupid<br />
• Little value<br />
• People reference <strong>the</strong>m, <strong>and</strong> <strong>the</strong>y are often wrong<br />
• Test only a single narrow use case.<br />
• Hitting a site with extram load will only show you whtat i till likely fail under a denial of service attack.<br />
• Should test corner cases, typical use cases<br />
Environment<br />
• Memory<br />
• Processors<br />
• Threads<br />
• Golbal Interpreter Lock<br />
3.2. PyCon 2012 73
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Client Impacts<br />
• Slow HTTP Browsers/clients<br />
• Need to h<strong>and</strong>le static assets ( Don’t use same server )<br />
Use Cases<br />
• Memory USage<br />
• Threads<br />
• Long Running Requests<br />
• HTTP Clients<br />
Memory Usage<br />
• Web server base memory usage<br />
• Web server per thrad memory usage<br />
• Application base memory usage<br />
• Loaded before forking?<br />
• Adding more processes increases memory quicker.<br />
• Issue is mainly about configuration<br />
• Change <strong>and</strong> evaluate what your config is, don’t just use <strong>the</strong> defaults.<br />
• Number of overall threads, dictated by overall concurrent users.<br />
Threads<br />
• More processes, more memory<br />
• Find a balance<br />
• If CPU is slow, more processes<br />
• IO Wait<br />
Long Running Request<br />
• Uploads<br />
• Slow HTTP<br />
• Large Response<br />
Slow HTTP Clients<br />
• Proxy NGINX with Gunicorn<br />
• Offload static<br />
• Put Nginx in front of apache workers -> mod_wsgi dameons<br />
74 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Restarts<br />
• Restarts to fix issues<br />
• Reloading of <strong>the</strong> application<br />
• Requests continue to backload<br />
• Should do a full shut down if backlog cannot be cleared.<br />
Pre load Everything<br />
• Load maximum processes into server at <strong>the</strong> begninng<br />
• No auto scaling<br />
Horizontal Scaling<br />
• Use more servers<br />
If you treat your server like a black box you will never know what is going<br />
on.<br />
Tools<br />
• New Relic<br />
• Sentry - Captures errors, but not performance problems<br />
Conclusion<br />
• Don’t trust server defaults<br />
• Monitor live production systems<br />
• Use benchmarks to explore a specific system, not to compare different systems.<br />
RESTful APIs With Tastypie<br />
Presenter: Daniel Lindsley<br />
Track: I<br />
Description:<br />
Providing full-featured REST APIs is an increasingly popular request. Tastypie allows you to easily<br />
implement a customizable REST API for your Python or Django applications.<br />
https://us.pycon.org/2012/schedule/presentation/61/<br />
What is Tastypie<br />
• REST framework for Django<br />
• Designed for Extension<br />
• Supports both Model <strong>and</strong> non Model Data<br />
3.2. PyCon 2012 75
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
• tastypieapi.org<br />
Philosophy<br />
• Make good use of HTTP<br />
• Use REST methods/status codes properly<br />
• Graceful Degradation (Backwards Compatable)<br />
• Flexible everything<br />
• Data can round trip (Anything you can GET you should be able to PUT <strong>and</strong> POST)<br />
• Reasonable defaults - but easy to extend<br />
HATEOAS<br />
• Hit API at <strong>the</strong> highest level <strong>and</strong> you should be able to explore it without documentation.<br />
• Users shouldn’t have to know anything in advance<br />
Tastypie<br />
• Builds on top of Django <strong>and</strong> plays nicely<br />
• Full GET/POST/DELETE/PATCH<br />
• Any data source (not just models)<br />
• Designed to be extended<br />
• Supports JSON, XML, etc.<br />
• Well tested<br />
• Lots of hooks<br />
• Decent documentation<br />
‘‘References to <strong>the</strong> Install <strong>Docs</strong> http://django-tastypie.read<strong>the</strong>docs.org/en/latest/index.html ‘‘<br />
• Going over resources, <strong>and</strong> API structure<br />
• api, api/__init__.py, api/resources.py<br />
Automatic<br />
• /api/v1/<br />
• /api/v1/user/<br />
• /api/v1/user/2/<br />
• /api/v1/user/schema<br />
• /api/v1/user/multiple/1;4;5/<br />
76 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Next<br />
• Filter<br />
• Leaking senstive info<br />
• Auth<br />
More<br />
• Exclude<br />
• Au<strong>the</strong>ntication<br />
• Authorization<br />
• Filtering<br />
• Cache<br />
• Throttling<br />
Extensibility<br />
• Why classes - It makes it easy to extend<br />
• Composition > inheritance<br />
• Why so many methods - Hooks, Hooks, Hooks.<br />
• Reasonable defaults, probably want JSON.<br />
• Serialization<br />
• Override or extend as you need.<br />
• Resource has lots of methods, many of which are pretty granular<br />
• Remove some formats<br />
serializer = Searizalier(formats=[’json’, ’xml’])<br />
Fields<br />
• Control how data gets prepared for presenetation<br />
• Full control over <strong>the</strong> API/Schema<br />
• Hydrate <strong>and</strong> dehydrate<br />
Advanced Celery<br />
Presenter: Ask Solem Hoel<br />
Track: V<br />
Description:<br />
This talk will delve deep into advanced aspects of <strong>the</strong> Celery task queue <strong>and</strong> ecosystem. Previous experience<br />
with task queues <strong>and</strong> message oriented middleware is beneficial.<br />
https://us.pycon.org/2012/schedule/presentation/81/<br />
3.2. PyCon 2012 77
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Introduction<br />
• Lead Celery developer<br />
• Task Queue<br />
• Tasks are just dictionaries<br />
• Subtasking<br />
Task Granularity<br />
• Coarse-grained - More Computation<br />
• Chunking can make very granular tasks good<br />
• Chunks can use threads, reduce latency<br />
Chords<br />
• Synchronization Primitive<br />
• Barrier<br />
• Header is a taskset<br />
• Body is applied with <strong>the</strong> results of <strong>the</strong> headers<br />
• Native support for Redis <strong>and</strong> Memcached<br />
Consider Subtasking<br />
::<br />
def smothing(): subtask.delay()<br />
Blocking<br />
• Bad<br />
• Use timeouts <strong>and</strong> retry if possible to stalled tasks.<br />
• Be smarter about routing.<br />
socket.settimeout()<br />
socket.setdefaulttimeout()<br />
• Reroute tasks to machines/workers with free CPU<br />
Cyme<br />
• Cyme node is a branch<br />
• No Master (Decentralized)<br />
• Branches know neighbors<br />
• API<br />
78 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
API<br />
• Create <strong>and</strong> manage<br />
• Create worker instances<br />
• Queues<br />
• Configure workers<br />
• Autoscaling<br />
pip install cyme<br />
cyme-branc -D<br />
What Python can learn from Java<br />
Presenter: Jonathan Ellis<br />
Track: V<br />
Description:<br />
Java is in some ways a bogeyman to <strong>the</strong> Python community – <strong>the</strong> language that parents scare <strong>the</strong>ir children<br />
with, <strong>the</strong> Cobol of <strong>the</strong> 21st century. But if we look past <strong>the</strong> cesspool of JEE it turns out that Java has quietly<br />
become an excellent systems environment, one that is still in many ways ahead of its time.<br />
https://us.pycon.org/2012/schedule/presentation/83/<br />
3.2.4 Sunday<br />
Sketching a Better Product<br />
Presenter: Idan Gazit<br />
Track: I<br />
Description:<br />
If writing is a means for organizing your thoughts, <strong>the</strong>n sketching is a means for organizing your thoughts<br />
visually. Just as good writing requires drafts, good design requires sketches: low-investment, lowresolution<br />
braindumps. Learn how to use ugly sketching to iterate your way to a better product.<br />
https://us.pycon.org/2012/schedule/presentation/301/<br />
Intro<br />
• Django’s BDFL Designer<br />
• Skillsapp.com<br />
Sketching is not drawing<br />
• Skethcing is a tool taht serves a purpose<br />
• Drawing is art, serves itself<br />
• Sketching is for ideas as drafts are to writing<br />
3.2. PyCon 2012 79
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
• Different parts of brain used to process designs, look, feel.<br />
• Act of getting ideas out <strong>and</strong> bak in.<br />
Sketches Should Be<br />
• Cheap, Try different Ideas, No guilt to throwing away<br />
• Fast, quick to create, low resolution<br />
• Less detail<br />
• Ugly, communicate unfinished product<br />
Design Funnel<br />
• Start out wide in scope <strong>and</strong> ideas<br />
• As project progresses, iterate, <strong>and</strong> get more narrow<br />
• Sketches lead to prototype<br />
• Waste less time<br />
Tools<br />
• Paper<br />
• Pen/Markers<br />
• Wall to display <strong>the</strong>m, visible<br />
• Iteration<br />
• iPad<br />
• Penultimate<br />
• Cosmonaut<br />
• iPad resolution isn’t as good as real paper<br />
37 Signals<br />
• Use two fat markers, black <strong>and</strong> red.<br />
• Epicenter Design, sketch <strong>the</strong> core of <strong>the</strong> layout or design<br />
How to Sketch<br />
• Draw lines<br />
• Boxes<br />
• And that is it.<br />
• Greeked Text<br />
80 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Images<br />
• Represent a box with an X<br />
• Fill in<br />
Technique<br />
• Drawing a straight line is hard<br />
• Try rotating page if you can’t draw in one direction<br />
• Ruler for more professional sketching<br />
<strong>Notes</strong><br />
• Stencils<br />
• Sketch <strong>the</strong> Iconic Thing<br />
Improving Documentation with “Beginner’s Mind” (or: Fixing <strong>the</strong> Django Tutorial)<br />
Presenter: Karen Rustad<br />
Track: III<br />
Description:<br />
This talk evaluates a well-known free software tutorial (<strong>the</strong> official Django tutorial) from <strong>the</strong> perspective<br />
of a web development novice in order to point out omissions <strong>and</strong> common sticking points <strong>and</strong> suggest<br />
improvements. More generally, this talk is useful to anyone looking to improve <strong>the</strong>ir project’s tutorials<br />
<strong>and</strong> o<strong>the</strong>r newcomer-targeted documentation by approaching <strong>the</strong>m with “beginner’s mind”.<br />
https://us.pycon.org/2012/schedule/presentation/422/<br />
Documentation Six Audiences <strong>and</strong> Purposes<br />
• First contact ( new users )<br />
• Education ( New )<br />
• Support ( Experienced )<br />
• Troubleshooting<br />
• Internals<br />
• Reference<br />
Documentation for New Users<br />
Most Important docs<br />
• Install/setup<br />
• Tuts<br />
3.2. PyCon 2012 81
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
What Makes a Good Tut<br />
• Advertises what is cool or unique<br />
• Enjoyable - not too long<br />
• Consistently likely to succeed, (platform agnostic, testing)<br />
• Prepares <strong>the</strong> reader for using it on <strong>the</strong>ir own<br />
• These Goals can conflict<br />
New users use tutorials as a scaffold for building whatever <strong>the</strong>y wanted to<br />
build using your project.<br />
Hypo<strong>the</strong>tical Tutorial Using Persona<br />
Kira<br />
• CS Undergrad<br />
• Familiar with python<br />
• New to web dev<br />
Kevin<br />
• Designer<br />
• Knows basic<br />
Django Tutorial Runthrough<br />
• Installation should come first.<br />
• Bad installation hygiene<br />
• Django doesn’t lead users to isolate using virtualenv.<br />
• How do I debug?<br />
• Where to find help?<br />
• Projects vs Apps , what is <strong>the</strong> difference?<br />
• Idea of code reuse.<br />
• No real discussion of test-driven development<br />
• What is tests.py used for?<br />
• Schema migrations - no talk of South<br />
• How to style forms<br />
• Static <strong>and</strong> Media files - not explained in <strong>the</strong> tutorial<br />
• Template inheritance<br />
• Deployment<br />
82 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Target Audience Chnage<br />
• Build a community or a library<br />
• If you want a long running project <strong>and</strong> a community you’ll need longer, more complete tutorial<br />
• Example: Railsbridge, PyStar.org<br />
• Comprehensive tutorials are longer, takes more time.<br />
• Modular structure can make this easier<br />
• Blind searching is hard, put linke in your docs instead<br />
• Better doc, “Intro to web programming using Django”<br />
Issues<br />
• Assuming familiarity with base<br />
• Unstated assumptions<br />
• List of directions withou why<br />
• Code samples<br />
• No obvious place for help<br />
Better <strong>Docs</strong><br />
• Remember you were a novice once<br />
• Realize your own expertise<br />
• Have a user test your docs<br />
• Announce audience<br />
• Explicit Dependencies<br />
• Different tutorials for different audiences<br />
What’s new <strong>and</strong> interesting in st<strong>and</strong>ard library<br />
Presenter: Senthil Kumaran<br />
Track: II<br />
Description:<br />
This talk distills some intereting stuff from What’s new document from 2.7, 3.2 <strong>and</strong> upcoming 3.3 release.<br />
Look out for those new arguments to your favorite methods, functions add <strong>the</strong> wow! factor to your code.<br />
Heard of @lru_cache?<br />
https://us.pycon.org/2012/schedule/presentation/303/<br />
Slides are Available:<br />
http://uthcode.googlecode.com/svn/trunk/presentations/pycon2012/index.html<br />
3.2. PyCon 2012 83
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
faulth<strong>and</strong>ler<br />
• New faulth<strong>and</strong>ler module.<br />
• This module contains functions to dump Python tracebacks explicitly, on a fault, after a timeout, or on a user<br />
signal. Call faulth<strong>and</strong>ler.enable() to install fault h<strong>and</strong>lers for <strong>the</strong> SIGSEGV, SIGFPE, SIGABRT, SIGBUS, <strong>and</strong><br />
SIGILL signals.<br />
• It is version 3.3 <strong>and</strong> was contributed by Victor Stinner.<br />
lzma<br />
• The newly-added lzma module provides data compression <strong>and</strong> decompression using <strong>the</strong> LZMA algorithm, including<br />
support for <strong>the</strong> .xz <strong>and</strong> .lzma file formats.<br />
• lzma compression is usually better than bz2.<br />
• Python 3.3<br />
• Per Øyvind Karlsen, Nadeem Vawda <strong>and</strong> o<strong>the</strong>rs.<br />
bz2 module<br />
• bz2.BZ2File can now read from <strong>and</strong> write to arbitrary file-like objects, by means of its constructor’s fileobj<br />
argument. (Nadeem Vawda)<br />
• bz2.BZ2File <strong>and</strong> bz2.decompress() can now decompress multi-stream inputs. bz2.BZ2File can now also be used<br />
to create this type of file, using <strong>the</strong> ‘a’ (append) mode. (Nir Aides)<br />
os module<br />
• sendfile() function which provides an efficent “zero-copy” way for copying data from one file (or socket) descriptor<br />
to ano<strong>the</strong>r. ( Ross Lagerwall <strong>and</strong> Giampaolo Rodola’)<br />
• Use of sendfile instead of send provides 1.5x speed up!<br />
fwalk() function similar to walk() except that it also yields file descriptors referring to <strong>the</strong> directories visited. (Interesting!)<br />
* Since 3.2 - The os module provides two new functions, fsencode() <strong>and</strong> fsdecode(), for encoding <strong>and</strong> decoding<br />
filenames based on file-system encoding.<br />
packaging<br />
• distutils module is called packaging, helper functions for building, packaging, distributing <strong>and</strong> installing additional<br />
projects into a Python installation.<br />
• distutils is still provided in <strong>the</strong> st<strong>and</strong>ard library, but users are encouraged to transition to packaging.<br />
• New features from packaging will be available under distutils2 in PyPI.<br />
signal module<br />
• signal.signal() <strong>and</strong> signal.siginterrupt() raise an OSError, instead of a RuntimeError: OSError has an errno<br />
attribute.<br />
• signal module has functions such as pthread_sigmask , pthread_kill, sigpending, sigwait, sigwaitinfo.<br />
84 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
• Jean-Paul Calderone, Antoine Pitrou <strong>and</strong> o<strong>the</strong>rs.<br />
socket module<br />
• The socket class now supports <strong>the</strong> PF_CAN protocol family. (Matthias Fuchs, Tiago Gonçalves) - Control Area<br />
Network Bus Drivers.<br />
• The socket class now supports <strong>the</strong> PF_RDS protocol family - Reliable High performance, low latency reliable<br />
connectioness protocol for delivering datagrams.<br />
ssl module<br />
RAND_bytes(): generate cryptographically strong pseudo-r<strong>and</strong>om bytes. RAND_pseudo_bytes(): generate<br />
pseudo-r<strong>and</strong>om bytes. (Both by Victor Stinner) Query <strong>the</strong> SSL compression algorithm used by an SSL<br />
socket, thanks to its new compression() method. You can also supress Compression. ( Antoine Pitrou)<br />
sys module<br />
The sys module has a new thread_info struct sequence holding informations about <strong>the</strong> thread implementation.<br />
>>> sys.thread_info<br />
sys.thread_info(name=’pthread’, lock=’semaphore’, version=’NPTL 2.13’)<br />
urllib package<br />
The Request class, now accepts a method argument used by get_method() to determine what HTTP<br />
method should be used. For example, this will send a ‘HEAD’ request.<br />
>>> urlopen(Request(’http://www.python.org’, method=’HEAD’))<br />
urllib package<br />
• The parse.urlparse() function now supports IPv6 addresses as described in RFC 2732<br />
request.urlopen can take POST which can be an iterable. * http.client.HTTPSConnection, urllib.request.HTTPSH<strong>and</strong>ler<br />
<strong>and</strong> urllib.request.urlopen() now take optional arguments to allow for server certificate<br />
checking against a set of Certificate Authorities, as recommended in public uses of HTTPS<br />
argparse - 3.2<br />
• argparse will be <strong>the</strong> future <strong>and</strong> optparse will slowly be deprecated.<br />
• Support for positional args, sub-comm<strong>and</strong>s, ‘required options’, pattern for specifying <strong>and</strong> validating options.<br />
• argparse has <strong>the</strong> ability to define subparsers, each with <strong>the</strong>ir own argument patterns <strong>and</strong> help displays:<br />
3.2. PyCon 2012 85
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
logging module - 3.2<br />
• The logging documentation has been augmented by a basic tutorial, an advanced tutorial, <strong>and</strong> a cookbook of<br />
logging recipes.<br />
• logging.config.dictConfig() - logging configuration with plain Python dictionaries.<br />
with open(’conf.json’, ’r’) as f:<br />
conf = json.load(f)<br />
logging.config.dictConfig(conf)<br />
from concurrent import futures - 3.2<br />
• Code for creating <strong>and</strong> managing concurrency is being collected in a new top-level namespace, concurrent<br />
first package is futures high level interface for managing threads <strong>and</strong> processes. * Inspired by java.utils.concurrent<br />
<strong>and</strong> Future Object. status checks (running or done), timeouts, cancellations, adding callbacks, <strong>and</strong> access to results or<br />
exceptions<br />
functools - 3.2<br />
• The functools module includes a new decorator for caching function calls. functools.lru_cache() can save repeated<br />
queries to an external resource whenever <strong>the</strong> results are expected to be <strong>the</strong> same.<br />
>>> import functools<br />
>>> @functools.lru_cache(maxsize=300)<br />
>>> def get_phone_number(name):<br />
c = conn.cursor()<br />
c.execute(’SELECT phonenumber FROM phonelist WHERE name=?’, (name,))<br />
return c.fetchone()[0]<br />
...<br />
>>> get_phone_number(name) # cached lookup<br />
functools - 3.2<br />
• We have cache stats<br />
>>> get_phone_number.cache_info()<br />
CacheInfo(hits=4805, misses=980, maxsize=300, currsize=300)<br />
• OMG! Way to get unwrapped function.<br />
>>> get_phone_number = get_phone_number.__wrapped__ # uncached function<br />
• functools.total_ordering - rich comparison methods, a new decorator functools.total_ordering() will use a existing<br />
equality <strong>and</strong> inequality methods to fill in <strong>the</strong> remaining methods.<br />
@total_ordering<br />
class Student:<br />
def __eq__(self, o<strong>the</strong>r):<br />
return ((self.lastname.lower(), self.firstname.lower()) ==<br />
(o<strong>the</strong>r.lastname.lower(), o<strong>the</strong>r.firstname.lower()))<br />
def __lt__(self, o<strong>the</strong>r):<br />
return ((self.lastname.lower(), self.firstname.lower()) <<br />
86 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Magic happens.<br />
(o<strong>the</strong>r.lastname.lower(), o<strong>the</strong>r.firstname.lower()))<br />
itertools - 3.2<br />
>>> from itertools import accumulate<br />
>>> list(accumulate([8, 2, 50]))<br />
[8, 10, 60]<br />
collections<br />
• The collections.Counter class now has two forms of in-place subtraction, <strong>the</strong> existing -= operator for saturating<br />
subtraction <strong>and</strong> <strong>the</strong> new subtract() method for regular subtraction<br />
• http://en.wikipedia.org/wiki/Saturation_arithmetic If <strong>the</strong> result of an operation is greater than <strong>the</strong> maximum it is<br />
set (“clamped”) to <strong>the</strong> maximum, while if it is below <strong>the</strong> minimum it is clamped to <strong>the</strong> minimum.<br />
• All <strong>the</strong>se features were added by Raymond Hettinger<br />
collections<br />
>>> tally = Counter(dogs=5, cat=3)<br />
>>> tally -= Counter(dogs=2, cats=8) # saturating subtraction<br />
>>> tally<br />
Counter({’dogs’: 3})<br />
>>> tally = Counter(dogs=5, cats=3)<br />
>>> tally.subtract(dogs=2, cats=8) # regular subtraction<br />
>>> tally<br />
Counter({’dogs’: 3, ’cats’: -5})<br />
unittest - 3.2<br />
• Improvements supporting test discovery for packages, easier experimentation at <strong>the</strong> interactive prompt<br />
python -m unittest discover -s my_proj_dir -p _test.py<br />
Interactivity!<br />
>>> TestCase().assertEqual(pow(2, 3), 8)<br />
pyc directories - 3.2<br />
• 3.2 onwards<br />
• Multiple implementations can refer to <strong>the</strong>ir own .pyc files.<br />
• mymodule.cpython-32.pyc, mymodule.cpython-33.pyc, <strong>and</strong> mymodule.unladen10.pyc<br />
• pyc files are now collected in a __pycache__ directory stored under <strong>the</strong> package directory<br />
3.2. PyCon 2012 87
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
• Imported modules now have a __cached__ attribute which stores <strong>the</strong> name of <strong>the</strong> actual file that was imported<br />
tag that is unique to each interpreter is accessible from <strong>the</strong> imp module<br />
WSGI 1.1.1<br />
• Well Intentioned Upgrade for WSGI to support Python3.<br />
• Informational PEP clarifies how bytes/text issues are to be h<strong>and</strong>led by <strong>the</strong> WGSI protocol<br />
New string formatting 3.2<br />
• str.format_map<br />
• It can take dictionaries from defaultdict, shelve, ConfigParser, dbm.<br />
>>> import shelve<br />
>>> d = shelve.open(’tmp.shl’)<br />
>>> ’The {project_name} status is {status} as of {date}’.format_map(d)<br />
’The testing project status is green as of February 15, 2011’<br />
>>> class PlaceholderDict(dict):<br />
def __missing__(self, key):<br />
return ’’.format(key)<br />
>>> ’Hello {name}, welcome to {location}’.format_map(PlaceholderDict())<br />
’Hello , welcome to ’<br />
threading 3.2<br />
• The threading module has a new Barrier synchronization class for making multiple threads wait until all of <strong>the</strong>m<br />
have reached a common barrier point.<br />
from threading import Barrier, Thread<br />
def get_votes(site):<br />
ballots = conduct_election(site)<br />
all_polls_closed.wait() # do not count until all polls are closed<br />
totals = summarize(ballots)<br />
publish(site, totals)<br />
all_polls_closed = Barrier(len(sites))<br />
for site in sites:<br />
Thread(target=get_votes, args=(site,)).start()<br />
ast module<br />
• The ast.literal_eval() function serves as a secure alternative to <strong>the</strong> builtin eval() function which is easily abused.<br />
>>> from ast import literal_eval<br />
>>> request = "{’req’: 3, ’func’: ’pow’, ’args’: (2, 0.5)}"<br />
>>> literal_eval(request)<br />
{’args’: (2, 0.5), ’req’: 3, ’func’: ’pow’}<br />
>>> request = "os.system(’do something harmful’)"<br />
88 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
>>> literal_eval(request)<br />
Traceback (most recent call last):<br />
...<br />
ValueError: malformed node or string: <br />
array module - 3.3<br />
• array module takes long long type.<br />
shutil - 3.3<br />
• shutil.disk_usage() - total, used <strong>and</strong> free disk space statistics.<br />
Deprecation Warnings - 2.7<br />
• DeprecationWarning <strong>and</strong> its descendants are now ignored unless o<strong>the</strong>rwise requested, preventing users from<br />
seeing warnings triggered by an application.<br />
• Previous Python 2.x releases had DeprecationWarning ON by default. Now, since <strong>the</strong> path to upgrade is 3.x,<br />
those have been silenced unless explictly requested.<br />
• You can re-enable display of DeprecationWarning messages by running Python with <strong>the</strong> -Wdefault (short form:<br />
-Wd) switch, or by setting <strong>the</strong> PYTHONWARNINGS environment variable to “default” (or “d”) before running<br />
Python.<br />
3.x Backported Features in 2.7<br />
• The syntax for set literals ({1,2,3} is a mutable set).<br />
• Dictionary <strong>and</strong> set comprehensions ({i: i*2 for i in range(3)}).<br />
• Multiple context managers in a single with statement.<br />
• A new version of <strong>the</strong> io library, rewritten in C for performance.<br />
• The ordered-dictionary type described in PEP 372<br />
• The new ”,” format specifier for Thous<strong>and</strong>s Separator PEP 378<br />
• The memoryview object <strong>and</strong> this is fur<strong>the</strong>r improved in 3.3<br />
• A small subset of <strong>the</strong> importlib module <strong>and</strong> full version of importlib will be in place in 3.3<br />
Dictionary Views<br />
• viewkeys(), viewvalues(), <strong>and</strong> viewitems() return an object called views.<br />
Bug fixes in modules<br />
• http://docs.python.org/whatsnew/2.7.html#new-<strong>and</strong>-improved-modules<br />
• 2.7.x is <strong>the</strong> maintained bug fix release. All bug reports which have been reported have found it’s way to 2.7.x<br />
• Only new features do not make it to 2.7.<br />
3.2. PyCon 2012 89
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
• It’s a stable release which can you to upgrade to Python 3.x<br />
There is more<br />
• http://docs.python.org/dev/whatsnew/3.3.html<br />
• http://docs.python.org/dev/whatsnew/3.2.html<br />
• http://docs.python.org/dev/whatsnew/2.7.html<br />
• Misc/NEWS file.<br />
print(’{0} {1}’.format(’Thank’,’ you!’))<br />
• Presentation - http://bit.ly/pycon2012stdlib<br />
3.3 Django Con US 2012<br />
Location: Hyatt Regency Crystal City, Washington, D.C.<br />
When: September 4th–6th 2012.djangocon.us<br />
Description:<br />
DjangoCon US is <strong>the</strong> main opportunity for djangonauts to come toge<strong>the</strong>r in <strong>the</strong> United States. It will<br />
consist of two tracks of talks over three days, <strong>and</strong> will also provide for open sessions, lightning talks, <strong>and</strong><br />
a development sprint after <strong>the</strong> conference.<br />
3.3.1 Tuesday<br />
Keynote<br />
Presenter: Eric Sterling<br />
Track: N/A<br />
Description:<br />
Keynote Address<br />
Local vs National<br />
• Local involvement is critical<br />
• Role of Money<br />
• Influence of people with money <strong>and</strong> access<br />
State Rights<br />
• Citizen power scares elected officials.<br />
• Knowledge is power<br />
• Knowledge <strong>and</strong> passion go toge<strong>the</strong>r<br />
90 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Maintaining Your Sanity While Maintaining Your Open Source App<br />
Presenter: Mark Lavin<br />
Track: I<br />
Description:<br />
Django has a thriving community of open source pluggable applications. Maintaining an external application<br />
can be a rewarding experience <strong>and</strong> doesn’t need to take over your life. Learn what it takes to package,<br />
document <strong>and</strong> test your Django app so that o<strong>the</strong>rs can use <strong>and</strong> contribute to what you’ve built.<br />
Brewedbyus.com<br />
Packaging<br />
• Package to use PIP<br />
• Direct users to use PIP first<br />
• Setuptools find_packages<br />
‘ Include Package Data ‘<br />
• Pull description from <strong>Read</strong>Me<br />
• Follow PEP386<br />
• 3 Numbers<br />
• Be consistent in version numbers<br />
• MANIFEST.in<br />
• Register on Pypi!<br />
Documentation<br />
• No Giant READMEs<br />
• <strong>Docs</strong> should be available online<br />
• Use sphinx <strong>and</strong> <strong>Read</strong> <strong>the</strong> <strong>Docs</strong><br />
Things To Document<br />
• How to install<br />
• Description of <strong>the</strong> project<br />
• How to configure <strong>the</strong> app<br />
• <strong>Release</strong> <strong>Notes</strong><br />
• Be clear<br />
3.3. Django Con US 2012 91
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Hosting <strong>Docs</strong><br />
• Setup post commit hook<br />
• Link to your repo<br />
Testing<br />
• Tests should not fail without an example project<br />
• Tests should not depend on small settings changes<br />
• Test only models<br />
• Run tests.py<br />
Test with TOX<br />
• User virtualenv to test<br />
• Test different versions of python/django<br />
• Test different DBs<br />
Goals<br />
• State your goals<br />
• Set expectations<br />
License<br />
• Always include a License<br />
• Prepare for <strong>the</strong> future<br />
Be <strong>Read</strong>y for Python 3<br />
• Be ready to be replaced<br />
• TOX<br />
Rejecting Requests<br />
• You can’t reject every contribution<br />
• Don’t reject based on tests <strong>and</strong> docs. Point <strong>the</strong>m in <strong>the</strong> right direction.<br />
• Do NOT accept every request.<br />
• If you accept it, be prepared to maintain it.<br />
92 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Avoid Burnout<br />
• Its okay to step away for a while.<br />
• Should not feel like a burden<br />
Debugging Live Python Web Applications<br />
Presenter: Amjith Ramanujam<br />
Track: II<br />
Description:<br />
Monitoring tools record <strong>the</strong> result of what happened to your web application when a problem arises, but<br />
for some classes of problems, monitoring systems are only a starting point. Sometimes it is necessary<br />
to take more intrusive steps to plan for <strong>the</strong> unexpected by embedding mechanisms that will allow you to<br />
interact with a live deployed web application <strong>and</strong> extract even more detailed information.<br />
Why Debug?<br />
• Obvious - Python exceptions<br />
• Subtle - Memory leaks<br />
• Performance - Slowness<br />
• Heisen - Only shows up in production.<br />
• Devops - Says no to debugging in production<br />
Things to Avoid<br />
• Do not do more damage<br />
** Crashing <strong>the</strong> site ** Loss of customer data<br />
Manage Risk<br />
• Use software that restricts what you can do.<br />
• Script changes<br />
• Test what you are going to do first<br />
• Develop contingency plans<br />
Monitoring<br />
Passive<br />
• Collection of log info<br />
• Collection of Python exceptions<br />
• Collection of performance data from hosts<br />
3.3. Django Con US 2012 93
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
• Logstash<br />
• graylog2<br />
• Sentry <strong>and</strong> New Relic<br />
Server Monitoring<br />
• Monit<br />
• Munin<br />
• Cacti<br />
• Nagios<br />
• New Relic<br />
Application Performance Monitoring<br />
• New Relic<br />
Web Page Performance<br />
• YSlow<br />
• GooglePageSpeed<br />
• WebPageTest<br />
• Firebug<br />
Transaction Tracing<br />
• Newrelic provides tracing at <strong>the</strong> function/method level.<br />
• Monkey patching instrumentation<br />
newrelic.api.function_trace.wrap_function_code<br />
Profiling<br />
• Thread Sampling<br />
** Plop ** statprof * Full Profile ** cprofile ** pytrace<br />
Browser<br />
• django-debug-toolbar<br />
• paste error middleware<br />
94 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Live Debugging (Dark Art)<br />
• Building backdoors<br />
• USing Pythons built in logging<br />
ispyd<br />
• Interactive debug console for use in production<br />
• Application must have backdoor, listens to socket<br />
• Demo<br />
• bit.ly/LiveDebugging<br />
Views Can Be Classy<br />
Presenter: Kenneth Love<br />
Track: II<br />
Description:<br />
An overview of what class-based views (CBVs) are, which ones are available, <strong>and</strong> how to use <strong>the</strong>m in<br />
your projects. I’ll also cover creating mixins, where function-based views still make sense, <strong>and</strong> how to<br />
test CBVs. As part of this, I’ll be covering my django-braces (https://crate.io/packages/django-braces/)<br />
package.<br />
Who Am I<br />
• @kennethlove<br />
Class Based Views<br />
• Bad right?<br />
Bad<br />
• Decorators must be wrapped around dispatch()<br />
• Inheritance chains. Not very obvious what is going on.<br />
• Combining mixin <strong>and</strong> views creates order exceptions<br />
• So much more going that you can’t see.<br />
MRO<br />
• Two classes that inherit from <strong>the</strong> same base class, but has methods in different orders.<br />
• Bit.ly/PythonMRO<br />
• A little enterprise-ish<br />
3.3. Django Con US 2012 95
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Why Use CBV<br />
• Faster implementation<br />
• Keep views.py concise<br />
• Everything is a class (Models, Forms, Templates)<br />
• Special cases are not special enough to break <strong>the</strong> rules, Views should be classes too.<br />
Batteries Included<br />
Object Based Views<br />
• Single object<br />
• Multitple object mixins<br />
• Detail/List View<br />
Form Based Views<br />
• Form View<br />
• Create View<br />
• Update View<br />
Date based Views<br />
• Year<br />
• Month<br />
• Day<br />
• Date<br />
Utility Views<br />
• Template Response<br />
• Template View<br />
• Redirect<br />
• View<br />
Common Methods<br />
• Dispatch, (Get, Post, Put, Delete)<br />
• get_context_data<br />
• get_object<br />
• get_queryset<br />
96 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
• get_form_class<br />
• get_form_kwargs<br />
• get_success_url<br />
• form_valid<br />
• Demo<br />
• Add base classes for common functionality in views. Convert <strong>the</strong>m into Mixins.<br />
Customizing<br />
• context_object_name<br />
• Base classes <strong>and</strong> Mixins are <strong>the</strong> same thing.<br />
• Mixins have a single purpose<br />
• Base class can have multiple mixins or whole new functions.<br />
Design Patterns<br />
• Using None as default<br />
• Move mixins to <strong>the</strong> front<br />
• Prevent code from running if it doesn’t meet requirements (Users aren’t logged in).<br />
Decoration<br />
• You can decorate inside <strong>the</strong> urls.py<br />
• You can add a second variable <strong>and</strong> wrap <strong>the</strong> .as_view() method.<br />
Function Based Views<br />
• Session manipulation<br />
• Login/Logout<br />
Django on Gevent<br />
Presenter: Cody Soyl<strong>and</strong><br />
Track: II<br />
Description:<br />
This is an introduction to using <strong>the</strong> Gevent networking library to empower your Django application with<br />
realtime features <strong>and</strong> resource-efficient cooperative concurrency. Django’s synchronous APIs make it<br />
impractical to use in a callback-based networking library, but fast single-threaded concurrency is still<br />
possible using <strong>the</strong> mind-blowing capabilities of coroutines.<br />
3.3. Django Con US 2012 97
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Real Time Web<br />
• Delivery of information as it happens<br />
• Open connections<br />
• C10K Problem 0 How do web servers h<strong>and</strong>le thous<strong>and</strong>s of connections at once<br />
New Challenges<br />
• Non blocking I/O<br />
• Low resource overhead<br />
• Distributed<br />
Concurrent Systems<br />
• Processes<br />
• Threads<br />
• Callbacks<br />
• Coroutines<br />
Threads<br />
• Memory Overhead<br />
• <strong>Read</strong>able, synchronous interface<br />
• Guaranteed cooperation<br />
Callbacks<br />
• Call stack not preserved<br />
• Simple things are intuitive<br />
• Complex things become confusing<br />
Coroutines<br />
• Call stack preserved<br />
• Synchronous API<br />
• Benefits of threads without <strong>the</strong> non-determinism<br />
98 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Greenlet<br />
• True coroutines in Python<br />
• Exp<strong>and</strong>s upon greenlet to provide “green threads”<br />
• Provides an event loop<br />
Green Threads<br />
• POSIX threads are pre-emptive<br />
• Green threads are cooperative<br />
• Very light weight<br />
Django Software Foundation Keynote<br />
Presenter: Russell Keith-Magee<br />
Track: N/A<br />
Description:<br />
State of <strong>the</strong> DSF<br />
• Board Members<br />
• Developer Members<br />
Corporate Members<br />
• Small/$500<br />
• Medium/$1000<br />
• Large/$5000<br />
Responsibilities<br />
• DSF doesn’t own copyright<br />
• DSF licenses code<br />
• Contributor License Agreements<br />
• Django Trademark<br />
CLA<br />
• Submit one if you have contributed code<br />
3.3. Django Con US 2012 99
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Not Okay To<br />
• Anything that implies endorsement<br />
• Especially in Commerce<br />
Trademark<br />
• Cannot start a company with Django <br />
Django Con<br />
• Anyone can run a Django <strong>Conference</strong><br />
• DSF licenses “DjangoCon” to <strong>the</strong> organizers<br />
• DSF not involved in DjangoCon operation<br />
Infrastructure<br />
• Djangoproject.com Rebuild<br />
• people.djangoproject.com<br />
• djangosnippets.com<br />
• $1000 to read <strong>the</strong> docs<br />
• Hosting thanks to Heroku, MediaTemple<br />
• Training<br />
• Sprints/PyCon sprint<br />
• <strong>Conference</strong> Sponsorships (Pycon/DjangoCons)<br />
• Travel Grants<br />
• DSF as a publisher?<br />
• Merch<strong>and</strong>ise<br />
• Help us help you<br />
Designing Your Open Source Project<br />
Presenter: Bryan Veloso<br />
Track: II<br />
Description:<br />
There is an ever present rift between designers <strong>and</strong> developers <strong>and</strong> it is one that has existed since our paths<br />
started crossing. We’ll talk about how to be mindful of design in your own open source project <strong>and</strong> how<br />
to attract designers to help your project become even more awesome.<br />
100 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Design <strong>and</strong> Open Source<br />
• Developers <strong>and</strong> Designers are quite similar.<br />
• Respecting clarity<br />
• Find hybrids<br />
• Teach each o<strong>the</strong>r<br />
These notes are short, because this talk was very good <strong>and</strong> I forgot to take a lot of notes..<br />
https://speakerdeck.com/u/bryan/p/designing-your-open-source-project<br />
API Design Tips<br />
Presenter: Daniel Lindsley<br />
Track: I<br />
Description:<br />
The focus of this talk will be on some pragmatic tips on how to design programmatic (non-web-based)<br />
APIs for use by o<strong>the</strong>r developers.<br />
What<br />
• Not HTTP APIs<br />
• Programmatic APIs<br />
• Libraries<br />
Why<br />
• O<strong>the</strong>r people use your code all <strong>the</strong> time<br />
• You might be not happy with past you.<br />
You cannot make everyone happy<br />
• You make assumptions about your environment<br />
• These don’t always apply for o<strong>the</strong>r people<br />
• More people are happy if <strong>the</strong>y can extend libraries<br />
• No copy-paste should be needed<br />
• Good docs matter<br />
• Real world use is <strong>the</strong> best use.<br />
3.3. Django Con US 2012 101
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Design<br />
• Bottom up<br />
• Top down<br />
• Bottom up sucks<br />
• Top down feels better<br />
• Everything fits toge<strong>the</strong>r<br />
• Less duplication<br />
• Test Driven Design<br />
Things you Should Do<br />
• Small components<br />
• Reflection (To <strong>and</strong> From) Be able to reverse operate<br />
• Narrow Familiarity - How similar is <strong>the</strong> code itself.<br />
• Assume <strong>the</strong> worst<br />
• Use it, <strong>the</strong>n step back <strong>and</strong> ask yourself how to make it better, easier for <strong>the</strong> user<br />
• Quick wins<br />
• Return values should be consistent<br />
Things you should NOT do<br />
• Low level API is good enough<br />
• Wildly different return values<br />
• If its diffcult to test, its probably wrong<br />
Django Specific<br />
• Pluggable backend all <strong>the</strong> things<br />
• Declaritive syntax<br />
• Avoid global state (Use __init__ )<br />
• Decrease reliance on self<br />
• Resist urge to use magic<br />
https://speakerdeck.com/u/daniellindsley/p/api-design-tips<br />
102 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
3.3.2 Wednesday<br />
Keynote - Fixing Computer Science<br />
Presenter: Selena Deckelmann<br />
Track: N/A<br />
Description:<br />
Keynote Address<br />
Fixing Computer Science<br />
• Computer science enrollment has decreased<br />
• 50% growth expected by 2018<br />
• 70% of FOSS devs have at least a Bachelors degree<br />
Open Source Lifestyle<br />
• Freedom<br />
• Sharing<br />
• Licensing<br />
• Work/Learn/Teach<br />
Teaching Someone How to Program<br />
• Mentoring<br />
• Filesystem navigation<br />
• Very confusing for new users GUI to Terminal<br />
• Explain filesystems for BOTH GUI <strong>and</strong> Terminal<br />
• New users get frustrated easily<br />
Open Licensing of Materials<br />
• Paris Declaration (http://bit.ly/MTvxzl)<br />
How to Teach<br />
• Just challenging enough to be interesting, but not hard enough to be frustrating<br />
• Modeling<br />
• Guided practice<br />
• Independent Practice<br />
• Generalization<br />
3.3. Django Con US 2012 103
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
• Have <strong>the</strong>m teach/explain <strong>the</strong> concept back to you<br />
Lost 35% of CS courses in High Schools<br />
• O<strong>the</strong>r academic areas are represented in High Schools<br />
• Shortage of teachers in areas where CS is desired<br />
• Minorities are not represented<br />
• Computer science seen as an elective<br />
• Not a part of Math or Science<br />
What we need to Teach<br />
• Computational Thinking<br />
• Large gap between teachers <strong>and</strong> open source developers<br />
Invite more people into Open Source<br />
• Speak language of education<br />
• Open source IT in schools is not <strong>the</strong> answer, right now.<br />
• Teachers are nautural alies for FOSS developers<br />
Access to computer science is a social justice issue.<br />
The Dungeon Master’s guide to Django’s ORM<br />
Presenter: MALCOLM TREDINNICK<br />
Track: II<br />
Description:<br />
If you’ve ever been curious about Django’s ORM implementation, you will have noticed <strong>the</strong> required<br />
learning curve. Some of <strong>the</strong> code is fairly complicated. O<strong>the</strong>r bits are worse. Here comes a 30 or 40<br />
minute guided tour of <strong>the</strong> uncharted realms: how <strong>the</strong> pieces fit toge<strong>the</strong>r, where to look for things, why <strong>the</strong><br />
current design is what it is. A portion of this is my fault; I should probably explain myself.<br />
Me<br />
• Python since 1997<br />
• Django user since Sept 2005<br />
• Django committer in May 2006<br />
104 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
History<br />
• 12 July 2005, import from private svn repo<br />
• Magic removal branch - 1 May 2006<br />
• 3 Ways of structuring <strong>the</strong> ORM were attempted<br />
• 4 July 2007 - Merge new ORM back in (Unicode)<br />
• 2008 - 1.0<br />
Worth It<br />
• Code structure has remained fairly stable<br />
• Abstraction feels right<br />
• Minor code duplication in recent times<br />
• Mostly logical code flow.<br />
Useful Rule<br />
• Developers who were here before you where probably not insane.<br />
Layers<br />
• django/db/modles/query.py - 1800 lines<br />
• django/db/models/sql/query.py - 2000 lines<br />
• django/db/backends/* - base.py, operations.py<br />
Down <strong>the</strong> Rabbit Hole<br />
• Simple filter query Article.objects.filter()<br />
• db.models.query.QuerySet<br />
• db.models.sql.query.Query<br />
• db.models.sql.where.WhereNode<br />
• db.models.sql.compiler.SQLCompailer<br />
• Continually filter from previous filters.<br />
Background<br />
• Nested queries<br />
• QuerySets can be merged<br />
• All aliases in a QuerySet can be changed at once.<br />
3.3. Django Con US 2012 105
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Cryptography for Django Applications<br />
Presenter: ERIK LABIANCA<br />
Track: II<br />
Description:<br />
A review of encryption in <strong>the</strong> context of a web application storing sensitive information. Topics covered<br />
include choosing whe<strong>the</strong>r to use crypto, selection of tools, proper usage (including examples), <strong>and</strong><br />
operational considerations with respect to security assessment.<br />
Who<br />
• Developer, Not cryptographer<br />
• Should you trust me? Maybe.<br />
TLDR<br />
• Analyze risks<br />
• Don’t write your own<br />
• Operate correctly<br />
• Commit to keeping up<br />
Hacks happen all <strong>the</strong> time<br />
Analyze<br />
• Data<br />
• Systems<br />
• Identify Vulnerabilities (Backups, Laptops, Compromised systems)<br />
• Analyze controls (Locked safe, Cryptography)<br />
Hash Properties<br />
• No Keys<br />
• Easy to compute <strong>the</strong> has value<br />
• Very hard to generate a message for a known hash value, modify without changing <strong>the</strong> hash.<br />
• Used for signed cookie <strong>and</strong> sessions in Django<br />
• Password verification<br />
106 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Symmetric Encryption Algorigthms<br />
• Secret Key<br />
• Reversible<br />
• Requires shared secret<br />
Public Key Cryptography<br />
• Asymmetric<br />
• N-way<br />
• 2 + keys<br />
Asymmetric Encryption Properties<br />
• Lots of complex keys<br />
• Slow<br />
Really need to be running HTTPS<br />
Django<br />
• Django does it right<br />
• Enable HTTPS<br />
• Enforce use of HTTPS via redirects<br />
• Inform django your useing HTTPS<br />
Tell Django your using HTTPS:<br />
SESSION_COOKIE_SECURE = True<br />
CSRF_COOKIE_SECURE = TRue<br />
SECURE_PROXY_SSL_HEADER<br />
• Protect data via SKC<br />
• Support encrypted payloads<br />
• FIPS / NIST recommendations<br />
• 1.4 is much better than <strong>1.3</strong><br />
• Keys can be kept in memory<br />
Lesson on Testing<br />
Presenter: David Cramer<br />
Track: II<br />
Description:<br />
3.3. Django Con US 2012 107
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Learn from failures (<strong>and</strong> successes) around testing patterns <strong>and</strong> culture in a growing company, both in<br />
amount of code, <strong>and</strong> number of engineers. We’ll dive into how DISQUS adopted testing, <strong>and</strong> <strong>the</strong> many<br />
challenges we’ve had to overcome.<br />
Time Consuming to Write<br />
• Takes long time to write good tests<br />
• 10 lines of code has 36 lines of tests<br />
• 50% of time is spent writing tests<br />
• Legacy code is expensive to test<br />
• Spend more time running <strong>the</strong>m, hardware is cheap.<br />
• Lots of Demos<br />
• If path changes, mock fails<br />
• Tests break a lot on code changes<br />
• Mock is useful for testing external services<br />
• Test <strong>the</strong> lifecycle of requests<br />
• Kind of works<br />
• Brittle<br />
• Use Phantom JS for js tests<br />
• Start with a Goal<br />
• Write testable Code<br />
• Break up code<br />
• Create Structure<br />
• Put tests in <strong>the</strong> top level directory<br />
• Document best practices<br />
• Continuous builds<br />
• Tests should be a part of your culture<br />
• Code Review<br />
• Test throughout <strong>the</strong> process<br />
• Nose (nose.read<strong>the</strong>docs.org)<br />
• Tests aren’t enough<br />
• Deep trace<br />
• Code Reviews<br />
• Culture is Key<br />
108 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Keynote - BDFL<br />
Presenter: Adrian Holovaty<br />
Track: N/A<br />
Description:<br />
Keynote Address<br />
Local Flavor Failure<br />
The Year Ahead<br />
• Between Now <strong>and</strong> <strong>the</strong> next Django Con<br />
Django 1.5<br />
• Alpha Oct 1<br />
• Beta Nov<br />
• Final release by Christmas<br />
• Porting to Python 3<br />
Coming UP<br />
• Remove local flavor<br />
• Comments also being removed<br />
• Removal of settings<br />
• New User/Auth design<br />
• Build your own User model<br />
• Concept of an APP object, get rid of global state<br />
PJAX<br />
• Single piece of middleware<br />
• Real time pushing<br />
Django Forms in an API World<br />
Presenter: TAREQUE HOSSAIN<br />
Track: I<br />
Description:<br />
3.3. Django Con US 2012 109
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
In a world of django powered web APIs <strong>and</strong> arbitrary consumers, traditional methods of rendering &<br />
validating django forms are ineffective. We discuss how to uphold <strong>the</strong> API provider/ consumer separation,<br />
yet utilize provider’s django form subsystem to power forms in a pure JS consumer. We achieve this by<br />
serializing form configurations, rendering metadata, error h<strong>and</strong>lers & exposing <strong>the</strong>m over API.<br />
Whats wrong with Forms<br />
New Way<br />
• Django forms live on API server<br />
• Validates/saves API<br />
• Trying to match frontend to <strong>the</strong> API<br />
API Clients<br />
• Website no longer lives on <strong>the</strong> same server<br />
• Forms exist on phones/web sites/o<strong>the</strong>r devices<br />
Issue<br />
• Forms have to be re created on each device<br />
• Browser considered a device<br />
• API/Form doesn’t match up<br />
What is a form<br />
• Blank document with places to add informations<br />
Django Forms<br />
• Binds/Validates data<br />
• Display<br />
• Model Forms<br />
• Easy<br />
• Widgets<br />
Distributed Services<br />
• Build an API<br />
110 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Deliver Form Definition over API<br />
• Define form in API<br />
• Serialize Form<br />
• Deliver, Recieve, Validate, Show Errors, <strong>and</strong> Process<br />
• Render, Submit, Validate<br />
• django remote forms<br />
• Encapsulate processing in form.save similar to model form<br />
Render forms with H<strong>and</strong>lebars/JS/CSS<br />
Why Django Sucks<br />
Presenter: KENNETH REITZ<br />
Track: I<br />
Description:<br />
This talk dives into <strong>the</strong> specifics of why Django isn’t always <strong>the</strong> best tool for <strong>the</strong> job, general frustrations<br />
with <strong>the</strong> framework, <strong>and</strong> potential fixes. It will balance out with many Django praises too, of course.<br />
Django Benefits<br />
• Makes modular decisions for you<br />
• Makes security decisions for you<br />
• Excellent <strong>Docs</strong><br />
• Installable 3rd party apps<br />
• Community resources<br />
Django Apps<br />
• Tools<br />
• WEb Process<br />
• Worker Processes<br />
Single Codebase is Great<br />
• Benefits of <strong>the</strong> whole stack<br />
• Architecutre<br />
• DRY<br />
• Only deploy once<br />
3.3. Django Con US 2012 111
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Single Codebases are evil<br />
• Tightly coupled<br />
• Broad knowledge is required<br />
• Tech debt is high<br />
• Must deploy everything at once<br />
Constraints are Good<br />
• Editors vs IDE<br />
• Mac OS X vs Desktop Linux<br />
• Pen <strong>and</strong> Paper vs Digital <strong>Notes</strong><br />
• Monolithic apps<br />
Seperated Services<br />
• API vs Front End<br />
• Build for Services<br />
• Decouple front end from backend?<br />
Django not for API services<br />
Django as API Consumer<br />
• Database is h<strong>and</strong>led by API<br />
• Makes modular decisions for you<br />
Flask<br />
• Simple HTTP<br />
• WSGI App Framework<br />
• Jinja2 Template<br />
• Lots of docs<br />
• Very simple<br />
• Bring your own batteries<br />
• No ORM for form validation<br />
• Greater flexibility<br />
• Configuration is simple<br />
112 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
3.3.3 Thursday<br />
Under <strong>the</strong> Microscope: Evaluating Existing Django Code<br />
Presenter: JOE JASINSKI<br />
Track: I<br />
Description:<br />
As a Web development firm that specializes in Django, we receive many inquiries from organizations<br />
looking for assistance with <strong>the</strong>ir existing Django websites. This session will describe our process for<br />
evaluating existing codebases <strong>and</strong> deployment structures. The goal is to provide a framework for evaluating<br />
o<strong>the</strong>r people’s code <strong>and</strong> underst<strong>and</strong> <strong>the</strong> scrutiny your code may someday endure.<br />
Django Consulting<br />
• Clients call when <strong>the</strong>y have staff that cannot h<strong>and</strong>le load<br />
• Clients have developers that leave on <strong>the</strong>m<br />
When clients call<br />
• Wide array of scenarios<br />
• Caller often has no technical knowledge<br />
• Is developer accessible<br />
Get Access to <strong>the</strong> Site<br />
Code Review<br />
• St<strong>and</strong>ard questions<br />
• Document<br />
• Enables comparison<br />
• Find code<br />
• find manage py<br />
• Lookup urls.py<br />
• Checklist<br />
Questions<br />
• What webserver<br />
• What django version<br />
• Check settings<br />
• Using logging<br />
• Do a pip freeze to see what packages are being used<br />
3.3. Django Con US 2012 113
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
• What type of version control is being used if any.<br />
• Tests<br />
• South?<br />
• Virtualenv?<br />
• Do <strong>the</strong>y have a README<br />
• Document things you find.<br />
• Keep an open mind<br />
• Research <strong>the</strong> client<br />
Additional<br />
• Assume your code will last forever<br />
• Code like django core team is reviewing it<br />
• Resist pull for speed from your boss<br />
• Excercise your right to say no.<br />
• Take time to be great. Bad coders hurt good ones.<br />
• It’s your reputation<br />
Accelerating <strong>and</strong> Enhancing Django with Redis<br />
Presenter: JOSHUA “JAG” GINSBERG<br />
Track: II<br />
Description:<br />
This tutorial introduces Redis, an in-memory key-object NoSQL datastore. We discuss out-of-<strong>the</strong>-box<br />
ways Redis can help improve <strong>the</strong> performance of your Django deployments, ways that using Redis instead<br />
of SQL for some data management can accelerate your apps, <strong>and</strong> more advanced <strong>and</strong> unconventional uses<br />
for Redis to solve real-time <strong>and</strong> big-data problems.<br />
What is Redis<br />
• Absurdly Fast<br />
• All in memory<br />
• Keys <strong>and</strong> objects<br />
• lists, strings, sets<br />
What isn’t redis<br />
• Not NoSQL<br />
• data structures limited <strong>and</strong> not nestable<br />
• No views<br />
114 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
• Not a simple key value store<br />
• Not memcached<br />
Crash Course<br />
• Get <strong>and</strong> Set right away<br />
• Doesn’t care about char encoding<br />
• Linked lists<br />
• Sets<br />
• Scores, floating point values<br />
• Dictionary keys not ordered<br />
Boring<br />
• Basically a cache<br />
• Clearing house<br />
Case Study<br />
• Run hundreds of ads on Facebook <strong>and</strong> snapshot <strong>the</strong>ir performance as fast as possible.<br />
• Facebook API does not update stats in real time<br />
• Ga<strong>the</strong>r stats <strong>and</strong> store as a hash map<br />
Drop In<br />
• Celery<br />
• Cache for Django<br />
• Use Redis for celery instead of RabbitMQ<br />
Give SQL A break<br />
• Counting<br />
Good Ideas<br />
• Use hierarchy<br />
• Atomic transactions<br />
• Different keyspaces for difference apps<br />
• Do not store large values in Redis<br />
• Do not count on persistence<br />
• Don’t forget that operations are Atomic<br />
3.3. Django Con US 2012 115
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
LUA - Lightweight Embeddable Scripting<br />
• Construct <strong>and</strong> deconstruct JSON<br />
Redis Hate<br />
• Non persistence<br />
• Need to hire a Sys Admin<br />
• Needs to fit in Memory<br />
• Redis does not return memory to system<br />
• Redis on dedicated hardware with lots of RAM<br />
• Single process, single CPU<br />
Django Core Team<br />
Presenter: Djanog Core<br />
Track: I<br />
Django Core<br />
What is a potential plan or way forward for Django to move forward in Real Time<br />
• Not confident about time (1 or 10 years)<br />
• Web is going toward “Thick Clients” (Phone Apps)<br />
• Adapt or Die<br />
• Django must move forward but not sure about timeline<br />
What is happening on <strong>the</strong> Schema change API<br />
• South is <strong>the</strong> defacto solution for migrations<br />
• Adding south abstractions in to 1.5<br />
• Time to start rolling migrations into Django<br />
Python 3 - Strategies <strong>and</strong> Tips for Migration<br />
• Not hard<br />
• Django has documented how <strong>the</strong>y approached <strong>the</strong> change<br />
• Confident that 3rd party apps will be able to convert it easily.<br />
New Areas of Interest for new dev<br />
• Real time<br />
• Performance<br />
• 2.0 game plan<br />
116 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
How do you break contrib out <strong>and</strong> still maintain <strong>the</strong>m (namespaces)<br />
• Support for better namespacing in Python 3.3<br />
• In practice cannot use name spaced packages<br />
What would be <strong>the</strong> thing that you think you could actually change in 2.0<br />
• Everything is a view.<br />
ORM is agnositc, should it be broken to allow performance improvements in Postgres<br />
• There should be more support for performance improvements in certain DB Backends<br />
• 1.5 1.6 might have some improvements<br />
Admin Radical restart?<br />
• Backend could serve an API <strong>and</strong> allow clients to provide better admin functionality<br />
• Very challenging project<br />
• Very large task<br />
• A lot of <strong>the</strong> admin does not use django tools that exist now<br />
• Admin does not use Class based views<br />
Will a team approach to design help django?<br />
• Designers work best not solo<br />
• Motivate each o<strong>the</strong>r<br />
• Unified vision<br />
Models <strong>and</strong> Migrations <strong>and</strong> Schemas - oh my!<br />
Presenter: ANDREW GODWIN<br />
Track: I<br />
Description:<br />
A look at <strong>the</strong> past, current <strong>and</strong> future of schemas, migrations <strong>and</strong> Django, <strong>and</strong> what it means for both<br />
website developers <strong>and</strong> ops staff.<br />
Past<br />
• Databases hate schema changes<br />
• Locks whole tables<br />
• Hammer I/O<br />
• Inconsistent<br />
• Django-evolution<br />
• dmigrations<br />
3.3. Django Con US 2012 117
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
• South 0.1 2008<br />
• 0.2 - MySQL<br />
• 0.3 - Dependencies<br />
• 0.4 - Alter columns<br />
• 0.5 - ORM Freezing<br />
• 0.6 - Field introspection<br />
• 0.7 - data/schema split, missing defaults for Not null, custom fields ignored.<br />
Things to Change<br />
• No rebase/collapse<br />
• Opaque migrations (Impossible to peek inside migrations)<br />
Databases<br />
• Code/schemas split<br />
• Database isn’t going to use Git<br />
• Extra fields are fine<br />
• Missing fields are not<br />
• Painful/slow to sync<br />
The Future<br />
• django.db.backends.schema<br />
• Database abstraction layer<br />
• contrib.migrations<br />
• Migration creation/running, will replace South for <strong>the</strong>se operations.<br />
• No frozen ORM<br />
• Raw SQL support<br />
• SQL Output support<br />
South 1.0<br />
• Python 3 support with Django 1.5<br />
• Python 2.6 required<br />
118 Chapter 3. <strong>Conference</strong>s
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Django Nose<br />
Presenter: ERIK ROSE<br />
Track: II<br />
Description:<br />
Django’s testrunner gets you started quickly, but you soon hit your head on its limitations as your project<br />
grows. By trading it for nose, a testing framework popular in <strong>the</strong> wider Python community, we can reduce<br />
boilerplate, boost performance, <strong>and</strong> improve testing UI, with only a few lines of setting changes. Re-use<br />
your test DBs, integrate with Jenkins, split your suite into pieces, <strong>and</strong> more.<br />
Django Tests Pain<br />
• Crowded<br />
• Slow<br />
• Overbroad<br />
• Rough<br />
• Extensible but not scalably so<br />
Installation<br />
• pip install django-nose<br />
• django_nose<br />
• django_nose.NoseTestSuiteRunner<br />
Discovery<br />
• Find test by reg ex<br />
• @istest<br />
• Subclasses of TestCase<br />
• No more accidental shadowing<br />
• No more forgotten imports<br />
Functions as tests<br />
• Package level setup <strong>and</strong> tear down<br />
Test Generators<br />
• cannot use in TestCase subclass<br />
3.3. Django Con US 2012 119
<strong>Conference</strong> <strong>Notes</strong> <strong>and</strong> <strong>Best</strong> <strong>Practices</strong>, <strong>Release</strong> <strong>1.3</strong><br />
Test Attributes<br />
• attribute plugin<br />
• @attr(‘selenium’)<br />
• manage.py test - a selenium<br />
Goodies<br />
• Custom error classes<br />
• Extensible<br />
• Plugins<br />
Speed<br />
• Switching contexts<br />
• Encourages running tests<br />
• No more test fixtures!<br />
120 Chapter 3. <strong>Conference</strong>s