Diese Präsentation wurde erfolgreich gemeldet.
Wir verwenden Ihre LinkedIn Profilangaben und Informationen zu Ihren Aktivitäten, um Anzeigen zu personalisieren und Ihnen relevantere Inhalte anzuzeigen. Sie können Ihre Anzeigeneinstellungen jederzeit ändern.
Rajan K Upadhyay 
1
Programming Languages 
Popular 
Programming Languages > 500 
Frameworks > 90000 
at least what Wikipedia says 
What Really...
Lets go back & check last software you developed 
• Without Alternatives, how difficult it was to estimate ? 
• Ideas -> C...
Time is an essence 
Python : Django A complete framework 
A Web Framework that shortens the Time it takes to develop 
soft...
Python: Language of Best 
• By The organizations attracting the best Programmers 
in the world 
Google, NASA, MIT 
5
• “The framework for perfectionists 
with deadlines” 
• Model-Template-View ( MTV ) not as 
complex as MVC 
• Flexible tem...
Scalability 
• Django runs on regular web servers, such as 
Apache, Lighty or Nginx, using a built-in Python 
or WSGI adap...
IT Acceptance 
• IT environments today are mostly familiar with 
Java 
• Solution: use Jython that compiles Python to 
byt...
DJANGO: 
QUICK OVERVIEW 
9
Project File Structure 
django-admin.py startproject 
<PROJECT_ROOT> 
manage.py 
<PROJECT_DIR> 
__init__.py 
settings.py 
...
settings.py 
• Defines settings used by a Django application 
• Referenced by wsgi.py to bootstrap the project 
loading 
•...
Sample Settings… 
DEBUG = True 
TEMPLATE_DEBUG = True 
ALLOWED_HOSTS = [] 
# Application definition 
INSTALLED_APPS = ( 
'...
Django Apps 
• Reusable modules 
• django-admin.py startapp <app_name> 
• Creates stub layout: 
<APP_ROOT> 
admin.py 
mode...
Django Models 
• Defined in models.py 
• Typically inherit from django.db.models.Model 
Example Model: 
from django.db imp...
Models (cont’d) 
• Default is to set NOT NULL on all fields. Override by 
adding null = True to field definition: 
name = ...
Models (cont’) 
• Need Nulls in a Boolean Field? Use 
models.NullBooleanField() 
• Set Default value with “default”: 
coun...
Model Methods 
• model.save(self, *args, **kwargs) 
• model.delete(self, *args, **kwargs) 
• model.get_absolute_url(self) ...
Activating a Model 
• Add the app to INSTALLED_APPS in settings.py 
• Run manage.py validate 
• Run manage.py syncdb 
• Mi...
Selecting Objects 
• Models include a default manager called objects 
• Manager methods allow selecting all or some 
insta...
Introspecting Legacy 
Models 
• manage.py inspectdb 
• Cut and paste generated code into models.py – 
Easy!! 
20
Full Sample 
from django.db import models 
from datetime import datetime 
class TimestampedModel(models.Model): 
created_d...
Full Sample (cont’d) 
class Question(TimestampedModel): 
question_text = models.CharField(max_length = 200) 
def __str__(s...
Function vs. Class Views 
• Django allows two styles of views – functions or class 
based views 
• Functions – take a requ...
Sample – Viewing a List 
of Questions 
• Function based: 
from .models import Question 
from django.shortcuts import rende...
Quick CRUD Operations 
with Generic Views 
• ListView 
• UpdateView 
• CreateView 
• If Model is specified, automagically ...
Sample – As Class Based 
View 
from .models import Question 
from django.views.generic import ListView 
class QuestionList...
Django Templates 
• Very simple syntax: 
variables = {{variable_name}} 
template tags = {%tag%} 
• Flexible – can be used ...
Question List Template 
<!doctype html> 
<html lang=en> 
<head> 
<meta charset=utf-8> 
<title>List of Questions</title> 
<...
urls.py 
• Defines routes to send urls to various views 
• Can use regular expressions 
• Extract parameters from a url an...
Forms in Django 
• django.forms provides a class to build HTML forms 
and validation. Example: 
from django import forms 
...
ModelForms 
• Automatically generate a form from a model. 
• Handles saving a bound model 
• Can specify fields to be incl...
Using a ModelForm 
• Create an instance of an empty form: 
form = QuestionForm() 
• Create a form to update an existing in...
Request & Response 
• Request object encapsulate the request and provide 
access to a number of attributes and methods for...
Django Extras 
• CRSF Middleware – enabled by default. Include 
template tag in all forms: 
{%csrf_token%} 
• Authenticati...
Auth Decorators 
• Live in django.contrib.auth.decorators 
• login_required 
@login_required 
def function_view(request): ...
Demo: 30 mins 
Let’s develop an Release Tracking system 
o Create Business Data Model 
o Database CRUD Operations to manag...
Step1: Settings: Connect to 
Database 
• DATABASES = { 
• 'default': { 
• 'ENGINE': 'django.db.backends.mysql', # Add 'pos...
Step2: Data Model 
from django.db import models 
class Environment(models.Model): 
environment = models.CharField(null=Fal...
Step3: Sync DB 
django_manage.py syncdb 
Whoooo ---- Your DB tables are created 
What Next  Lets create some Interfaces 
...
Register Admin 
from django.db import models 
from django.contrib import admin 
class Environment(models.Model): 
environm...
Admin Interface Ready 
• Run  manage.py runserver 8000 
http://127.0.0.1:8000/admin/ 
- Entire CRUD Operation for 
Models...
Views: Front End 
• Setup a URL pattern : Edit url.py 
url(r'^$', 'ReleaseTracker.views.home', name='home'), 
. Create vie...
Create Template 
Create home.html in templates 
<!DOCTYPE html> 
<html> 
<head> 
<title></title> 
</head> 
<body> 
{# you ...
FRONT END 
• Open http://127.0.0.1:8000/ 
You will be able to see the model data 
44
Nächste SlideShare
Wird geladen in …5
×

Tango with django

825 Aufrufe

Veröffentlicht am

A Web Framework that shortens the Time it takes to develop software in at least an Order of Magnitude. while also tremendously minimizing Effort Pain, Time waste, Complexity, Cost of change & more

Veröffentlicht in: Technologie
  • Als Erste(r) kommentieren

  • Gehören Sie zu den Ersten, denen das gefällt!

Tango with django

  1. 1. Rajan K Upadhyay 1
  2. 2. Programming Languages Popular Programming Languages > 500 Frameworks > 90000 at least what Wikipedia says What Really I should Learn ? 2
  3. 3. Lets go back & check last software you developed • Without Alternatives, how difficult it was to estimate ? • Ideas -> Conceptualization -> Enterprise Ready was full of Effort, Pain, Time waste, Complexity & Change !!! • Was my system adaptive to the change that business demand? … God it was really nightmare to maintain the code …. • What is the time it took to get the customer from a frustrated to a happy customer ? also the time it took to develop version 2, with different requirements & scale: 3
  4. 4. Time is an essence Python : Django A complete framework A Web Framework that shortens the Time it takes to develop software in at least an Order of Magnitude. while also tremendously minimizing Effort Pain, Time waste, Complexity, Cost of change & more 9/1/2014 4
  5. 5. Python: Language of Best • By The organizations attracting the best Programmers in the world Google, NASA, MIT 5
  6. 6. • “The framework for perfectionists with deadlines” • Model-Template-View ( MTV ) not as complex as MVC • Flexible template language that can be used to generate HTML, CSV, Email or any other format • Includes ORM that supports many databases – Postgresql, MySQL, Oracle, SQLite • Lots of extras included – middleware, csrf protections, sessions, caching, authentication • Written in C – high performance, ability to link to C libraries for extensions • Interpreted script language compiled on the fly into byte code • Easier to read coding standards – whitespace sensitive • Object Oriented WHY 6
  7. 7. Scalability • Django runs on regular web servers, such as Apache, Lighty or Nginx, using a built-in Python or WSGI adapter • This makes it very lightweight & scalable, as any LAMP deployment o There are examples of sites that handle MM reqs/hour, using less than 10 servers 7
  8. 8. IT Acceptance • IT environments today are mostly familiar with Java • Solution: use Jython that compiles Python to bytecode o Package a Django project as .war o Sun constantly improves Jython & maintains compatibility /w Django 8
  9. 9. DJANGO: QUICK OVERVIEW 9
  10. 10. Project File Structure django-admin.py startproject <PROJECT_ROOT> manage.py <PROJECT_DIR> __init__.py settings.py urls.py wsgi.py 10
  11. 11. settings.py • Defines settings used by a Django application • Referenced by wsgi.py to bootstrap the project loading • Techniques for managing dev vs prod settings: o Create settings-dev.py and settings-prod.py and use symlink to link settings.py to the correct settings o Factor out common settings into base-settings.py and import. Use conditionals to load correct settings based on DEBUG or other setting 11
  12. 12. Sample Settings… DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) 12
  13. 13. Django Apps • Reusable modules • django-admin.py startapp <app_name> • Creates stub layout: <APP_ROOT> admin.py models.py templates (directory) tests.py views.py urls.py 13
  14. 14. Django Models • Defined in models.py • Typically inherit from django.db.models.Model Example Model: from django.db import models class TestModel(models.Model): name = models.CharField(max_length = 20) age = models.IntegerField() 14
  15. 15. Models (cont’d) • Default is to set NOT NULL on all fields. Override by adding null = True to field definition: name = models.CharField(max_length=20, null = True) • Relationships defined through special field types: models.OneToOneField(model) models.ForeignKey(model) models.ManyToManyField(model) 15
  16. 16. Models (cont’) • Need Nulls in a Boolean Field? Use models.NullBooleanField() • Set Default value with “default”: count = models.IntegerField(default = 0) • Use a inner Meta class to define additional options, especially useful for abstract classes: class TestModel(models.Model): class Meta: abstract = True 16
  17. 17. Model Methods • model.save(self, *args, **kwargs) • model.delete(self, *args, **kwargs) • model.get_absolute_url(self) • model.__str__(self) [Python 3] model.__unicode__(self) [Python 2] • Override with super(MODEL, self).save(*args, **kwargs) 17
  18. 18. Activating a Model • Add the app to INSTALLED_APPS in settings.py • Run manage.py validate • Run manage.py syncdb • Migrations o Write custom script or manually handle migrations o Use South 18
  19. 19. Selecting Objects • Models include a default manager called objects • Manager methods allow selecting all or some instances Question.objects.all() Question.objects.get(pk = 1) Use try block, throws DoesNotExist exception if no match Question.objects.filter(created_date__lt = ‘2014- 01-01’) • Returns QuerySet 19
  20. 20. Introspecting Legacy Models • manage.py inspectdb • Cut and paste generated code into models.py – Easy!! 20
  21. 21. Full Sample from django.db import models from datetime import datetime class TimestampedModel(models.Model): created_datetime = models.DateTimeField() updated_datetime = models.DateTimeField() def save(self, *args, **kwargs): if self.id is None: self.created_datetime = datetime.now() updated_datetime = datetime.now() super(TimestampedModel,self).save(*args, **kwargs) class Meta: abstract = True 21
  22. 22. Full Sample (cont’d) class Question(TimestampedModel): question_text = models.CharField(max_length = 200) def __str__(self): return self.question_text 22
  23. 23. Function vs. Class Views • Django allows two styles of views – functions or class based views • Functions – take a request object as the first parameter and must return a response object • Class based views – allow CRUD operations with minimal code. Can inherit from multiple generic view classes (i.e. Mixins) 23
  24. 24. Sample – Viewing a List of Questions • Function based: from .models import Question from django.shortcuts import render_to_response def question_list(request): questions = Question.objects.all() return render_to_response(‘question_list.html’, { ‘questions’:questions}) 24
  25. 25. Quick CRUD Operations with Generic Views • ListView • UpdateView • CreateView • If Model is specified, automagically creates a matching ModelForm • Form will save the Model if data passes validation • Override form_valid() method to provide custom logic (i.e sending email or setting additional fields) 25
  26. 26. Sample – As Class Based View from .models import Question from django.views.generic import ListView class QuestionList(ListView): model = Question context_object_name = ‘questions’ 26
  27. 27. Django Templates • Very simple syntax: variables = {{variable_name}} template tags = {%tag%} • Flexible – can be used to render html, text, csv, email, you name it! • Dot notation – template engine attempts to resolve by looking for matching attributes, hashes and methods 27
  28. 28. Question List Template <!doctype html> <html lang=en> <head> <meta charset=utf-8> <title>List of Questions</title> </head> <body> {%if questions%} <ul> {%for q in questions%} <li>{{q.question_text}}</li> {%endfor%} </ul> {%else%} <p>No questions have been defined</p> {%endif%} </body> </html> 28
  29. 29. urls.py • Defines routes to send urls to various views • Can use regular expressions • Extract parameters from a url and pass to the view as a named parameter: r(‘^question/(?P<question_id>d+)/$’,’views.question_ detail’) • Extensible – urls.py can include additional url files from apps: r(‘^question/’,include(question.urls)) 29
  30. 30. Forms in Django • django.forms provides a class to build HTML forms and validation. Example: from django import forms class EditQuestionForm(forms.Form): question_text = forms.CharField(max_length = 200) • Often redundant when creating forms that work on a single model 30
  31. 31. ModelForms • Automatically generate a form from a model. • Handles saving a bound model • Can specify fields to be included or excluded in the form • Sample: from django.forms import ModelForm from .models import Question class QuestionForm(ModelForm): class Meta: model = Question fields = [‘question_text’] 31
  32. 32. Using a ModelForm • Create an instance of an empty form: form = QuestionForm() • Create a form to update an existing instance of a model: question = Question.objects.get(pk = 1) form = QuestionForm(instance = question) • Pass the form into the template and use the form methods to render the form: form.as_p form.as_ul form.<field_name> form.<field_name>.errors 32
  33. 33. Request & Response • Request object encapsulate the request and provide access to a number of attributes and methods for accessing cookies, sessions, the logged in user object, meta data (i.e environment variables), • Response objects are returned to the browser. Can set content type, content length, response does not have to return HTML or a rendered template • Special response types allow for common functionality: HttpResponeRedirect Http404 HttpStreamingResponse 33
  34. 34. Django Extras • CRSF Middleware – enabled by default. Include template tag in all forms: {%csrf_token%} • Authentication • Caching • Sessions • Messages • Email • Logging 34
  35. 35. Auth Decorators • Live in django.contrib.auth.decorators • login_required @login_required def function_view(request): …. • user_passes_test (can be used with lambda functions for real power) – @user_passes_test(lambda u: u.is_staff) def function_view(request): … • has_perms – test for user permissions 35
  36. 36. Demo: 30 mins Let’s develop an Release Tracking system o Create Business Data Model o Database CRUD Operations to manage/add/edit/delete Releases o Rich Web UI (search, filters, last actions) o Users management (permissions, groups), User logging, Access level control o Scalable deployment (any # of users) 36
  37. 37. Step1: Settings: Connect to Database • DATABASES = { • 'default': { • 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. • 'NAME': ‘release', # Or path to database file if using sqlite3. • # The following settings are not used with sqlite3: • 'USER': 'root', • 'PASSWORD': ‘', • 'HOST': 'localhost', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. • 'PORT': '', # Set to empty string for default. • } • } 37
  38. 38. Step2: Data Model from django.db import models class Environment(models.Model): environment = models.CharField(null=False, max_length=200) # Create your models here. class Release(models.Model): dateCreated = models.DateField(null=False, auto_now_add=True) releaseDate = models.DateField(null=False) releaseTitle = models.CharField(null=False, max_length=200) releaseEnv = models.ForeignKey(Environment) 38
  39. 39. Step3: Sync DB django_manage.py syncdb Whoooo ---- Your DB tables are created What Next  Lets create some Interfaces 39
  40. 40. Register Admin from django.db import models from django.contrib import admin class Environment(models.Model): environment = models.CharField(null=False, max_length=200) # Create your models here. class Release(models.Model): dateCreated = models.DateField(null=False, auto_now_add=True) releaseDate = models.DateField(null=False) releaseTitle = models.CharField(null=False, max_length=200) releaseEnv = models.ForeignKey(Environment) admin.site.register(Release) admin.site.register(Environment) 40
  41. 41. Admin Interface Ready • Run  manage.py runserver 8000 http://127.0.0.1:8000/admin/ - Entire CRUD Operation for Models - User Authentication, Groups, Access Level & control - User Log - Multisite & Multi Application 41
  42. 42. Views: Front End • Setup a URL pattern : Edit url.py url(r'^$', 'ReleaseTracker.views.home', name='home'), . Create view as home # Create your views here. from django.http import HttpResponse from rtracker.models import Environment from rtracker.models import Release from django.shortcuts import get_object_or_404, render_to_response from django.template import RequestContext def home(request): releaseitems = Release.objects.all() return render_to_response('home.html', {'releaseitems': releaseitems}, context_instance=RequestContext(request)) 42
  43. 43. Create Template Create home.html in templates <!DOCTYPE html> <html> <head> <title></title> </head> <body> {# you can include templates #} {% include "nav.html" %} {% for release in releaseitems %} {{release.releaseTitle}} {% endfor %} </body> </html> 43
  44. 44. FRONT END • Open http://127.0.0.1:8000/ You will be able to see the model data 44

×