Вы находитесь на странице: 1из 57

The framework for perfectionists with deadlines.

P H P
Python Meet-Up 2011
X
Framework Shoot Out
Adzmely Mansor (doubt)
adzmely@gmail.com
Introductory
FAQ - about me
frequently 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 Project
shell> django-admin.py startproject slashdotmy
shell> cd slashdotmy
shell> ls
__init__.py
manage.py
settings.py
urls.py
• start a project
shell> python manage.py startapp vdoblog
shell> cd vdoblog • configure settings
shell> ls
__init__.py
models.py
tests.py views.py • create an app
shell> python manage.py runserver • run dev server
• start coding
Validating 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.
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

ee s r
rs s lle
u se Template URL dispatcher nt ro
how co

s ees
s ers
View at u
wh

Model

Database
Architecture Diagram
http://vdo.slash.my
Browser

Template URL dispatcher

View

Model

Database
Architecture Diagram
urls.py
Browser

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

Model
# slashdotmy/portal/urls.py
urlpatterns = patterns(
... Database
(r'^$', 'views.index'),
...
)
Architecture Diagram
~/slashdotmy/portal/views.py
Browser

Template URL dispatcher

View

Model

Database
Architecture Diagram
~/slashdotmy/portal/views.py
urlpatterns = patterns(
...
(r'^$', 'views.index'), URL dispatcher
) ller
o
co ntr

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

ee s
rs s
u s e
t
wha
Django :: Model
~/slashdotmy/vdoblog/models.py
from django.contrib.auth.models import User Browser

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

#email = models.EmailField(max_length=50)
Database
Using model in “View”
in view/controller
from django.contrib.auth.models import User
from 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))

h e re i s _ s taff=0
ro m au t h_user w
select * f d e s c l i m i t 25
r by la s t _ log in
o r de
Template
in 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 %}
t i on
</div> ven
pre
</div> xs s
</div>
</div>
Working with Forms
Django NewForms
(form handling library)
Working With Forms
• With django NewForms library
• display an html form with automatically
generated widget
Working With Forms
from 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 Forms
shell> python manage.py shell

Python 2.6.4 (r264:75706, Dec 7 2009, 18:43:55)


[GCC 4.4.1] on linux2
Type "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
In templates
<form action="/contact/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>

g e r y protection
s i te req u es t for
cross p ro tection
g i ng
co okie for
ation
session fix

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 # ~/slashdotmy/auth/backends.py

class FacebookBackend:

• require only def authenticate(self, token=None):


....
two methods
• authenticate()
def get_user(self, user_id):
....

• get_user() AUTHENTICATION_BACKENDS = (
'auth.backends.FacebookBackend',
)
Custom Authentication
• controller/views
• use internal # ~/slashdotmy/vdoblog/views.py

django auth from django.contrib.auth.decorators import login_required

system @login_required
def pubStream(request):
if not request.method == "POST":

• login_required return HttpResponseRedirect("/")


vdoId = UniqueId()
...

• auto session ...


Custom Authentication
• template # ~/slashdotmy/templates/base/header.html

• just code the {% if user.username %}

<a href=”/signout”>
logic Logout
</a>

• everything {% else %}

provided by <a href=”.....”>


Login
the auth </a>

context {% 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 Admin
a bonus
Django Admin
Django Admin
Django Admin
Django Admin : Custom
Layout
from django.contrib import admin
from 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 admin


from 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”
h e y
uer
ac Lazy q
rity sal a rd
Session u
C
Speed o de ORM? Sec ve
r iz
C
nt Tr
a W
yt
e Mu e r y SQ XSS
B
a n ce lti
ge m c to Fo L Injec
Ad v DB
n a Di re
rm t i on
t u r es a s
Fea M
ers ser er Soc Valid
Cachin
g Engi
ne
Filt U s ial
In t ation
te U
iA Auth eg r
pl
a
u l t cce atio
n
Te
m M ss C
on t Un
late rol
T emp it T

“Real Application
Engin
e est
De
si gne
r

Development” De
e r ut ad
i
Des C
g n
La
y o
lin
ew
e
M id
N
Rap ent Push
lop m y PM
e d
e ve
i
ec mer
d D
d
Un usto r f e ct
C T eam P e Monkey
Zom of
bies Patches
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.org
http://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 You
Q&A
http://vdo.slash.my
(demo app used in this presentation)

http://blog.xjutsu.com
http://scribd.com/adzmely
adzmely@gmail.com
Yahoo IM : adzmely

Вам также может понравиться