0% found this document useful (0 votes)
65 views77 pages

Raspberry Pi IoT Integration Guide

Uploaded by

tharunkumar0973
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views77 pages

Raspberry Pi IoT Integration Guide

Uploaded by

tharunkumar0973
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

Unit 5

1. IoT Physical Devices & Endpoints:


• Rasberry Pi, Rasberry Pi interfaces-Serial, SPI, I2C.
2. IoT Physical Servers and Cloud offerings:
• WAMP: AutoBahn for IoT, Xivelycloud for IoT
3. Python Web Application Framework:
• Django Framework-Roles of Model, Template and View
Exemplary Device: Raspberry Pi
• Raspberry Pi is a low-cost mini-computer with the physical size of a credit card.
• Single-board computer.
• Low cost.
• Easy to access.
• Raspberry Pi runs various flavors of Linux and can perform almost all tasks that a
normal desktop computer can do.
• Raspberry Pi also allows interfacing sensors and actuators through the general
purpose I/O pins.
• Since Raspberry Pi runs Linux operating system, it supports Python "out of the
box".
Raspberry Pi Board

Display Serial Interface

Camera Serial Interface


Basic Architecture of Raspberry Pi

RAM

I/O CPU/GPU USB HUB

ETHERNET USB
Comparison of various models:
About the Board Status LEDs

Status LED Function


ACT SD card access
PWR 3.3V Power is present
FDX Full Duplex LAN connected
LNK Link/Network activity
100 100 Mbit LAN connected
Raspberry Pi 4
Basic Set up for Raspberry Pi
1. HDMI cable.
2. Monitor.
3. Key board.
4. Mouse.
5. 5volt power adapter for raspberry pi.
6. LAN cable .
7. Min-2GBmicro sd card
Raspberry Pi Setup
Download Raspbian:
Download latest Raspbianimage from raspberry pi official site:
https://www.raspberrypi.org/downloads/

Programming
Default installed :
• Python
• C
• C++
• Java
• Scratch
• Ruby
Note : Any language that will compile for ARMv6 can be used with raspberry pi.
Linux on Raspberry Pi
NOOBS (or “New Out Of the Box Software”) is a unique installation image. With
NOOBS loaded on an SD Card you can install a wonderful range of operating systems for
your Raspberry Pi.

• Raspbian- Raspbian Linux is a Debian Wheezy port optimized for Raspberry Pi.
• Arch- Arch is an Arch Linux port for AMD (Advance micro devices) devices.
• Pidora- Pidora Linux is a Fedora Linux optimized for Raspberry Pi.
• RaspBMC- RaspBMC is an XBMC media-center distribution for Raspberry Pi.
• OpenELEC- OpenELEC is a fast and user-friendly XBMC media-center
distribution.
• RISC OS- RISC OS is a very fast and compact operating system.
Raspbian Linux Desktop
Raspberry Pi GPIO
Act as both digital output and digital input.

• Output: turn a GPIO pin high or low.

• Input: detect a GPIO pin high or low.


Raspberry Pi GPIO headers
• A 40-pin GPIO header is found on all current Raspberry Pi boards.
• Prior to the Pi 1 Model B+ (2014), boards comprised a shorter 26-pin header.
• Any of the GPIO pins can be designated (in software) as an input or output pin and used
for a wide range of purposes.
Voltages:
• Two 5V pins and two 3V3 pins are present on the board, as well as a number of ground
pins (0V), which are non-configurable.
• The remaining pins are all general purpose 3V3 pins, meaning outputs are set to 3V3 and
inputs are 3V3-tolerant.
Raspberry Pi Interfaces
1. Serial:
The serial interface on Raspberry Pi has receive (Rx) and transmit (Tx) pins for communication with serial
peripherals.

2. SPI:
Serial Peripheral Interface (SPI) is a synchronous serial data protocol used for communicating with one or
more peripheral devices.
In an SPI connection, there is one MASTER device and one or more Peripheral devices. There are 5 pins in
raspberry pi for SPI interface:
• MISO- Master In Slave Out : Master line for sending data to the peripherals.
• MOSI- Master Out Slave In : Slave line for sending data to the master.
• SCK (Serial Clock) : Clock generated by master to synchronize data transmission
• CE0 (Chip Enable 0)
• CE1 (Chip Enable 1)
3. I2C:
The I2C (Inter-IC) interface pins on Raspberry Pi allows to connect hardware modules. I2C interface allows
synchronous data transfer with just two pins - SDA (data line) and SCL (clock line).
As well as simple input and output devices, the GPIO pins can be used with a variety of
alternative functions, some are available on all pins, others on specific pins:
• PWM (pulse-width modulation)
– Software PWM available on all pins
– Hardware PWM available on GPIO12, GPIO13, GPIO18, GPIO19
• SPI
– SPI0: MOSI (GPIO10); MISO (GPIO9); SCLK (GPIO11); CE0 (GPIO8), CE1 (GPIO7)
– SPI1: MOSI (GPIO20); MISO (GPIO19); SCLK (GPIO21); CE0 (GPIO18); CE1 (GPIO17);
CE2 (GPIO16)
• I2C
– Data: (GPIO2); Clock (GPIO3)
– EEPROM Data: (GPIO0); EEPROM Clock (GPIO1)
• Serial
– TX (GPIO14); RX (GPIO15)
Fully hardware PWM
• This type of PWM is generated by the Pi's PWM peripheral.
• The timing of the pulses is controlled by the PWM peripheral.
• It is the most accurate and the most flexible.
• It can be generated on GPIO 12/13/18/19. However there are only two channels, so only two different
PWM streams can be generated at a time. GPIO 12/18 are on one channel, GPIO 13/19 on the other.
• Suitable for jitter free servos, glitch free LED brightness control, motor speed control.

Software Timed PWM


• This type of PWM is generated by software.
• The timing of the pulses is controlled by the (Linux) scheduler. It is appreciably less timing accurate than
fully hardware PWM.
• The number of frequencies is unlimited and the number of steps between on and off is unlimited.
• This type of PWM may be generated on any GPIO on the expansion header. All GPIO may have different
settings. The timing accuracy will vary according to the number of GPIO being used for PWM.
• Not really suitable for servos, will control LED brightness but will suffer from glitches, suitable for motor
speed control.
SPI (Serial Periferal Interface)
INTRODUCTION TO SPI COMMUNICATION

• SPI is a common communication protocol used by many different devices. For example, SD card
modules, RFID card reader modules, and 2.4 GHz wireless transmitter/receivers all use SPI to
communicate with microcontrollers.

Raspberry Pi hardware supports speeds from


500 kHz to 32 MHz .
▪ Physically connect the Raspberry Pi
hardware to one or two SPI devices.
▪ Connect the SCLK, MOSI, and MISO pins to
their counterparts on the SPI devices.
▪ Connect the CE0 pin on Raspberry Pi
hardware to the CE pin on one SPI device
and Connect the CE1 pin on Raspberry Pi
hardware to the CE pin on other SPI device.
• One unique benefit of SPI is the fact that data can be transferred without interruption. Any
number of bits can be sent or received in a continuous stream.
HOW SPI WORKS?
• The clock signal synchronizes the output of data bits from the master to the sampling of bits
by the slave.
• Devices communicating via SPI are in a master-slave relationship.
• The master is the controlling device (usually a microcontroller), while the slave (usually a
sensor, display, or memory chip) takes instruction from the master.
• SPI is a single-master communication protocol. This means that one central device initiates
all the communications with the slaves.
• When the SPI master wishes to send data to a slave and/or request information from it, it
selects slave by pulling the corresponding CE line low and it activates the clock signal at a
clock frequency usable by the master and the slave.
• The master generates information onto MOSI line while it samples the MISO line.
STEPS OF SPI DATA TRANSMISSION
2. The master switches the SS/CS pin to a low
1. The master outputs the clock signal: voltage state, which activates the slave:

3. The master sends the data one bit at a time to 4. If a response is needed, the slave returns
the slave along the MOSI line. The slave reads the data one bit at a time to the master
bits as they are received: along the MISO line. The master reads the
bits as they are received:
Advantages and Disadvantages of SPI Protocol
ADVANTAGES
• No start and stop bits, so the data can be streamed continuously without
interruption
• No complicated slave addressing system like I2C
• Higher data transfer rate than I2C (almost twice as fast)
• Separate MISO and MOSI lines, so data can be sent and received at the same
time.

DISADVANTAGES
• Uses four wires (I2C and UARTs use two)
• No acknowledgement that the data has been successfully received (I2C has this)
• No form of error checking like the parity bit in UART
• Only allows for a single master
I2C (Inter IC Interface)
• With I2C, you can connect multiple slaves to a single master (like SPI) and you can have
multiple masters controlling single, or multiple slaves.
• This is really useful when you want to have more than one microcontroller logging data to a
single memory card or displaying text to a single LCD.
• I²C is a multi-master protocol that uses 2 signal lines.
– The two I²C signals are called ‘serial data’ (SDA) and ‘serial clock’ (SCL). There is no need
of chip select (slave select) or arbitration logic.
– Virtually any number of slaves and any number of masters can be connected onto these
2 signal lines and communicate between each other using a protocol that defines:
• 7-bits slave addresses: each device connected to the bus has got such a unique
address.
• Data divided into 8-bit bytes.
• A few control bits for controlling the communication start, end, direction and for an
acknowledgment mechanism.
• The data rate has to be chosen between 100 kbps, 400 kbps and 3.4 Mbps, respectively called
standard mode, fast mode and high speed mode. Some I²C variants include 10 kbps (low speed mode)
and 1 Mbps (fast mode +) as valid speeds.
• Physically, the I²C bus consists of the 2 active wires SDA and SCL and a ground connection. The active
wires are both bi-directional.
• The I2C protocol specification states that the IC that initiates a data transfer on the bus is considered
the Bus Master. Consequently, at that time, all the other ICs are regarded to be Bus Slaves.
HOW I2C WORKS

1. First, the master will issue a START condition. This acts as an ‘Attention’ signal to all of the connected devices. All
ICs on the bus will listen to the bus for incoming data.
2. Then the master sends the ADDRESS of the device it wants to access, along with an indication whether the
access is a Read or Write operation (Write in our example).
3. Having received the address, all IC’s will compare it with their own address. If it doesn’t match, they simply wait
until the bus is released by the stop condition. If the address matches, however, the chip will produce a
response called the ACKNOWLEDGE signal.
4. Once the master receives the acknowledge, it can start transmitting or receiving DATA.
5. When all is done, the master will issue the STOP condition. This is a signal that states the bus has been released
and that the connected ICs may expect another transmission to start any moment.
6. When a master wants to receive data from a slave, it proceeds the same way, but sets the RD/nWR bit at a
logical one. Once the slave has acknowledged the address, it starts sending the requested data, byte by byte.
After each data byte, it is up to the master to acknowledge the received data.
ADVANTAGES AND DISADVANTAGES OF I2C
ADVANTAGES
• Only uses two wires
• Supports multiple masters and multiple slaves
• ACK/NACK bit gives confirmation that each frame is transferred successfully
• Hardware is less complicated than with UARTs

DISADVANTAGES
• Slower data transfer rate than SPI
• The size of the data frame is limited to 8 bits
• More complicated hardware needed to implement than SPI
WAMP - AutoBahn for IoT
WAMP (Web Application Messaging Protocol)
➢ WAMP (Web Application Messaging Protocol) is a sub-protocol of
WebSocket which provides the messaging patterns:
• Publish-Subscribe, and
• Remote Procedure call (RPC)

➢ WAMP enables distributed application architectures where the


application components are distributed on multiple nodes and
communicate with messaging patterns provided by WAMP.
➢ WebSocket is a computer communication protocol, providing full-
duplex communication channels over a single TCP connection.
➢ A distributed system is a system whose components are located on
different networked computers, which communicate and coordinate their
actions by passing messages to one another. The components interact with
one another in order to achieve a common goal.
➢ Remote Procedure Call (RPC): In distributed computing, RPC is done when a
computer program causes a procedure (subroutine) to execute on another
computer on a shared network,
▪ It is coded as if it were a normal (local) procedure call, without the
programmer explicitly coding the details for the remote interaction.
▪ This is a form of client–server interaction (caller is client, executor is
server)
➢ Application components: App components are the essential building blocks of an
Android app. Each component is an entry point through which the system or a user
can enter your app.

Components Description
Activities They dictate the UI and handle the user interaction to the smart
phone screen
Services They handle background processing associated with an
application.
Broadcast Receivers They handle communication between Android OS and
applications.
Content Providers They handle data and database management issues.
Feature of WAMP protocol- Loosely coupled:
WAMP provides unified Application Routing for application communication:
• routing of events in the Publish & Subscriber pattern and
• routing of calls in the Remote Procedure Call pattern
between applications components in one protocol.

Strong coupled:
Lets take the old “client-server” model. In the client-server model, a remote procedure call goes
directly from the Caller to the Callee:

Caller Callee

Remote procedure calls in the Client-Server model


In the client-server model, a Caller needs to have knowledge about where the Callee resides and
how to reach it. This introduces a strong coupling between Caller and Callee. Which is bad, because
applications can quickly become complex.
Publish-Subscriber (PubSub) Model

▪ The problems coming from strong coupling


between application components were Broker
recognized and this lead to the publish-
subscribe model.
▪ A Broker keeps a book of subscriptions: who is
currently subscribed on which topic. Publisher Subscriber
▪ The act of determining receivers of
information (independently of the A Broker decouples Publishers and Subscribers
information submitted) and forwarding the
information to receivers is called Routing.
Routed Remote Procedure Call (rRPC) Model
▪ WAMP translates the benefits of loose coupling
to RPC. Dealer
▪ Different from the client-server model, WAMP
also decouples Callers and Callees by introducing
an intermediary, the Dealer
▪ Similar to a Broker’s role with PubSub, Caller Callee
the Dealer is responsible for routing a call
originating from the Caller to the Callee and route Remote procedure calls in the Dealer model
back results or errors vice-versa.
▪ Both do not know about each other: where the
peer resides and how to reach it. This knowledge
is encapsulated in the Dealer.
How rRPC works with WAMP?
1. With WAMP, a Callee registers a procedure at a Dealer under an abstract name: an
URI identifying the procedure.
2. When a Caller wants to call a remote procedure, it talks to the Dealer and only
provides the URI of the procedure to be called plus any call arguments.
3. The Dealer will look up the procedure to be invoked in its book of registered
procedures. The information from the book includes where the Callee implementing
the procedure resides, and how to reach it.
4. In effect, Callers and Callees are decoupled, and applications can use RPC and still
benefit from loose coupling.
Component based Brokers, Dealers and Routers
• What if combine a Broker (for Publish & Subscribe) and a Dealer (for routed Remote
Procedure Calls)?
• When a Broker and a Dealer are combined then we get what WAMP calls a Router:

Router = Broker + Dealer

A Router combines a Broker and a Dealer

• A Router is capable of routing both calls and events, and hence can support flexible,
decoupled architectures that use both RPC and PubSub.
Example:
WAMP Router
Imagine to have a small embedded
device like an Arduino uno with Dealer Broker
sensors (like a temperature sensor) and
actuators (like a light or motor)
connected. 1 2
We want to integrate the device into
an overall system with
• user facing frontend to control the UI or UI or
Actuator Sensor
actuators, and Backend Backend
• continuously process sensor values in a
Caller Callee Publisher Subscriber
backend component.
Embedded Device
Using WAMP, we can have:
WAMP in an IoT application
a) a browser-based UI,
b) the embedded device and Fig. Switching on a light on the device from the browser-based UI is
c) our backend talk to each other in real- naturally done by calling a remote procedure on the device (1) and the
time sensor values generated by the device continuously are naturally
transmitted to the backend component (and possibly others) via publish
& subscribe (2).
WAMP - Concepts
• Transport: Transport is channel that connects two peers.
• Session: Session is a conversation between two peers that runs over a transport.
• Client: Clients are peers that can have one or more roles. In publish-subscribe model client can have
following roles:
▪ Publisher: Publisher publishes events (including payload) to the topic maintained by the Broker.
▪ Subscriber: Subscriber subscribes to the topics and receives the events including the payload.
In rRPC model client can have following roles:
▪ Caller: Caller issues calls to the remote procedures along with call arguments.
▪ Callee: Callee executes the procedures to which the calls are issued by the caller and returns the
results back to the caller.
• Router: Routers are peers that perform generic call and event routing.
In publish-subscribe model Router has the role of a Broker:
▪ Broker: Broker acts as a router and routes messages published to a topic to all subscribers subscribed
to the topic.
In RPC model Router has the role of a Dealer:
▪ Dealer: Dealer acts a router and routes RPC calls from the Caller to the Callee and routes results from
Callee to Caller.
• Application Code: Application code runs on the Clients (Publisher, Subscriber, Callee or Caller).
WAMP Session between Client and Router

Client Router

Roles Roles
Publisher
Transport Dealer
Subscriber
Session

Caller
Broker
Callee
WAMP WebSocket Protocol
Publish-Subscribe messaging using WAMP

Client Server Client

Client Process Server Process Client Process


WAMP App WAMP-WebSocket WAMP-WebSocket WAMP App
Session Communication WAMP Router Communication Session
Session
App Code Message published Subscriber App Code
to topic receives Message
Benefits of using WAMP Protocol
• Using WAMP one can build distributed systems out of application components which are loosely
coupled and communicate in (soft) real-time.
• One protocol fulfilling “all” application communication needs.
• WAMP is easy to use, simple to implement and based on modern Web standards: WebSocket,
JSON and URIs.
• Language independent: WAMP was designed with first-class support for different languages in
mind. Nothing in WAMP is specific to a single programming language.
As soon as a programming language has a WAMP implementation, it can talk to application
components written in any other language with WAMP support.
Introduction to Cloud Storage Models

Xively Cloud for IoT


Why the cloud?
❑ IoT is about DATA sensed and transmitted from OBJECTS.
❑ What are the numbers involved in such paradigm?
▪ IPV6 can covers every IoT device
▪ Recent estimates: 4.4 zettabytes (10^21 B) of IoT data by 2020!
❑ How to manage such a massive amount of data?
▪ Go to the cloud!

Desired features
▪ Easily connect devices to the cloud
▪ Store/retrieve sensor data in the cloud
▪ Make decisions in the cloud and analyze data
▪ Visualize/share data
▪ Actuate from the cloud
Cloud Services
SaaS PaaS IaaS
Provid Complete software Ability to develop Ability to provision
es the application or UI to and deploy computing and
user application itself. application in the storage resources.
cloud using tools, These resources are
API, software provided to user in
libraries and the form of virtual
services provided machine instances
by CSP. and virtual storage.
Cloud Underlying cloud Underlying cloud Underlying cloud
service infrastructure infrastructure infrastructure
provid including servers, including servers,
er networks, OS, networks, OS and
(CSP) storage and storage.
manag application
es software.
Cloud Platforms for IoT
• Microsoft Azure IoT Suite
• Google Cloud's IoT Platform
• IBM Watson IoT Platform
• AWS IoT Platform
• Cisco IoT Cloud Connect
• Salesforce IoT Cloud
• Kaa IoT Platform
• Thingspeak IoT Platform
• Xively Cloud
Xively Cloud for IoT
• Created in 2007, acquired in 2011 by LogMeln
• Recently acquired by Google.
• Xively is a commercial Platform-as-a-Service which provides tools and
services for developing IoT solutions.
• IoT developers can focus on front-end infrastructures and devices for IoT
that generates the data, while the backend data collection infrastructure is
managed by Xively.

Xively platform comprises of:


1. A message bus for real-time message management and routing
2. Data services for time series archiving.
3. Directory services that provides a searchable directory of objects.
Directory services identify every resource on the network
4. Business services for device provisioning and management
• Xively is an enterprise platform for building, managing, and deriving
business value from connected products.
• Xively is a system for deploying IoT applications on the cloud. Xively is
basically a data collection, management, and distribution infrastructure. It
also provides APIs to connect and develop IoT applications.
• The following diagram shows a conceptual Architecture for a connected
product solution.
Xively Main services:
• Real-Time Messaging - Xively connects products and applications, while
automatically scaling for you as you grow.
• Security - Every message is fully encrypted and devices are protected
from outside attack. Xively uses your device-user relationship models to
authorize data access.
• Stores data from device sensors from all over the world
• Serves data to other entities in other parts of the world
• Data visualization for data of connected sensors to IoT devices.
• Graphical plots of collected data.
• Generates alerts.
• Access to historical data
• Generates feeds which can be real-world objects of own or others.
Xively main features
▪ Interoperability: extensive support for major languages and platforms.
▪ Simple management
▪ Scalability and Performance
▪ Security: HTTPS, SSL

Xively HTTP based APIs


▪ Easy to implement on device hardware acting as clients to Xively web
services
▪ APIs connect to the web service and send data.
▪ APIs provides services for logging, sharing and displaying sensor data of
all
Xively Support
▪ The platform supports the REST, WebSockets and MQTT protocols and
connects the devices to Xively Cloud Services.
▪ Native SDKs (Software Development Kit) for Android, Arduino, Java, PHP,
Ruby, and Python languages
▪ Developers can use the workflow of prototyping, deployment and
management through the tools provided at Xively

Xively Methods for IoT Devices Data


▪ Concept of users, feeds, data streams, data points and triggers
▪ Data feed typically a single location (e.g. a device or devices network),
▪ Data streams are of individual sensors associated with that location (for
example, ambient lights, temperatures, power consumption).
▪ Pull or Push (Automatic or Manual Feed)
Xively Data formats and Structures
▪ Number of data formats and structures enable the interaction, data
collection and services
▪ Support exists for JSON , XML and CSV
▪ Structures: Tabular, spreadsheet, Excel, Data numbers and Text with a
comma-separated values in

Xively Uses in IoT/M2M


▪ Private and Public Data Access
▪ Data streams, Data points and Triggers
▪ Creating and Managing Feeds
▪ Visualizing Data
Start using Xively:
1. First register for a developer account on https://xively.com/.
2. Create development devices on Xively
3. Xively will create Feed-ID and an API Key to connect to the new
device.
a) Xively FEEDS
• A feed represents an environment. (i.e. an office, a house, a
forest, etc.)
• It’s a collection of channels or datastreams defined for a device
and the associated Metadata.
• Required attributes: Title
• Other attributes: ID, status, location, description.
b) API Keys: API Keys are used to provide different levels of
permissions.
• IoT devices can send data to a channel using Xively APIs.
Xively Channels
• Xively devices/Feed have one or more Channels. Each channel enables
bi-directional communication between IoT Devices and Xively cloud.
• A channel represents an individual sensor/device stream within an
environment
• Required attributes: Stream ID, Current Value
• Other attributes: Tags, units, unit symbol, min value, max value, etc.

Triggers
1. For each channel, one or more Triggers can be created.
2. A trigger specification includes:
a) a channel to which the trigger corresponds,
b) Trigger condition and
c) an HTTP POST URL.
3. Triggers are used for integration with third party applications.
Example: Post a tweet when temperature is greater than 30°. Minimum interval
between two posts: 5 seconds
Creating Feeds and Channels
• Feeds and channels can be created directly from the web
platform
• Alternatively, they can be created with an HTTP POST request
– Headers and body of the HTTP requests specify information on the
feed to be created

Updating channels
• Similarly, channels may be updated with fresh data in
different ways:
– Directly, with HTTP requests
– Indirectly, with libraries
Device
Product Template Metadata

Device
Device
Device
Basic operations
• Xively libraries supports RESTful APIs, Sockets and MQTT
protocols for connecting IoT devices to Xively cloud.
• Xively API enables to create/modify/retrieve feeds and
datastreams.
• All operations are done via RESTful HTTP commands
– All resources are uniquely addressable through URL
– All resources can be manipulated (create, read, update, delete) via
HTTP requests (POST, GET, PUT, DELETE)
– The data for/from resources is transferred through well-known
representations (HTML, JSON)
• Create/delete/update a Feed
• Create/delete/update a Channel
• List/view a Feed
• Operations may be performed either with HTTP requests or
by using the provided libraries.
Django Framework
A High Level Python Application
Framework
Django Framework:
• Django Framework is an open source web application framework for developing Web
Applications in Python.
• Framework in general is a collection of solutions, packages and best practices that allows
development of web apps and dynamic websites.
• It provides generic things that almost all applications need.
It's like building a house. First you put up a wooden frame that outlines the structure of the
house. That's the framework. Then you build the house on the framework: you add walls,
windows, doors, etc.

Why Django?
• With Django, one can take Web applications from concept to launch in a matter of hours.
• Django takes care of much of the hassle of Web development, so that one can focus on
writing the app without needing to reinvent the wheel.
• It’s free and open source.
Features of Django:
• Ridiculously fast.
Django was designed to help developers take applications from concept to completion as quickly
as possible.
• Fully loaded.
Django handles all the common Web development tasks. Django takes care of user authentication,
content administration, site maps, and many more tasks — right out of the box.
• Reassuringly secure.
Django takes security seriously and helps developers avoid many common security mistakes, such
as SQL injection, cross-site scripting, cross-site request forgery and click-jacking. Its user
authentication system provides a secure way to manage user accounts and passwords.
• Exceedingly scalable.
Some of the busiest sites on the planet use Django’s ability to quickly and flexibly scale to meet
the heaviest traffic demands.
• Incredibly versatile.
Companies, organizations and governments have used Django to build all sorts of things — from
content management systems to social networks to scientific computing platforms.
• Frontend web designing:
– e.g. HTML, CSS (Cascading Style Sheets), Javascript
• Backend development:
– e.g. Servlet, Javascript, PHP (Personal Home Page), ASP (Active Server
Page), Python
Django

Django is based on MVT architecture:


The MVT design pattern separates the code into three parts.

MVT

Model View Template


Roles of Model, Template and View
1. Model:
✓ Model acts as a definition of stored DATA and handles the interactions with the
database.
✓ It contains the code responsible for dealing with data and databases.

2. Template:
✓ Template is simply an HTML Page.
✓ Templates are used to specify a structure for an output. Data can be populated in a
template using placeholders. It defines how the data is presented.
✓ An example is a Generic list view that we can use to display a set of records from the
database.

3. View:
✓ View ties the model to the template.
✓ The view is where you write the code that actually generates the web pages.
✓ View determines what data is to be displayed, retrieves the data from the database
and passes the data to the template.
MVC- Model- View- Controller
Model View Controller, known as MVC separates the code as three components. MVC
separates the logic and presentation layer from each other.
MVC architecture has been used for designing web applications as well as mobile apps.

1. Model – This layer deals with data-related logic. For example, it can retrieve, change
and save data to the database.

2. View – It can be called as the presentation layer. It is responsible for collecting data from
the model or user and presenting it. In a web application, everything that is displayed in
the browser falls under View.

3. Controller – It controls the data flow and interaction between view and model. For
example, a controller, based on a request or action, will collect data from a database
with the help of Model and send it to the user through Views.
Difference between MVC and MVT
1. The main difference between MVC and MVT is that in a Model View Controller
pattern, we have to write all the control specific code. But in an MVT, the
controller part is taken care of by the framework itself.
2. The classic MVC pattern works by managing the state of an application. When a
user performs an action or makes a request, an action in the Controller is called.
The Controller then either tells Model to make changes and update the View or
returns a View based on a Model. Hence we can say that the View is controlled
by the Controller and Model.
However, MVT takes a slightly different approach. When a user makes an HTTP
request, the corresponding view performs a query on the Model and collects
the result set from the Model. The View then fills the result in a template and
sends it to the user.
3. Unlike in MVC, view is not coupled with a Model. This makes MVT loosely
coupled and easy-to-modify.
MVT Pattern: Model-View-Template

• A template is an HTML file mixed with DTL (Django Template Language).


• Django takes care of the Controller part, which is the code that controls the interaction
between the other two parts, the Model and View.
Serving a Request for a Website by Django

What happens when server receives a request for a website?


1. The request is passed to Django and Django tries to analyze this request.
2. The URL resolver tries to match the URL against a list of patterns. It performs this match
from top to bottom.
3. If it finds a match then it passes the request to the view, which is the associated function.
4. The function view can check if the request is allowed.
5. It also generates a response, and then Django sends it to the user’s web browser.

MVT Pattern:
When a user requests for a resource, Django acts as a controller and checks if it is available. If
the URL maps, the View interacts with the Model and renders a Template. Django sends back
a Template to the user as a response.
Install Django
/> py -m pip install Django
/> py -m pip install Django==3.1.3
Creating a Project

...\> django-admin startproject mysite

What startproject created:


mysite/
manage.py
db.sqlite3
mysite/
__init__.py
settings.py
urls.py
wsgi.py
mysite/
manage.py
db.sqlite3
mysite/
__init__.py
settings.py
urls.py
wsgi.py

__init__.py: Python pakage.


manage.py: contains an array of functions for managing the site.
This script lets us interact with our project using the command line. Facilities
include starting up the server and syncing to the database.
db.sqlite3: This is the database file for your project and has extension .sqlite3.

settings.py: contains website’s settings like database configuration details.


urls.py: contains URL patterns that map URLs to pages.
This holds links in your project and the function(s).
wsgi.py: This deploys our project over WSGI and helps the app communicate with the web
server. WSGI stands for Web Server Gateway Interface.
The development server
• Django comes with built-in, lightweight Web server that can be used for development
purposes.
• Let’s verify your Django project works. Change into the outer mysite directory and run the
following commands:

...\> py manage.py runserver


• When Django development server is started the default project can be viewed at the URL:
http://localhost:8000.

Changing the port:


By default, the runserver command starts the development server on the internal IP at port
8000.
If you want to change the server’s port, pass it as a command-line argument. For instance, this
command starts the server on port 8080:

...\> py manage.py runserver 8080


Creating an Application
Projects vs. Apps
An app is a Web application that does something – e.g., a Weblog system, a database of public
records or a simple poll app.
A project is a collection of configuration and apps for a particular website. A project can contain
multiple apps. An app can be in multiple projects.

..\ mysite> py manage.py startapp polls


polls/
__init__.py
admin.py • Migrations - This holds another __init__.py file.
apps.py • __init__.py - This is a Python package.
migrations/
• admin.py - This lets us make the app modifiable in the admin
__init__.py
models.py interface.
tests.py • apps.py - This holds the names of all your applications.
views.py • models.py - This holds all application models.
• tests.py - This holds unit tests for the project.
• views.py - This holds the application views for the project
Writing the first view
Let’s write the first view. Open the file polls/views.py and put the following Python code in it:

polls/views.py

from django.http import HttpResponse


def index(request):
return HttpResponse ("Hello, world. You're at the polls index.")

To call the view, we need to map it to a URL - and for this we need a URLconf.
To create a URLconf in the polls directory, create a file called urls.py.

polls/ In the polls/urls.py file include the following code:


__init__.py polls/urls.py
admin.py
apps.py from django.urls import path
migrations/ from . import views
__init__.py
models.py urlpatterns = [
tests.py path(' ', views.index, name='index'),
views.py ]
urls.py
The next step is to point the root URLconf at the polls.urls module. In mysite/urls.py, add an import
for django.urls.include and insert an include() in the urlpatterns list, so you have:

mysite/urls.py

from django.contrib import admin


from django.urls import include, path

urlpatterns = [
path('polls/', include('polls.urls')), path('admin/',
admin.site.urls),
]

The include() function allows referencing other URLconfs. Whenever Django encounters include(),
it chops off whatever part of the URL matched up to that point and sends the remaining string to
the included URLconf for further processing.
http://localhost:8000/polls/

“Hello, world. You’re at the polls index.”

which you defined in the index view

You might also like