Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Django, Web Development Done Right

Django, Web Development Done Right

To date, developing web applications usually involves the accomplishment of the
following two (simple) preliminary steps: (1) choosing the *programming
language* to use; (2) choosing the **web framework** to use, implemented
in that language.

In fact, **web frameworks** provides a common and solid stack of
functionalities (a.k.a. *full-stack frameworks*) out-of-the-box, aimed at
reducing boilerplate code, without "re-inventing" the wheel.

Some of these functionalities includes *automatic session handling*,
*built-in model and database management*, *authentication mechanisms*,
*template composition* and *templating language*, and so forth.

However, even if web frameworks provide the overall software platform to
integrate and orchestrate all these tools, developers are required to embrace
frameworks' design philosophy, and to adapt it to fit into their own web
applications.

**Django** is one of the most famous and widely used web framework in *Python*.

Django is built on top of solid design principles, and provides a full stack of
features aimed at drastically reducing the burden of developing *data intensive*
web applications (e.g., `django.contrib.admin`).

This talk aims at presenting an overview of the main features and capabilities
of the *Django framework*.

In particular, after a general and very short introduction to web frameworks'
features, this first part of the talk highlights some of the most important
*batteries* provided by the framework out-of-the-box.
To this end, several code examples are going to be reported in the slides
during the presentation.

Moreover, the second part of the talk focuses on presenting *best practice*
of design and developing web applications with `django`.
For example, "Which is the best way to modularize the Python code into several
and really *pluggable* `django apps`?".

To this end, a detailed description of the apps provided by the framework will
be presented, in order to understand how to use them in our code (e.g.,
`django.contrib.auth` ) in a very
[DRY](https://docs.djangoproject.com/en/1.7/misc/design-philosophies/#don-t-repeat-yourself-dry) fashion.

This talk is intended for a *Basic* level of audience. Thus, no prior knowledge
of Django is required to attend this talk. However, a *good knowledge* of
Python is required.

Valerio Maggio

June 13, 2014
Tweet

More Decks by Valerio Maggio

Other Decks in Programming

Transcript

  1. After this talk you should (hopefully!-) have learnt what a

    web framework is and what it is not have learnt when and why you should use a web framework be aware that there is a plethora of web frameworks now available (but Django is a very good one!-) (iow) Overview of Django features and design (Very brief) Introduction to 
 Web Frameworks Introduction to +
  2. (Last but not least) Monty Python’s funny quotes (along with

    title slides) Btw, there’s a rationale for that (despite the fact that it’s funny !-)
  3. WHAT YOU’LL
 not FIND IN THIS TALK A Django tutorial

    …but we’ll have a lot of examples and useful references
  4. “ King Arthur: One, two, five!
 Sir Galahad: Three sir!


    King Arthur: THREE! ” – Monty Python and the Holy Grail Start over (seriously)
  5. Framework “framework” is one of the most overused word in

    Computer Science framework is a buzzword Testing framework Development framework Web framework ’^.*$’ framework
  6. What a framework is not A framework is not an

    API “An API specifies how some software components should interact with each other” A framework is not a Library “A Library is a collection of functions/objects serving a particular purpose”
  7. What a framework is not (cont.) A framework is not

    an Application
 (Moreover) A (web) framework is not a CMS manage work-flows and contents in a collaborative environment (CMS) alleviate the burden associated with common web development (Framework)

  8. So... What a framework may be? (metaphor)
 “A work table

    full of tools that are ready to be used.”
  9. “King Arthur: A Duck.
 Sir Bedevere: …Exactly. So, logically...
 Peasant:

    If she weighed the same as a duck... she's made of wood.
 Sir Bedevere: And therefore...
 Peasant: ...A witch!” – Monty Python and the Holy Grail Introducing
  10. (Django) References Italian http://sushi.apogeonline.com/ebook/ creare-la-prima-applicazione-con-django Code examples used along the

    slides has been gathered from: https://bitbucket.org/django-sushi http://goo.gl/j9aVJI
  11. “Thanks a lot for the gold and frankincense, but don't

    worry too much about the myrrh the next time, all right?.” – Monty Python - The life of Brian 1. Web Technologies Evolution
  12. Web Evolution Timeline Web developers wrote every page “by hand”

    Updating a web site means editing HTML “re-design” means “do it from scratch” one at a time No Scalability i.e., How many pages there may be? HTML Pages no Web sad times :’(
  13. Web Evolution Timeline (+) Web Pages are intended as resources

    Dynamically generate contents It was the raise of the so-called “server side technologies” (-) Difficult Code reuse Lots of boilerplate code (-) High learning curve HTML Pages CGI Scripting no Web CGI - Common Gateway Interface
  14. !! Any Concern? I did my best in making these

    Perl scripts (human) readable :-P Web Browser Web Server CGI Program HTTP Request HTML Response exec w/environ stdout
  15. !! Any remark? Web Browser Web Server CGI Program HTTP

    Request HTML Response exec w/environ stdout Database SQL
  16. Web Evolution Timeline (+) Learning curve extremely shallow Server-side code

    mixed within HTML (-) No Security and or protection mechanism provided (-) (Again… and even more) 
 Bunch of HTML, Code and SQL… all together HTML Pages CGI Scripting PHP like Technologies PHP: Hypertext Pre-Processor …originally it was “Personal Home Page” no Web
  17. JSP example !! Any remark? I mean…despite of using MySQL

    :-P …more on 
 http://goo.gl/NkzONA
  18. Presentation + Business Logic + Data (& SQL) = All

    messed up Q: What if you have to share (even one of) them among multiple pages? A: Duplication 
 (a.k.a. Bad Smell)
  19. Web Evolution Timeline (a.k.a.) Desktop like web applications Javascript (and

    Ajax) Intensive web apps Software Solutions battery included HTML Pages CGI Scripting PHP like Technologies RIA: Rich Internet Applications no Web RIA
  20. Web Server XMLHTTP Request XML Response QUERY_STRING XML data Database

    Server-side Technology Web Browser Javascript (Update) HTML SQL Rich-Internet Applications Presentation and Visualisation Data and Models Business Logic
  21. MVC: Model View Controller Model Responsible for domain and data

    acquisition View Responsible of data visualisation Controller Responsible of domain object handling Controller Model View +theView +theController +theModel +theModel
  22. (Web-MVC) “Stack” of Capabilities Model Database Abstractions ORM - Object

    relational Mapping View Javascript Library Web page compositions (a.k.a. Template Engine) (Local) Development Server Controller URL Routing (RESTful) Controller-view Association Security Mechanism (SQL-Injections, Clickjacking, CSRF)
  23. Do not reinvent the wheel Web frameworks provide a programming

    infrastructure for developing web applications
  24. “ Cleric: And the people did feast upon the lambs

    and sloths, and carp and 
 anchovies, and orangutans and breakfast cereals, and fruit-bats and… Brother Maynard: Skip a bit brother…” – Monty Python and the Holy Grail 2. Web Frameworks
  25. Definition […] frameworks provide support for a number of activities

    such as interpreting requests, producing responses, storing data persistently, and so on. […] those frameworks […] are often known as full-stack frameworks in that they attempt to supply components for each layer in the stack. source: python.org wiki FYI, there exist also Micro-Frameworks
  26. [full|micro] stack 
 web frameworks Full stack frameworks: HTTP Request/Response

    URL Routing Mechanism Dev Server (WSGI) ORM Template Engines Micro stack frameworks: HTTP Request/Response URL Routing Mechanism Dev Server (WSGI) ORM (or any DB wrapper) Template Engines
  27. Layers 
 of the stack [full|micro] stack frameworks: HTTP Request/Response

    URL Routing Mechanism Dev Server (WSGI) [ORM]? [Template Engines]? Some frameworks Provide their own implementation for each component of the stack e.g., Django Some others are designed to integrate third party tools e.g., Turbogears
  28. Design Principles and Goals Convention over Configuration Convention over Configuration

    is a programming design that favours following a certain set of programming conventions instead of configuring an application framework. DRY (Don’t Repeat Yourself) DRY is a principle that focuses on reducing information duplication by keeping any piece of knowledge in a system in only one place Loose Coupling The various layers of the framework shouldn’t “know” about each other unless absolutely necessary.
  29. Design Principles and Goals Less code Web Apps should use

    as little code as possible; they should lack boilerplate. Quick Development The point of a Web framework in the 21st century is to make the tedious aspects of Web development fast.
  30. “And Now for Something Completely Different.” – Monty Python Flying

    Circus 3. Django at a glance https://www.djangoproject.com
  31. Django MVC:
 MTV Model Django ORM + Python classes Template

    HTML-like resources Shows data coming from Views. View Python Callback functions Handles business logic: arranges and supplies data to Templates (+) Controller (framework) Dispatches requests to proper Views based on RegExp matching MTV: Model-Template-View View Model Template +theTemplate +theModel URL Dispatcher [(framework) Controller] +theView
  32. Django features Django has a lot of built-in stuff, to

    boost productivity Nevertheless, it strives to remain as small as possible to support any extension to not limit what you can do
  33. Django Project and Apps $ django-admin.py startproject booklibrary booklibrary/ ├──

    manage.py └── booklibrary ├── __init__.py ├── settings.py ├── urls.py └── wsgi.py 1 directory, 5 files $ python manage.py startapp library booklibrary/ ├── manage.py ├── booklibrary │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── library ├── __init__.py ├── admin.py ├── models.py ├── tests.py └── views.py 2 directories, 10 files A Django Project is made of Apps Apps provide specific functionalities e.g., Auth, Social Integration, Polls, … Apps should be as less coupled as possible
  34. Design goal: Reusable Apps Loosely coupled modules (Apps) in order

    to be shared among different projects • a.k.a. pluggable apps You can plug into your project many 3rd party apps, immediately adding to your product complex functionality Copy&Paste the folder into the Project root • No need for coding
  35. SOME REUSABLE APPS django-ratings django-ajax-validation django-google-analytics django-mailer django-discussion django-announcements django-email-confirmation

    django-jits django-liveblogging django-atompub django-queue-service django-galaxy django-messages django-audioplayer django-dynamic-media-serve django-evolution django-authopenid django-googlemap django-compress django-db-log django-avatar django-graphs django-oembed django-clevercss django-basic-blog django-microformats django-object-view-tracking django-chunks django-basic-library django-tagging django-mobileadmin django-ads django-basic-people django-survey django-rest-interface django-orm-cache django-basic-places django-voting django-page-cms django-registration django-cron django-wiki django-photologue django-navbar django-favorites satchmo django-pingback django-openid django-forum sorl-thumbnail django-pressroom django-oauth django-gcal django-mailfriend django-recommender django-mmo
  36. Data Models and ORM Author first_name: Char[50] last_name: Char[50] Genre

    description: Char[30] Book title: Char[200] buyed_on: Date 1..* 1..* 1 1..* All the model classes extends (django) models.Model
  37. Automatic Forms Model Form 
 (i.e., Form from Model class)

    extending (django) forms.ModelForm Form Class with 
 custom fields
 extending (django) forms.Form
  38. Views and Templates books.html: 
 template file name Book.objects.all().order_by(‘title’): 


    Django ORM in action This means: SELECT * from Book ORDER_BY ‘title’
  39. (built-in) Template Language Variables: Syntax {{ variable_name }} e.g., {{

    author }} Template Tags: Syntax {% template_tag_name %} e.g., {% for book in books %} {% endfor %} Filters: Syntax {{ variable_name|filter }} Alters the formatting of variables e.g., {{ book.bought_on|date:”d/m/Y” }}
  40. URL config URL dispatching based on Regular Expressions: Mapping between

    RegExp and Django view This URL will match incoming requests to /books/ that will be served by the view librery.views.books This will enable default Admin Application
  41. “ Sir Bedevere: …and what do you burn apart from

    witches?
 Peasant: Moooore witcheees!!” – Monty Python and the Holy Grail Migration is coming
  42. migration is coming migrate is going to replace the syncdb

    command syncdb will still work (up to Django 1.8) pre_migrate, post_migrate signals makemigrations command responsible to create new migrations schema based on changes docs.djangoproject.com/en/dev/topics/migrations/