SlideShare a Scribd company logo
Introduction to
(Python and)
the Django Framework
Prashant Punjabi
Solution Street
9/26/2014
Python
!
• Created by Guido van Rossum
in the late 1980s
!
• Named after ‘Monty Python’s
Flying Circus’
!
• Python 2.0 was released on 16
October 2000
!
• Python 3.0 a major,
backwards-incompatible
release, was released on 3
December 2008
!
• Guido is the BDFL
Python
• General Purpose, high-level programming language
• Supports multiple programming paradigms
• object-oriented, functional, structured, imperative(?)
• Dynamically typed
• Many implementations
• CPython (reference)
• Jython
• IronPython .. and many more
The Zen of Python
• “Core philosophy”
• Beautiful is better than ugly
• Explicit is better than implicit
• Simple is better than complex
• Complex is better than complicated
• Readability counts
• >>> import this
Data Types
• Numbers
• int, float, long (and complex)
• Strings
• str, unicode
• Sequence Types
• str, unicode, lists, tuples (and bytearrays, buffers, xrange)
• strings, tuples are ‘immutable’
• lists are mutable
• Mapping Types
• dict
Functions
• Defined using the keyword.. def
• Followed by the function name and the parenthesized list of formal parameters.
• The statements that form the body of the function start at the next line,
• and must be indented (just like this line)
• The first statement of the function body can optionally be a string literal
• this string literal is the function’s documentation string, or docstring.
• Arguments are passed using call by value (where the value is always an object
reference, not the value of the object)
• Functions always return a value
• If not return is explicitly defined, the function returns None
Control Flow
• if
• if…elif…else
• for
• range
• break, continue, else
• while
Truthi-nessTM
• An empty list ([])
• An empty tuple (())
• An empty dictionary ({})
• An empty string ('')
• Zero (0)
• The special object None
• The object False (obviously)
• Custom objects that define their own Boolean context behavior (this is
advanced Python usage)
Modules and Packages
• A module is a file containing Python definitions and statements.
• The file name is the module name with the suffix .py appended.
• Within a module, the module’s name (as a string) is available as the value of the
global variable __name__
• Modules can be executed as a script
• python module.py [args]
• __name__ is set to __main__
• Packages are a way of structuring Python’s module namespace by using “dotted
module names”
• The __init__.py file is required to make Python treat a directory as containing
packages
Classes
• Python’s class mechanism adds classes with a minimum of new syntax and
semantics
• Python classes provide all the standard features of Object Oriented
Programming
• multiple base classes
• a derived class can override any methods of its base class or classes
• a method can call the method of a base class with the same name
• Objects can contain arbitrary amounts and kinds of data
• Class and Instance Variables
• Static Methods
Standard Library
• Operating System Interface
• File handling
• String pattern matching
• Regular expressions
• Mathematics
• Internet Access
• Dates and Times
• Collections
• Unit Tests
Batteries Included
Django
Django
• Django grew organically from real-world applications
• Born in the fall of 2003, in Lawrence, Kansas, USA
• Adrian Holovaty and Simon Willison - web
programmers at the Lawrence Journal-World
newspaper
• Released it in July 2005 and named it Django, after the
jazz guitarist Django Reinhard
• “For Perfectionists with Deadlines”
Getting Started
• Installation
• pip install Django
• ¯_(ツ)_/¯
• Creating a Django project
• django-admin.py startproject django_example
• Adding an ‘app’ to your Django project
• python manage.py startapp music
MVC - Separation of Concerns
• models.py
• description of the database table, represented by a Python class, called a model
• create, retrieve, update and delete records in your database using simple Python code
• views.py
• contains the business logic for the page
• contains functions, each of which are called a view functions or simply views
• urls.py
• file specifies which view is called for a given URL pattern
• Templates
• describes the design of the page
• uses a template language with basic logic statements
models.py
• Each model is represented by a class that subclasses django.db.models.Model
• Class variables represents a database fields in the model
• A field is represented by an instance of a Field class eg CharField,
DateTimeField
• The name of each Field instance is used by the database as the column name
• Some Field classes have required arguments, others have optional arguments
• CharField, for example, requires that you give it a max_length
• default is an optional argument for many Field classes
• ForeignKey field is used to define relationships
• Django supports many-to-one, many-to-many and one-to-one
Queries
• Each model has at least one Manager, and it’s called objects by default.
• Managers are accessible only via model classes
• Enforce a separation between “table-level” operations and “record-
level” operations.
• A QuerySet represents a collection of objects from your database
• It can have zero, one or many filters
• A QuerySet equates to a SELECT statement, and a filter is a limiting
clause such as WHERE or LIMIT.
• Example
Migrations
• New in Django 1.7
• Previously accomplished by an external package called south
• Keeps the database in sync with the model objects
• Commands
• migrate
• makemigrations
• sqlmigrate
• squashmigrations
• Data Migrations
• python manage.py makemigrations --empty music
urls.py
• Django lets you design URLs however you want, with no
framework limitations.
• “Cool URIs don’t change”
• URL configuration module (URLconf)
• simple mapping between URL patterns (regular expressions)
to Python functions (views)
• capture parts of URL as parameters to view function (named
groups)
• can be constructed dynamically
views.py
• A Python function that takes a Web request and returns a Web response
• HTML contents of a Web page,
• a redirect, or a 404 error,
• an XML document,
• an image
• . . . or anything
• The convention is to put views in a file called views.py
• but it can be pretty much anywhere on your python path
• ‘Django Shortcuts’
• redirect, reverse, render_to_response,
Templates
• Designed to strike a balance between power and ease
• A template is simply a text file. It can generate any text-based format (HTML, XML,
CSV, etc.).
• Variables - {{ variable }}
• Replaced with values when the template is evaluated
• Use a dot (.) to access attributes of a variable
• Dictionary lookup, attribute or method lookup or numeric index lookup
• {{ person.name }} or {{ person.get_full_name }} or {{ books.
1 }}
• Filters can be used to modify variables for display
• {{ name|lower }}
Templates
• Tags control the logic of the template
• {% tag %}
• Commonly used tags
• for
• if, elif and else
• block and extends - Template inheritance
Template Inheritance
• Most powerful part of Django’s template engine
• Build a base “skeleton” template that contains all the
common elements of your site and defines blocks that
child templates can override.
• {% extends %} must be the first template tag in that
template.
• More {% block %} tags in your base templates are
better
• Child templates don’t have to define all parent blocks
Forms
• Django handles three distinct parts of the work involved in forms
• preparing and restructuring data ready for rendering
• creating HTML forms for the data
• receiving and processing submitted forms and data from the client
• The Django Form class
• Form class’ fields map to HTML form <input> elements
• Fields manage form data and perform validation when a form is submitted
• Fields are represented to a user in the browser as HTML “widgets”
• Each field type has an appropriate default Widget class, but these can be
overridden as required.
Batteries (still) included
• Authentication and Authorization
• Emails
• File Uploads
• Session
• Caching
• Transactions
• .. and so on
See also..
• The Django ‘admin’ app
• django-admin.py and manage.py
• ModelForms
• Generic Views or Class based views
• Static File deployment
• Settings
• Middleware
• Similar to Servlet Filters in Java
References
• Python - Wikipedia page (http://en.wikipedia.org/wiki/
Python_(programming_language))
• The Python Tutorial (https://docs.python.org/2/tutorial/
index.html)
• The Django Project (https://www.djangoproject.com/)
• The Django Book (http://www.djangobook.com/en/2.0/
index.html)
• The Django Documentation (https://
docs.djangoproject.com/en/1.7/)
Questions?
Thank you!

More Related Content

What's hot

GeekAustin PHP Class - Session 6
GeekAustin PHP Class - Session 6GeekAustin PHP Class - Session 6
GeekAustin PHP Class - Session 6jimbojsb
 
WordPress Themes 101 - HighEdWeb New England 2013
WordPress Themes 101 - HighEdWeb New England 2013WordPress Themes 101 - HighEdWeb New England 2013
WordPress Themes 101 - HighEdWeb New England 2013
Curtiss Grymala
 
Eurydike: Schemaless Object Relational SQL Mapper
Eurydike: Schemaless Object Relational SQL MapperEurydike: Schemaless Object Relational SQL Mapper
Eurydike: Schemaless Object Relational SQL Mapper
ESUG
 
Json - ideal for data interchange
Json - ideal for data interchangeJson - ideal for data interchange
Json - ideal for data interchange
Christoph Santschi
 
PHP - Introduction to PHP Date and Time Functions
PHP -  Introduction to  PHP Date and Time FunctionsPHP -  Introduction to  PHP Date and Time Functions
PHP - Introduction to PHP Date and Time Functions
Vibrant Technologies & Computers
 
FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3
Toni Kolev
 
WordPress Themes 101 - dotEduGuru Summit 2013
WordPress Themes 101 - dotEduGuru Summit 2013WordPress Themes 101 - dotEduGuru Summit 2013
WordPress Themes 101 - dotEduGuru Summit 2013
Curtiss Grymala
 
Apache Velocity
Apache Velocity Apache Velocity
Apache Velocity
yesprakash
 

What's hot (12)

GeekAustin PHP Class - Session 6
GeekAustin PHP Class - Session 6GeekAustin PHP Class - Session 6
GeekAustin PHP Class - Session 6
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
WordPress Themes 101 - HighEdWeb New England 2013
WordPress Themes 101 - HighEdWeb New England 2013WordPress Themes 101 - HighEdWeb New England 2013
WordPress Themes 101 - HighEdWeb New England 2013
 
Eurydike: Schemaless Object Relational SQL Mapper
Eurydike: Schemaless Object Relational SQL MapperEurydike: Schemaless Object Relational SQL Mapper
Eurydike: Schemaless Object Relational SQL Mapper
 
Json - ideal for data interchange
Json - ideal for data interchangeJson - ideal for data interchange
Json - ideal for data interchange
 
PHP - Introduction to PHP Date and Time Functions
PHP -  Introduction to  PHP Date and Time FunctionsPHP -  Introduction to  PHP Date and Time Functions
PHP - Introduction to PHP Date and Time Functions
 
Php Basics
Php BasicsPhp Basics
Php Basics
 
FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3
 
Java XML Parsing
Java XML ParsingJava XML Parsing
Java XML Parsing
 
JS Essence
JS EssenceJS Essence
JS Essence
 
WordPress Themes 101 - dotEduGuru Summit 2013
WordPress Themes 101 - dotEduGuru Summit 2013WordPress Themes 101 - dotEduGuru Summit 2013
WordPress Themes 101 - dotEduGuru Summit 2013
 
Apache Velocity
Apache Velocity Apache Velocity
Apache Velocity
 

Viewers also liked

Recent resume
Recent resumeRecent resume
Recent resume
Sudharson M R
 
Wipro resume
Wipro resumeWipro resume
Wipro resume
Kapil Chaudhary
 
Resume-Python-Developer-ZachLiu
Resume-Python-Developer-ZachLiuResume-Python-Developer-ZachLiu
Resume-Python-Developer-ZachLiuZhiqiang Liu
 
Python/Django Training
Python/Django TrainingPython/Django Training
Python/Django Training
University of Technology
 
Resume
ResumeResume
Resume
narsglance
 

Viewers also liked (12)

Recent resume
Recent resumeRecent resume
Recent resume
 
Saurav Srivastava CV..
Saurav Srivastava CV..Saurav Srivastava CV..
Saurav Srivastava CV..
 
Resume
ResumeResume
Resume
 
django
djangodjango
django
 
CV(Arpit_Singh)
CV(Arpit_Singh)CV(Arpit_Singh)
CV(Arpit_Singh)
 
socialpref
socialprefsocialpref
socialpref
 
Wipro resume
Wipro resumeWipro resume
Wipro resume
 
Archana Jaiswal Resume
Archana Jaiswal ResumeArchana Jaiswal Resume
Archana Jaiswal Resume
 
Resume-Python-Developer-ZachLiu
Resume-Python-Developer-ZachLiuResume-Python-Developer-ZachLiu
Resume-Python-Developer-ZachLiu
 
Python/Django Training
Python/Django TrainingPython/Django Training
Python/Django Training
 
Resume
ResumeResume
Resume
 
Dana resume1
Dana resume1Dana resume1
Dana resume1
 

Similar to Introduction to Python and Django

GDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineGDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineYared Ayalew
 
Best Python Online Training with Live Project by Expert
Best Python Online Training with Live Project by Expert Best Python Online Training with Live Project by Expert
Best Python Online Training with Live Project by Expert
QA TrainingHub
 
Python-Magnitia-ToC.pdf
Python-Magnitia-ToC.pdfPython-Magnitia-ToC.pdf
Python-Magnitia-ToC.pdf
AnanthReddy38
 
Introduction_to_Python.pptx
Introduction_to_Python.pptxIntroduction_to_Python.pptx
Introduction_to_Python.pptx
RahulChaudhary51756
 
Software Programming with Python II.pptx
Software Programming with Python II.pptxSoftware Programming with Python II.pptx
Software Programming with Python II.pptx
GevitaChinnaiah
 
Advanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoAdvanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojo
Fu Cheng
 
QueryPath, Mash-ups, and Web Services
QueryPath, Mash-ups, and Web ServicesQueryPath, Mash-ups, and Web Services
QueryPath, Mash-ups, and Web Services
Matt Butcher
 
Python Programming - VI. Classes and Objects
Python Programming - VI. Classes and ObjectsPython Programming - VI. Classes and Objects
Python Programming - VI. Classes and ObjectsRanel Padon
 
Web development django.pdf
Web development django.pdfWeb development django.pdf
Web development django.pdf
KomalSaini178773
 
Python indroduction
Python indroductionPython indroduction
Python indroduction
FEG
 
Beyond Domino Designer
Beyond Domino DesignerBeyond Domino Designer
Beyond Domino Designer
Paul Withers
 
Tango with django
Tango with djangoTango with django
Tango with django
Rajan Kumar Upadhyay
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
AbhishekMondal42
 
Integrating the Solr search engine
Integrating the Solr search engineIntegrating the Solr search engine
Integrating the Solr search engine
th0masr
 
Modules Building Presentation
Modules Building PresentationModules Building Presentation
Modules Building Presentationhtyson
 
Your first d8 module
Your first d8 moduleYour first d8 module
Your first d8 module
tedbow
 
A peek into Python's Metaclass and Bytecode from a Smalltalk User
A peek into Python's Metaclass and Bytecode from a Smalltalk UserA peek into Python's Metaclass and Bytecode from a Smalltalk User
A peek into Python's Metaclass and Bytecode from a Smalltalk User
Koan-Sin Tan
 
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
Udit Gangwani
 
Introduction to Monsoon PHP framework
Introduction to Monsoon PHP frameworkIntroduction to Monsoon PHP framework
Introduction to Monsoon PHP framework
Krishna Srikanth Manda
 

Similar to Introduction to Python and Django (20)

GDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineGDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App Engine
 
Python Tutorial Part 2
Python Tutorial Part 2Python Tutorial Part 2
Python Tutorial Part 2
 
Best Python Online Training with Live Project by Expert
Best Python Online Training with Live Project by Expert Best Python Online Training with Live Project by Expert
Best Python Online Training with Live Project by Expert
 
Python-Magnitia-ToC.pdf
Python-Magnitia-ToC.pdfPython-Magnitia-ToC.pdf
Python-Magnitia-ToC.pdf
 
Introduction_to_Python.pptx
Introduction_to_Python.pptxIntroduction_to_Python.pptx
Introduction_to_Python.pptx
 
Software Programming with Python II.pptx
Software Programming with Python II.pptxSoftware Programming with Python II.pptx
Software Programming with Python II.pptx
 
Advanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojoAdvanced guide to develop ajax applications using dojo
Advanced guide to develop ajax applications using dojo
 
QueryPath, Mash-ups, and Web Services
QueryPath, Mash-ups, and Web ServicesQueryPath, Mash-ups, and Web Services
QueryPath, Mash-ups, and Web Services
 
Python Programming - VI. Classes and Objects
Python Programming - VI. Classes and ObjectsPython Programming - VI. Classes and Objects
Python Programming - VI. Classes and Objects
 
Web development django.pdf
Web development django.pdfWeb development django.pdf
Web development django.pdf
 
Python indroduction
Python indroductionPython indroduction
Python indroduction
 
Beyond Domino Designer
Beyond Domino DesignerBeyond Domino Designer
Beyond Domino Designer
 
Tango with django
Tango with djangoTango with django
Tango with django
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Integrating the Solr search engine
Integrating the Solr search engineIntegrating the Solr search engine
Integrating the Solr search engine
 
Modules Building Presentation
Modules Building PresentationModules Building Presentation
Modules Building Presentation
 
Your first d8 module
Your first d8 moduleYour first d8 module
Your first d8 module
 
A peek into Python's Metaclass and Bytecode from a Smalltalk User
A peek into Python's Metaclass and Bytecode from a Smalltalk UserA peek into Python's Metaclass and Bytecode from a Smalltalk User
A peek into Python's Metaclass and Bytecode from a Smalltalk User
 
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]
 
Introduction to Monsoon PHP framework
Introduction to Monsoon PHP frameworkIntroduction to Monsoon PHP framework
Introduction to Monsoon PHP framework
 

Recently uploaded

The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 

Recently uploaded (20)

The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 

Introduction to Python and Django

  • 1. Introduction to (Python and) the Django Framework Prashant Punjabi Solution Street 9/26/2014
  • 2. Python ! • Created by Guido van Rossum in the late 1980s ! • Named after ‘Monty Python’s Flying Circus’ ! • Python 2.0 was released on 16 October 2000 ! • Python 3.0 a major, backwards-incompatible release, was released on 3 December 2008 ! • Guido is the BDFL
  • 3. Python • General Purpose, high-level programming language • Supports multiple programming paradigms • object-oriented, functional, structured, imperative(?) • Dynamically typed • Many implementations • CPython (reference) • Jython • IronPython .. and many more
  • 4. The Zen of Python • “Core philosophy” • Beautiful is better than ugly • Explicit is better than implicit • Simple is better than complex • Complex is better than complicated • Readability counts • >>> import this
  • 5. Data Types • Numbers • int, float, long (and complex) • Strings • str, unicode • Sequence Types • str, unicode, lists, tuples (and bytearrays, buffers, xrange) • strings, tuples are ‘immutable’ • lists are mutable • Mapping Types • dict
  • 6. Functions • Defined using the keyword.. def • Followed by the function name and the parenthesized list of formal parameters. • The statements that form the body of the function start at the next line, • and must be indented (just like this line) • The first statement of the function body can optionally be a string literal • this string literal is the function’s documentation string, or docstring. • Arguments are passed using call by value (where the value is always an object reference, not the value of the object) • Functions always return a value • If not return is explicitly defined, the function returns None
  • 7. Control Flow • if • if…elif…else • for • range • break, continue, else • while
  • 8. Truthi-nessTM • An empty list ([]) • An empty tuple (()) • An empty dictionary ({}) • An empty string ('') • Zero (0) • The special object None • The object False (obviously) • Custom objects that define their own Boolean context behavior (this is advanced Python usage)
  • 9. Modules and Packages • A module is a file containing Python definitions and statements. • The file name is the module name with the suffix .py appended. • Within a module, the module’s name (as a string) is available as the value of the global variable __name__ • Modules can be executed as a script • python module.py [args] • __name__ is set to __main__ • Packages are a way of structuring Python’s module namespace by using “dotted module names” • The __init__.py file is required to make Python treat a directory as containing packages
  • 10. Classes • Python’s class mechanism adds classes with a minimum of new syntax and semantics • Python classes provide all the standard features of Object Oriented Programming • multiple base classes • a derived class can override any methods of its base class or classes • a method can call the method of a base class with the same name • Objects can contain arbitrary amounts and kinds of data • Class and Instance Variables • Static Methods
  • 11. Standard Library • Operating System Interface • File handling • String pattern matching • Regular expressions • Mathematics • Internet Access • Dates and Times • Collections • Unit Tests
  • 14. Django • Django grew organically from real-world applications • Born in the fall of 2003, in Lawrence, Kansas, USA • Adrian Holovaty and Simon Willison - web programmers at the Lawrence Journal-World newspaper • Released it in July 2005 and named it Django, after the jazz guitarist Django Reinhard • “For Perfectionists with Deadlines”
  • 15. Getting Started • Installation • pip install Django • ¯_(ツ)_/¯ • Creating a Django project • django-admin.py startproject django_example • Adding an ‘app’ to your Django project • python manage.py startapp music
  • 16. MVC - Separation of Concerns • models.py • description of the database table, represented by a Python class, called a model • create, retrieve, update and delete records in your database using simple Python code • views.py • contains the business logic for the page • contains functions, each of which are called a view functions or simply views • urls.py • file specifies which view is called for a given URL pattern • Templates • describes the design of the page • uses a template language with basic logic statements
  • 17. models.py • Each model is represented by a class that subclasses django.db.models.Model • Class variables represents a database fields in the model • A field is represented by an instance of a Field class eg CharField, DateTimeField • The name of each Field instance is used by the database as the column name • Some Field classes have required arguments, others have optional arguments • CharField, for example, requires that you give it a max_length • default is an optional argument for many Field classes • ForeignKey field is used to define relationships • Django supports many-to-one, many-to-many and one-to-one
  • 18. Queries • Each model has at least one Manager, and it’s called objects by default. • Managers are accessible only via model classes • Enforce a separation between “table-level” operations and “record- level” operations. • A QuerySet represents a collection of objects from your database • It can have zero, one or many filters • A QuerySet equates to a SELECT statement, and a filter is a limiting clause such as WHERE or LIMIT. • Example
  • 19. Migrations • New in Django 1.7 • Previously accomplished by an external package called south • Keeps the database in sync with the model objects • Commands • migrate • makemigrations • sqlmigrate • squashmigrations • Data Migrations • python manage.py makemigrations --empty music
  • 20. urls.py • Django lets you design URLs however you want, with no framework limitations. • “Cool URIs don’t change” • URL configuration module (URLconf) • simple mapping between URL patterns (regular expressions) to Python functions (views) • capture parts of URL as parameters to view function (named groups) • can be constructed dynamically
  • 21. views.py • A Python function that takes a Web request and returns a Web response • HTML contents of a Web page, • a redirect, or a 404 error, • an XML document, • an image • . . . or anything • The convention is to put views in a file called views.py • but it can be pretty much anywhere on your python path • ‘Django Shortcuts’ • redirect, reverse, render_to_response,
  • 22. Templates • Designed to strike a balance between power and ease • A template is simply a text file. It can generate any text-based format (HTML, XML, CSV, etc.). • Variables - {{ variable }} • Replaced with values when the template is evaluated • Use a dot (.) to access attributes of a variable • Dictionary lookup, attribute or method lookup or numeric index lookup • {{ person.name }} or {{ person.get_full_name }} or {{ books. 1 }} • Filters can be used to modify variables for display • {{ name|lower }}
  • 23. Templates • Tags control the logic of the template • {% tag %} • Commonly used tags • for • if, elif and else • block and extends - Template inheritance
  • 24. Template Inheritance • Most powerful part of Django’s template engine • Build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override. • {% extends %} must be the first template tag in that template. • More {% block %} tags in your base templates are better • Child templates don’t have to define all parent blocks
  • 25. Forms • Django handles three distinct parts of the work involved in forms • preparing and restructuring data ready for rendering • creating HTML forms for the data • receiving and processing submitted forms and data from the client • The Django Form class • Form class’ fields map to HTML form <input> elements • Fields manage form data and perform validation when a form is submitted • Fields are represented to a user in the browser as HTML “widgets” • Each field type has an appropriate default Widget class, but these can be overridden as required.
  • 26. Batteries (still) included • Authentication and Authorization • Emails • File Uploads • Session • Caching • Transactions • .. and so on
  • 27. See also.. • The Django ‘admin’ app • django-admin.py and manage.py • ModelForms • Generic Views or Class based views • Static File deployment • Settings • Middleware • Similar to Servlet Filters in Java
  • 28. References • Python - Wikipedia page (http://en.wikipedia.org/wiki/ Python_(programming_language)) • The Python Tutorial (https://docs.python.org/2/tutorial/ index.html) • The Django Project (https://www.djangoproject.com/) • The Django Book (http://www.djangobook.com/en/2.0/ index.html) • The Django Documentation (https:// docs.djangoproject.com/en/1.7/)