GDG Addis - An Introduction to Django and App Engine
-
Upload
yared-ayalew -
Category
Documents
-
view
330 -
download
3
description
Transcript of GDG Addis - An Introduction to Django and App Engine
Django & App Engine Developing and Deploying to the Cloud
Yared Ayalew @yaredayalew
Agenda
• Django 101
• Using Django
• Django and App Engine
Not this Django!
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
What’s it for?
• Building dynamic websites
• A high level web framework
• Abstracts common problems
• Shortcuts for fast development
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 ...
Architecture
• “MTV”
• Models describe your data
• Views control what a user sees and does
• Templates are what users see
Using Django
Requirements
• Python 2.3+
• PostgreSQL/MySQL/SQLite
• Apache + mod_python/mod_wsgi/FastCGI
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
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
Creating a Virtualenv Create the virtual environment $ virtualenv myenvironment Activate the virtual environment $ cd myenvironment $ source bin/activate (myenvironment)$
Get Django
Download it and install from
http://www.djangoproject.com/download
OR
$ pip install django
Development
Create A Project $ django-‐admin.py startproject myproject myproject/ manage.py myproject/ __init__.py settings.py urls.py wsgi.py
Running a Project
$ python manage.py runserver
Browse to http://localhost:8000
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."
Creating Applications
$ python manage.py startapp myapp myapp/ __init__.py models.py tests.py views.py
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
Django Building blocks
Project Configuration
• Easy configuration in file settings.py
• Allows you to configure:
• Database connection
• Installed apps
• Template path
• Logging etc.
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)
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})
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 }}
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
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>
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'),)
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
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>
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)
Django + 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.
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/