GDG Addis - An Introduction to Django and App Engine

34
Django & App Engine Developing and Deploying to the Cloud Yared Ayalew @yaredayalew

description

 

Transcript of GDG Addis - An Introduction to Django and App Engine

Page 1: GDG Addis - An Introduction to Django and App Engine

Django & App Engine Developing and Deploying to the Cloud

Yared Ayalew @yaredayalew

Page 2: GDG Addis - An Introduction to Django and App Engine

Agenda

• Django 101

• Using Django

• Django and App Engine

Page 3: GDG Addis - An Introduction to Django and App Engine

Not this Django!

Page 4: GDG Addis - An Introduction to Django and App Engine
Page 5: GDG Addis - An Introduction to Django and App Engine

What is Django?

“The web framework for perfectionists with deadlines”

Django makes it easier to build better web apps more quickly and with less code

www.djangoproject.com

Page 6: GDG Addis - An Introduction to Django and App Engine

What’s it for?

• Building dynamic websites

• A high level web framework

• Abstracts common problems

• Shortcuts for fast development

Page 7: GDG Addis - An Introduction to Django and App Engine

The Framework

• Elegant URL Design

• Object/Relational Mapper (ORM)

• Powerful Templating System

• Automatic Admin Interface

•  i18n

•  caching, syndication, middleware, email, sql, modules, authentication, sessions, comments, sitemaps, gis ...

Page 8: GDG Addis - An Introduction to Django and App Engine

Architecture

• “MTV”

• Models describe your data

• Views control what a user sees and does

• Templates are what users see

Page 9: GDG Addis - An Introduction to Django and App Engine

Using Django

Page 10: GDG Addis - An Introduction to Django and App Engine

Requirements

• Python 2.3+

• PostgreSQL/MySQL/SQLite

• Apache + mod_python/mod_wsgi/FastCGI

Page 11: GDG Addis - An Introduction to Django and App Engine

Pip

• A tool for installing and managing Python packages

• PIP (Pip installs Python)

$  wget  http://pypi.python.org/packages/source/p/pip/pip-­‐1.2.1.tar.gz    $  tar  xzf  pip-­‐1.2.1.tar.gz    $  cd  pip-­‐1.2.1  

$  python  setup.py  install    

Page 12: GDG Addis - An Introduction to Django and App Engine

virtualenv

• A self-contained virtual environment for Python development

• Does not touch your Python installation

• Keep track of needed modules with a requirements file

• Allows to test several package versions

$  pip  install  virtualenv  

Page 13: GDG Addis - An Introduction to Django and App Engine

Creating a Virtualenv Create  the  virtual  environment  $  virtualenv  myenvironment    Activate  the  virtual  environment  $  cd  myenvironment  $  source  bin/activate  (myenvironment)$      

Page 14: GDG Addis - An Introduction to Django and App Engine

Get Django

Download it and install from

http://www.djangoproject.com/download

OR

$  pip  install  django  

Page 15: GDG Addis - An Introduction to Django and App Engine

Development

Page 16: GDG Addis - An Introduction to Django and App Engine

Create A Project $  django-­‐admin.py  startproject  myproject    myproject/    manage.py    myproject/        __init__.py        settings.py        urls.py        wsgi.py      

Page 17: GDG Addis - An Introduction to Django and App Engine

Running a Project

$  python  manage.py  runserver    

Browse to http://localhost:8000

Page 18: GDG Addis - An Introduction to Django and App Engine

Projects and Apps

“A project is a collection of settings for an instance of Django, including database configuration, Django-specific options and

application-specific settings.”

"A bundle of Django code, including models and views, that lives together in a single Python package and represents a full Django

application."

Page 19: GDG Addis - An Introduction to Django and App Engine

Creating Applications

$  python  manage.py  startapp  myapp    myapp/      __init__.py      models.py      tests.py      views.py      

Page 20: GDG Addis - An Introduction to Django and App Engine

Django Tools • Django Shell – manipulate your models

python  manage.py  shell  

• Django Server – development & debugging environment

python  manage.py  server  

• SyncDb – build your database from models

python  manage.py  syncdb  

Page 21: GDG Addis - An Introduction to Django and App Engine

Django Building blocks

Page 22: GDG Addis - An Introduction to Django and App Engine

Project Configuration

• Easy configuration in file settings.py  

• Allows you to configure:

• Database connection

•  Installed apps

• Template path

• Logging etc.

Page 23: GDG Addis - An Introduction to Django and App Engine

Models

• Python classes that represent objects in the database and is a subclass of django.db.models.Model  

• Each attribute of the model represents a database field

class  Location(models.Model):                    location_description  =  models.TextField()            city  =  models.CharField("City",max_length=200,null=True)            common_name  =  models.CharField(max_length=200)            lat  =  models.FloatField("Latitude",blank=True,null=True)            lon  =  models.FloatField("Longitude",blank=True,null=True)      

Page 24: GDG Addis - An Introduction to Django and App Engine

Views

• A Python function that takes a web request and returns a web response.

• Response can be html, redirection, 404, image, binary stream, xml etc.

from  myapp.models  import  Location    def  location_by_city(request,city):          places  =  Location.objects.filter(city=city)          return  render_to_response(‘locations/result.html’,{‘places’:places})          

Page 25: GDG Addis - An Introduction to Django and App Engine

Templates

• A text file that can generate any text based format (html, xml, cvs etc)

• Designer friendly

• Tags, variables and filters

•  {%  if  %}  {%  else  %}  {%  endif  %}  

•  {%  for  item  in  list  %}    {%  endfor  %}  

•  {%  ifequal  %}  {%  endifequal  %}  

•  {{  name|lower  }}  

Page 26: GDG Addis - An Introduction to Django and App Engine

Philosophies and Limitations

• Business logic should be separated from presentation logic

• Syntax should be decoupled from HTML/XML

• Designers are assumed to be comfortable with HTML code

• Designers are assumed not to be Python programmers

• The goal is not to invent a programming language

Page 27: GDG Addis - An Introduction to Django and App Engine

Templates

result.html  {%  extends  “base.html”  %}  {%  block  title  %}  Search  Result  {%  endblock%}  {%  block  content  %}            <h2>The  following  locations  are  found:</h2>            {%  for  place  in  places  %}                  <h4>{{  place.common_name  }}</h4>                  <p>  {{  place.location_description  }}  </p>                  <img  src=’{%  url  place.get_map  %}’/>            {%  endfor  %}  {%  endblock  %}    

base.html  <html>      <head>          <title>{%  block  title  %}{%  endblock  %}</title>      </head>      <body>            {%  block  content  %}  {%  endblock  %}      </body>  </html>    

Page 28: GDG Addis - An Introduction to Django and App Engine

URLs • A mapping between a regex url pattern and view functions

• Part of the overall application design

• defined inside urls.py  

from  django.conf.urls  import  patterns,  include,  url    urlpatterns  =  patterns('',          

 url(r'^$',  'myapp.index'),    url(r'^places/(?P<city>\w+)/)$',  'myapp.location_by_city'),              url(r'^place/(?P<location_id>\d+)/$','myapp.view_place'),)  

 

Page 29: GDG Addis - An Introduction to Django and App Engine

Forms • Classes that represent html forms

• Allow data input, validation, error message, label etc. class  CreateLocation(forms.Form):        description  =  forms.TextField()        city  =  forms.CharField(label=”City”,max_length=200)        common_name  =  forms.CharField(max_length=200,widget=                                    forms.TextInput(attrs={‘class’:‘medium_text’}))        lat  =  forms.FloatField()        lon  =  forms.FloatField()    

from  django.forms  import  models  class  LocationForm(model.ModelForm):              class  Meta:                        model=Location    

Page 30: GDG Addis - An Introduction to Django and App Engine

Forms views.py    def  new_location(request):          if  request.method==‘POST’:                form  =  CreateLocation(request.POST)                if  form.is_valid():                      #  Create  a  new  location  object  and  save  it  to  the  database                      return  HttpResponseRedirect(‘/index/’)                else:                      form  =  CreateLocation()                return  render_to_response(‘new.html’,{‘form’:form})    

new.html  <form  action  =  “/new/”  method=“POST”>            {%  csrf_token  %}            {{  form.as_p  }}            <input  type=“submit”  value=“Save”/>  </form>  

Page 31: GDG Addis - An Introduction to Django and App Engine

Automatic Admin • Gives you admin interface to manage your models

• Built into the framework

• To enable admin interface in urls.py uncomment from  django.contrib  import  admin  admin.autodiscover()    url(r'^admin/',  include(admin.site.urls))    #  inside  your  app  add  a  file  called  admin.py  from  django.contrib  import  admin  from  models  import  Location    admin.site.register(Location)  

Page 32: GDG Addis - An Introduction to Django and App Engine

Django + App Engine

Page 33: GDG Addis - An Introduction to Django and App Engine

Django App Engine

• Supports Non-relational models (NOSQL)

• No support for Django’s ImageField and ManyToManyField

• Aggregates

• Transactions

• Many-to-many relations

• QuerySet.select_related() – a queryset that follows foreign-key relationship.

Page 34: GDG Addis - An Introduction to Django and App Engine

Google Cloud SQL •  Fully managed relational database based on MySQL that lives in

Google’s cloud.

• Currently in beta and requires to enable billing

• Restrictions:

•  100 GB size limit per instance

• No support for user defined functions

• MySQL replication is not supported

• More detail at https://developers.google.com/cloud-sql/