django/python framework

Post on 01-Apr-2015

1.090 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

DESCRIPTION

My presentation slides during PHP Meetup 2011 (Framework Shootout) at MIMOS 19/02/2011. However it was about Django/Python framework. An intro maybe enough as introduction for PHP geeks down here.

TRANSCRIPT

Python Meet-Up 2011Framework Shoot Out

Adzmely Mansor (doubt)adzmely@gmail.com

XPHPThe framework for perfectionists with deadlines.

Introductory

FAQ - about mefrequently answered questions

• no I’m not “ustaz”

• yes, I’m half chinese

• yes, I’m “OLD” :P

• so please don’t use “sms” short text in forum

Let s Shoot

Django History

• Named after “famous” guitarist “Django Reindhart”

• Developed by Adrian Holovaty & Jacob Kaplan-Moss

• Open sourced in 2005

• 1.0 version released Sept. 3 2008

• now 1.2.5

What is DJango?

• open source web application framework

• written in python

• nope ! it is not a “MVC” framework

• rather a “MTV” framework

• lets you divide code modules into logical groups to make it flexible

Quick Overview

Starting a Projectshell> django-admin.py startproject slashdotmyshell> cd slashdotmyshell> ls __init__.py manage.py settings.py urls.py

shell> python manage.py startapp vdoblogshell> cd vdoblogshell> ls__init__.py models.py tests.py views.py

shell> python manage.py runserverValidating models...0 errors found

Django version 1.2.5, using settings 'slashdotmy.settings'Development server is running at http://127.0.0.1:8000/Quit the server with CONTROL-C.

• start a project• configure settings• create an app• run dev server• start coding

Starting a Project

http://localhost:8000

a “Project” in Django

“A project is a collection of applications,

using the same settings file”

Application in Django

“An application tries to provide a single,

relatively self-contained

set of related functions”

a blog Project

• blog - project

• blog post - application

• comments - application

• ... etc ...

a groupware Project

• groupware - project

• blog - application

• calendar - application

• file manager - application

• etc

Django Architecture

MVT Architecture

• Models : describes your data structure/database schema

• Views : controls what users sees

• Templates : how a user sees it

• Controller : url dispatcher

Architecture Diagram Browser

URL dispatcherTemplate

Database

View

Model

what users

seeshow user

s sees

controlle

r

Architecture Diagram

Browser

URL dispatcherTemplate

Database

View

Model

http://vdo.slash.my

Architecture Diagram

Browser

URL dispatcherTemplate

Database

View

Model

urls.py

urlpatterns = patterns( (r'^login', 'slashdotmy.auth.views.login'), (r'^logout', 'slashdotmy.auth.views.signout'), (r'^blog/', include ('slashdotmy.vdoblog.urls')), (r'', include ('slashdotmy.portal.urls')),)

# slashdotmy/portal/urls.pyurlpatterns = patterns( ... (r'^$', 'views.index'), ...)

Architecture Diagram ~/slashdotmy/portal/views.py

Browser

URL dispatcherTemplate

Database

View

Model

Architecture Diagram ~/slashdotmy/portal/views.py

def index(request): ... publishedList = Published.objects.order_by('-pub_date')[:5] template_context = {'users': users, 'publist': publishedList} return render_to_response('portal/index.html', template_context)

urlpatterns = patterns( ... (r'^$', 'views.index'),)

URL dispatcher

View

what users

sees

controlle

r

Django :: Model

Browser

URL dispatcherTemplate

Database

View

Model

~/slashdotmy/vdoblog/models.pyfrom django.contrib.auth.models import User

class Published(models.Model): vdo_id = models.CharField(max_length=25) title = models.CharField(max_length=70) descriptions = models.CharField(max_length=200) pub_date = models.DateTimeField(auto_now_add=True) user_id = models.ForeignKey(User) fb_id = models.CharField(max_length=50) num_views = models.IntegerField(default=0)

#email = models.EmailField(max_length=50)

Using model in “View”in view/controller

from django.contrib.auth.models import Userfrom slashdotmy.vdoblog.models import Published, PublishedForm

def index(request): users = auth_models.User.objects.filter(is_staff=0).order_by('-last_login')[:25] publishedList = Published.objects.order_by('-pub_date')[:4] template_context = {'settings': settings, 'users': users, 'publist': publishedList} return render_to_response('portal/index.html', template_context, context_instance=RequestContext(request))

select * from auth_user where is_staff=0

order by last_login desc limit 25

Templatein template

<div id="washere"> <div id="sources"> <div class="blocktitle"> Who were here, recently? </div>

<div class="blocklist"> <div class="listinner"> {% for fbuser in users %} <img src="http://graph.facebook.com/{{ fbuser.username|escape }}/picture/?type=small" /> {% endfor %} </div> </div> </div></div>

xss prev

ention

Working with FormsDjango NewForms

(form handling library)

Working With Forms

• With django NewForms library

• display an html form with automatically generated widget

Working With Formsfrom django.forms import ModelForm, Textarea, HiddenInput, TextInput

class PublishedForm(ModelForm): class Meta: model = Published exclude = ('pub_date', 'num_views', 'vdo_id') widgets = { 'user_id': HiddenInput(), 'fb_id': HiddenInput(), 'descriptions': Textarea(attrs={'cols': 50, 'rows': 6, 'class':'areatext'}), 'title': TextInput(attrs={'size': 60, 'class':'inputext'}), }

Working With Formsshell> python manage.py shell

Python 2.6.4 (r264:75706, Dec 7 2009, 18:43:55) [GCC 4.4.1] on linux2Type "help", "copyright", "credits" or "license" for more information.(InteractiveConsole)

>>> from vdoblog.models import PublishedForm >>> f = PublishedForm()

>>> f.as_p()

u'<p><label for="id_title">Title:</label> <input name="title" maxlength="70" id="id_title" type="text" class="inputext" size="60" /></p>\n<p><label for="id_descriptions"> Descriptions:</label> <textarea id="id_descriptions" rows="6" cols="50" name="descriptions" class="areatext"></textarea><input type="hidden" name="user_id" id="id_user_id" /><input type="hidden" name="fb_id" id="id_fb_id" /></p>'

>>>

Working With Forms

• With django NewForms library

• display an html form with automatically generated widget

• .as_p - paragraph

• .as_table - tables based

• .as_ul - list items

Working With Forms

<form action="/contact/" method="post">{% csrf_token %}{{ form.as_p }}<input type="submit" value="Submit" /></form>

In templates

cross site request forgery pro

tection

cookie forging protection

session fixation

For example, PHP allows session identifiers to be passed in the URL (i.e.http://example.com/?PHPSESSID=fa90197ca25f6ab40bb1374c510d7a32). An attacker who tricks a user into clicking on a link with a hardcoded session ID will cause the user to pick up that session.

Working With Forms

• With django NewForms library

• check submitted data against validation rules

• email / int / ip address / etc

• redisplay a form in the case of validation errors

• finally convert form data to python data types

Customizing Django Authentication & Authorization

Django :: Authentication

• part of loadable application

• provides:

• user accounts & groups

• permissions

• cookie-based user session

• admin page

Django :: Authentication

# ~/slashdotmy/settings.py

INSTALLED_APPS = ( 'django.contrib.contenttypes', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.sites', 'slashdotmy.auth', 'slashdotmy.vdoblog',)

Demo:: Authentication

• Django allow plugin of other/customize authentication sources

• can custom default user db schema

• tandem with other system

• for demo app - facebook auth

• without customizing core

• easily hooked

Custom Authentication

• custom plugin

• require only two methods

• authenticate()

• get_user()AUTHENTICATION_BACKENDS = ( 'auth.backends.FacebookBackend',)

# ~/slashdotmy/auth/backends.py

class FacebookBackend:

def authenticate(self, token=None): ....

def get_user(self, user_id): ....

Custom Authentication

• controller/views

• use internal django auth system

• login_required

• auto session

# ~/slashdotmy/vdoblog/views.py

from django.contrib.auth.decorators import login_required

@login_requireddef pubStream(request): if not request.method == "POST": return HttpResponseRedirect("/") vdoId = UniqueId() ... ...

Custom Authentication

• template

• just code the logic

• everything provided by the auth context

# ~/slashdotmy/templates/base/header.html

{% if user.username %}

<a href=”/signout”> Logout

</a>

{% else %}

<a href=”.....”>Login

</a>

{% endif %}

Template Tags & Filters

Template Tags & Filters

Customize Filters

<div class="item"> by {{ published.user_id.first_name }} {{ published.user_id.last_name }} <div class="itemdate"> {% load customFilters %} {{ published.pub_date|humanizeTimeDiff }} ago </div></div>

Django Admina bonus

Django Admin

Django Admin

Django Admin

Django Admin : Custom Layout

from django.contrib import adminfrom slashdotmy.vdoblog.models import Published

class PublishedAdmin(admin.ModelAdmin): list_display = ['fb_userid', 'title', 'pub_date', 'vdo_id']

admin.site.register(Published, PublishedAdmin)

from django.contrib import adminfrom slashdotmy.vdoblog.models import Published

class Published(models.Model): .... def fb_userid(self): return "<img src='http://graph.facebook.com/%s/picture/?type=small'>" % (self.user_id)

Django Admin : Custom

“Real Application Development”

“Real Application Development”

Forms

Multi UserUser Management

Validation

Security

XSSSQL Injection

Social Integration

Directo

ry Traversal

Advance

Features

ORM?

Template Filters

Lazy query

Speed

Caching Engine

Multi DBByte

Code Cac

he

Auth

Session

Rapid

Development

Unit TestTemplate

Engine

Designer

Pushy PM

Undecided

Customer

Perfect

Designer

MC

Deadline

Team ofZombies

Wizard

New L

ayout

Access Control

MonkeyPatches

image source :: http://thefuturistiswriting.blogspot.com/2010/07/some-dont-like-it-hot.html

Why Framework?

• unified coding

• MVC

• readable

• maintainable

• organized structure

• “no monkey patching”

Why Framework?

• rapid development

• ready made reusable/common modules

• authentication / user management / ACL

• session management

• cache system

• ORM - relational mapper

• security, etc

But sometimes..

• it doesn’t fit anymore

• different

• environment

• customer

• requirements

• need additional flow/fields/features/filters or some level of customizations

What I don’t want

• don’t want to be trapped in a rigid framework, no possibilities of extending

• modification of core = branching = bad

What I want!

• a framework that provide dozens of features, integrated modules, automation, integrated security, etc

• but not limited to

• possibilities of extending/customization

• change the existing integrated modules process flow

• want to be free, “no string attached”

“The framework for perfectionists with

deadlines”http://www.djangoproject.com

http://www.django-cms.orghttp://www.python.org.my

“with PHP you know people learned that because they want get jobs, with JAVA they learned that

because they take computer science courses, with Python you learned because you love it, because

you want to experience the beauty, I'm sure it's the same way with ruby...

”: - Adrian Holovaty (Django)

Thank YouQ&Ahttp://vdo.slash.my

(demo app used in this presentation)

http://blog.xjutsu.comhttp://scribd.com/adzmely

adzmely@gmail.comYahoo IM : adzmely

top related