0% found this document useful (0 votes)
173 views

Django Unit 1

This document outlines the details of a course on Python web development with Django taught by Priya Singh. It includes information about the instructor, the course syllabus divided into 5 units covering Python libraries, the Django framework, authentication, databases, and deployment. It also lists course objectives, outcomes, how the outcomes map to program outcomes, and program specific outcomes. The overall goal of the course is for students to learn how to design and build dynamic websites using the Django web framework.

Uploaded by

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

Django Unit 1

This document outlines the details of a course on Python web development with Django taught by Priya Singh. It includes information about the instructor, the course syllabus divided into 5 units covering Python libraries, the Django framework, authentication, databases, and deployment. It also lists course objectives, outcomes, how the outcomes map to program outcomes, and program specific outcomes. The overall goal of the course is for students to learn how to design and build dynamic websites using the Django web framework.

Uploaded by

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

Noida Institute of Engineering and Technology, Greater Noida

Python Web Development with


Django

Unit: I

Python libraries for web development

Priya Singh
Course Details
(Asst. Professor)
(B. Tech. 5th Sem)
CSE Department

12/23/2023 Priya Singh Python web development with Django Unit I 1


Faculty Introduction
Name Priya Singh
Qualification M. Tech. (Computer Engineering)
Designation Assistant Professor
Department Computer Science & Engineering
NIET Experience 9 months
Subject Taught Operating System, Data Structures, C Programming, Web
Technology.

Research Paper Published paper in IEEE International conference “Application of neural network for flight
simulation”(Scopus Indexed)
Published paper in IEEE International conference “New Morphological Technique for
Medical Image Segmentation”(Scopus Indexed)
Published paper in National conference on “Performance study on Morphological Based
Technique for Image Segmentation”.

12/23/2023 Priya Singh Python web development with Django Unit I 2


Evaluation Scheme

Python Web development with Django (Elective I)


Design Pattern (Elective II)

Priya Singh Python web development with Django Unit I


12/23/2023 3
Syllabus

UNIT-I: Python libraries for web development

Collections-Container datatypes, Tkinter-GUI applications, Requests-


HTTP requests, BeautifulSoup4-web scraping, Scrapy, Zappa, Dash,
CherryPy, TurboGears, Flask, Web2Py,
Bottle, Falcon, CubicWeb, Quixote, Pyramid.

12/23/2023 4
Priya Singh Python web development with Django Unit I
Syllabus

UNIT-II: Introduction to Django Framework

Understanding Django environment, Features of Django and Django


architecture, MVC &MTV, Urls and Views, Mapping the views to URLs,
Django Template, Template inheritance Django Models, Creating model for
site, Converting the model into a table, Fields in Models, Integrating
Bootstrap into Django, Creating tables, Creating grids, Creating carousels.

12/23/2023 Priya Singh Python web development with Django Unit I 5


Syllabus

UNIT-III: Integrating Accounts & Authentication on Django

Introduction to Django Authentication System, Security Problem & Solution


with Django Creating Registration Form using Django, Adding Email Field In
Forms, Configuring email settings, Sending emails with Django, Adding Grid
Layout On Registration Page, Adding Page Restrictions, Login Functionality Test
and Logout.

Priya Singh Python web development with Django Unit I


12/23/2023 6
Syllabus

UNIT-IV: Connecting SQLite with Django

Database Migrations, Fetch Data From Database, Displaying Data On


Templates, Adding Condition On Data, Sending data from url to view,
Sending data from view to template, Saving objects into database,
Sorting objects, Filtering objects, Deleting objects, Difference between
session and cookie, Creating sessions and cookies in Django.

Priya Singh Python web development with Django Unit I


12/23/2023 7
Syllabus

UNIT-V: Deploying Django Web Application on Cloud

Creating a functional website in Django, Four Important Pillars to


Deploy, Registering on Heroku and GitHub, Push project from Local
System to GitHub, Working with Django Heroku
Working with Static Root, Handling WSGI with gunicorn, Setting up
Database & adding users

Priya Singh Python web development with Django Unit I


12/23/2023 8
Branch Wise Application

1. Real time web analytics


2. Digital Advertising
3. E-Commerce
4. Publishing
5. Massively Multiplayer Online Games
6. Backend Services and Messaging
7. Project Management & Collaboration
8. Real time Monitoring Services
9.Live Charting and Graphing
10. Group and Private Chat

Priya Singh Python web development with Django Unit I


12/23/2023 9
Course Objective

In this semester, the students will

Study how to shows relationships and interactions between frontend &backend

Study to speed up the development process by providing well-tested, proven


development/design paradigms.

Select a specific framework for the development of a given website or webapp.

Analyzing and creating a functional website in Django and deploy Django Web
Application on Cloud.

Priya Singh Python web development with Django Unit I


12/23/2023 10
Course Outcomes (COs)

At the end of course, the student will be able to:


CO1 : Apply the knowledge of python programing that are vital in understanding Django application

CO2 : Demonstrate web application framework (Django) to design and implement dynamic website

CO3 : Implementing and analyzing the concept of Integrating Accounts & Authentication on Django

CO4 : Understand the impact of web designing by database connectivity with SQLite

CO5 : Analyzing & Creating a functional website in Django and deploy Django Web Application Cloud

12/23/2023 Priya Singh Python web development with Django Unit I 11


Program Outcomes (POs)

Engineering Graduates will be able to:

PO1 : Engineering Knowledge

PO2 : Problem Analysis

PO3 : Design/Development of solutions

PO4 : Conduct Investigations of complex problems

PO5 : Modern tool usage

PO6 : The engineer and society


12/23/2023 Priya Singh Python web development with Django Unit I 12
Program Outcomes (POs)

Engineering Graduates will be able to:

PO7 : Environment and sustainability

PO8 : Ethics

PO9 : Individual and teamwork

PO10 : Communication

PO11 : Project management and finance

PO12 : Life-long learning


12/23/2023 Priya Singh Python web development with Django Unit I 13
COs - POs Mapping

CO.K PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12

CO1 2 2 2 3 3 - - - - - - -

CO2 3 2 3 2 3 - - - - - - -

CO3 3 2 3 2 3 - - - - - - -

CO4 3 2 3 2 3 - - - - - - -

CO5 3 2 3 3 3 - - - - - - -

AVG 2.8 2.0 2.8 2.4 3.0 - - - - - - -

12/23/2023 Priya Singh Python web development with Django Unit I 14


Program Specific Outcomes(PSOs)
Program Specific
S. No. PSO Description
Outcomes (PSO)

1 PSO1 Understand to shows relationships and interactions


between classes or objects of a pattern.

2 PSO2 Study to speed up the development process by


providing well-tested, proven development

3 PSO3 Select a specific design pattern for the solution of a


given design problem

Create a catalogue entry for a simple design pattern


4 PSO4 whose purpose and application is understood.

12/23/2023 Priya Singh Python web development with Django Unit I 15


COs - PSOs Mapping

CO.K PSO1 PSO2 PSO3 PSO4

CO1 3 - - -

CO2 3 3 - -

CO3 3 3 - -

CO4 3 3 - -

CO5 3 3 - -

12/23/2023 Priya Singh Python web development with Django Unit I 16


Program Educational Objectives (PEOs)

Program Educational
PEOs Description
Objectives (PEOs)
To have an excellent scientific and engineering breadth so as to comprehend,
PEOs analyze, design and provide sustainable solutions for real-life problems using state-
of-the-art technologies.

To have a successful career in industries, to pursue higher studies or to support


PEOs entrepreneurial endeavors and to face the global challenges.

To have an effective communication skills, professional attitude, ethical values and a


PEOs desire to learn specific knowledge in emerging trends, technologies for research,
innovation and product development and contribution to society.

To have life-long learning for up-skilling and re-skilling for successful professional
PEOs career as engineer, scientist, entrepreneur and bureaucrat for betterment of society.

12/23/2023 Priya Singh Python web development with Django Unit I 17


Result Analysis(Department Result & Subject Result & Individual result

Name of the faculty Subject code Result % of clear passed

12/23/2023 Priya Singh Python web development with Django Unit I 18


Pattern of Online External Exam Question Paper (100 marks)

12/23/2023 Priya Singh Python web development with Django Unit I 19


Pattern of Online External Exam Question Paper (100 marks)

12/23/2023 Priya Singh Python web development with Django Unit I 20


Pattern of Online External Exam Question Paper (100 marks)

12/23/2023 Priya Singh Python web development with Django Unit I 21


Pattern of Online External Exam Question Paper (100 marks)

12/23/2023 Priya Singh Python web development with Django Unit I 22


Pattern of Online External Exam Question Paper (100 marks)

12/23/2023 Priya Singh Python web development with Django Unit I 23


Prerequisite / Recap

• Student should have knowledge of HTML , CSS and JavaScript .

• Students should have good knowledge of Python Programming and

Python coding experience.

• knowledge of Computer and basic skill.

• Good problem solving Skill .

12/23/2023 Priya Singh Python web development with Django Unit I 24


Brief Introduction about the Subject with videos

YouTube /other Video Links


• https://youtu.be/eoPsX7MKfe8?list=PLIdgECt554OVFKXRpo_kuI0XpUQKk0ycO

• https://youtu.be/tA42nHmmEKw?list=PLh2mXjKcTPSACrQxPM2_1Ojus5HX88ht7

• https://youtu.be/8ndsDXohLMQ?list=PLDsnL5pk7-N_9oy2RN4A65Z-PEnvtc7rf

• https://youtu.be/QXeEoD0pB3E?list=PLsyeobzWxl7poL9JTVyndKe62ieoN-MZ3

• https://youtu.be/9MmC_uGjBsM?list=PL3pGy4HtqwD02GVgM96-V0sq4_DSinqvf

12/23/2023 Priya Singh Python web development with Django Unit I 25


Unit I Content

• Collections-Container datatypes,
• Tkinter-GUI applications,
• Requests-HTTP requests,
• BeautifulSoup4-web scraping,
• Scrapy, Zappa, Dash, CherryPy, TurboGears,
• Flask, Web2Py,
• Bottle, Falcon, CubicWeb, Quixote, Pyramid.

12/23/2023 Priya Singh Python web development with Django Unit I 26


Unit I Objective

In Unit I, the students will be able to find


• Definitions of terms and concepts.
• The idea of a python Library .
• The origins BeautifulSoup4-web scraping.
• How Bottle framework works.
• Brief introduction of Falcon, CubicWeb, Quixote, Pyramid

Priya Singh Python web development with Django Unit I


12/23/2023 27
Topic Objective

Topic : Collection— Container datatypes

• In this topic, the students will gain , The idea of this module
implements specialized container datatypes providing alternatives
to Python’s general purpose built-in containers,

12/23/2023 Priya Singh Python web development with Django Unit I 28


Counter container
A Counter is a container that keeps track of how many times equivalent
values are added. It can be used to implement the same algorithms for
which bag or multiset data structures are commonly used in other
languages.
Initializing:
Counter supports three forms of initialization. Its constructor can be called
with a sequence of items, a dictionary containing keys and counts, or using
keyword arguments mapping string names to counts.
import collections
print collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])
print collections.Counter({'a':2, 'b':3, 'c':1})
print collections.Counter(a=2, b=3, c=1)
The results of all three forms of initialization are the same.
12/23/2023
Priya Singh Python web development with Django Unit I
29
Defaultdict

The standard dictionary includes the method setdefault() for retrieving a


value and establishing a default if the
value does not exist. By contrast, defaultdict lets the caller specify the
default up front when the container initialized.
import collections
def default_factory():
return 'default value'
d = collections.defaultdict(default_factory, foo='bar')
print 'd:', d
print 'foo =>', d['foo']
print 'bar =>', d['bar']
This works well as long as it is appropriate for all keys to have the same
default.
12/23/2023
Priya Singh Python web development with Django Unit I
30
Deque
A double-ended queue, or deque, supports adding and removing
elements from either end. The more commonly used stacks and queues
are degenerate forms of deques, where the inputs and outputs are
restricted to a single end.
import collections
d = collections.deque('abcdefg')
print 'Deque:', d
print 'Length:', len(d)
print 'Left end:', d[0]
print 'Right end:', d[-1]
d.remove('c')print 'remove(c):', d
12/23/2023 Priya Singh Python web development with Django Unit I 31
Deque

Since deques are a type of sequence container, they support some of


the same operations that lists support, such as examining the contents
with __getitem__(), determining length, and removing elements from
the middle by matching identity.
$ python collections_deque.py
Deque: deque(['a', 'b', 'c', 'd', 'e', 'f', 'g'])
Length: 7
Left end: a
Right end: g
remove(c): deque(['a', 'b', 'd', 'e', 'f', 'g'])

12/23/2023 Priya Singh Python web development with Django Unit I 32


Ordered Dict
An OrderedDict is a dictionary subclass that remembers the order in
which its contents are added.
import collections
print 'Regular dictionary:‘
A regular dict does not track the insertion order, and iterating over it
produces the values in an arbitrary order. In an OrderedDict, by
contrast, the order the items are inserted is remembered and used
when creating an iterator.
$ python collections_ordereddict_iter.py
Regular dictionary:a Ac Cb Be Ed D
OrderedDict:a Ab Bc Cd De E

12/23/2023 Priya Singh Python web development with Django Unit I 33


OrderedDict(continues….)

A regular dict does not track the insertion order, and


iterating over it produces the values in an arbitrary order.
In an OrderedDict, by contrast, the order the items are
inserted is remembered and used when creating an
iterator.
$ python collections_ordereddict_iter.py
Regular dictionary:
aA cC bB eE dD
OrderedDict: a A b B cC dD eE

12/23/2023 Priya Singh Python web development with Django Unit I 34


Python - GUI Programming (Tkinter)
Tkinter − Tkinter is the Python interface to the Tk GUI toolkit shipped with
Python. We would look this option in this chapter.
Tkinter Programming
Tkinter is the standard GUI library for Python. Python when combined with
Tkinter provides a fast and easy way to create GUI applications. Tkinter provides
a powerful object-oriented interface to the Tk GUI toolkit.
Creating a GUI application using Tkinter is an easy task. All you need to do is
perform the following steps −
Import the Tkinter module.
Create the GUI application main window.
Add one or more of the above-mentioned widgets to the GUI application.
Enter the main event loop to take action against each event triggered by user.
12/23/2023 Priya Singh Python web development with Django Unit I 35
Python - GUI Programming (Tkinter)(continue….)
Example
#!/usr/bin/pythonimport Tkintertop = Tkinter.Tk()# Code to add
widgets will go here...top.mainloop()
This would create a following window –

commonly called widgets.


There are currently 15 types of widgets in Tkinter. We present these
widgets as well as a brief description in the following table −
Sr.No. Operator & Description
1 Button
The Button widget is used to display buttons in your application.
2 Canvas
The Canvas widget is used to draw shapes, such as lines, ovals,
polygons and rectangles, in your application.

12/23/2023 Priya Singh Python web development with Django Unit I 36


Python - GUI Programming (Tkinter)(continue….)
Checkbutton
3 The Checkbutton widget is used to display a number of options as checkboxes. The user
can select multiple options at a time.
Entry -----The Entry widget is used to display a single-line text field for accepting values
4
from a user.

5 Frame ----The Frame widget is used as a container widget to organize other widgets.

Label
6 The Label widget is used to provide a single-line caption for other widgets. It can also
contain images.

7 Listbox --- The Listbox widget is used to provide a list of options to a user.

12/23/2023 Priya Singh Python web development with Django Unit I 37


Python - GUI Programming (Tkinter)(continue….)

Geometry Management

All Tkinter widgets have access to specific geometry management methods,


which have the purpose of organizing widgets throughout the parent widget area.
Tkinter exposes the following geometry manager classes: pack, grid, and place.
•The pack() Method − This geometry manager organizes widgets in blocks before
placing them in the parent widget.
•The grid() Method − This geometry manager organizes widgets in a table-like
structure in the parent widget.
•The place() Method − This geometry manager organizes widgets by placing them
in a specific position in the parent widget.

12/23/2023 Priya Singh Python web development with Django Unit I 38


HTTP - Requests
GET and POST requests using Python
This post discusses two HTTP (Hypertext Transfer Protocol) request methods GET and
POST requests in Python and their implementation in python.
What is HTTP
HTTP is a set of protocols designed to enable communication between clients and
servers. It works as a request-response protocol between a client and server.
A web browser may be the client, and an application on a computer that hosts a
website may be the server.
So, to request a response from the server, there are mainly two methods:
1.GET : to request data from the server.
2.POST : to submit data to be processed to the server.

12/23/2023 Priya Singh Python web development with Django Unit I 39


HTTP – Requests(continue…)
Here is a simple diagram which explains the basic concept of GET and POST methods.

12/23/2023 Priya Singh Python web development with Django Unit I 40


HTTP – Requests(continue…)
Now, to make HTTP requests in python, we can use several HTTP libraries like:
Httplib urllib requests

The most elegant and simplest of above listed libraries is Requests. We will be using requests
library in this article. To download and install Requests library, use following command:
pip install requests

Here are some important points to ponder upon:


When the method is GET, all form data is encoded into the URL, appended to the action URL as
query string parameters. With POST, form data appears within the message body of the HTTP
request.
In GET method, the parameter data is limited to what we can stuff into the request line (URL).
Safest to use less than 2K of parameters, some servers handle up to 64K.No such problem in
POST method since we send data in message body of the HTTP request, not the URL.
12/23/2023 Priya Singh Python web development with Django Unit I 41
HTTP – Requests(continue…)

•Only ASCII characters are allowed for data to be sent in GET


method.There is no such restriction in POST method.
•GET is less secure compared to POST because data sent is part of the
URL. So, GET method should not be used when sending passwords or
other sensitive information.

Beautiful Soup 4-web scraping


Beautiful Soup is a library that makes it easy to scrape information
from web pages. It sits atop an HTML or XML parser, providing
Pythonic idioms for iterating, searching, and modifying the parse tree.

12/23/2023 Priya Singh Python web development with Django Unit I 42


Scrapy

Scrapy is a Python framework for large scale web scraping. It gives you all the tools
you need to efficiently extract data from websites, process them as you want, and
store them in your preferred structure and format.
As diverse the internet is, there is no “one size fits all” approach in extracting data
from websites. Many a time ad hoc approaches are taken and if you start writing
code for every little task you perform, you will eventually end up creating your own
scraping framework. Scrapy is that framework.
With Scrapy you don’t need to reinvent the wheel.

2. Write your first Web Scraping code with Scrapy


We will first quickly take a look at how to setup your system for web scraping and
then see how we can build a simple web scraping system for extracting data from
Reddit website.

12/23/2023 Priya Singh Python web development with Django Unit I 43


Zappa
Zappa is a way to deploy serverless web apps on AWS Lambda.
Zappa is a very powerful open source python project which lets you build, deploy
and update your WSGI app hosted on AWS Lambda + API Gateway easily.
Zappa is a Python package that bundles up web apps written in Flask or Django and
deploys them to AWS (Amazon Web Services) Lambda.
Lambda is Amazon's function as a service (FaaS) platorm. Why is Zappa so great?
Because instead of deploying your Flask or Django web app on a cloud server, like an
AWS EC2 instance or a Digital Ocean Droplet, you can deploy your app serverless as an
AWS Lambda function.

This isn't really "serverless" (servers run AWS Lambda), but with an AWS Lambda
function, you don't have to spin up servers, install packages, make sure security
patches are up to date, and most of all: you don't have to pay for server time that
isn't used.
A cloud server has to run all the time, whether or not someone visits your website. But
an AWS Lambda function only runs when requested.

12/23/2023 Priya Singh Python web development with Django Unit I 44


Install Zappa and Flask

• Before we can deploy our web app on AWS Lambda with Zappa, first we need
to install Zappa and a web framework to build our web app with. In this
project, we are going to build a Flask app, so Flask needs to be installed too.
You can install both of these packages with pip, the Python package manager.
• Using a terminal, create a project directory called zappa_app and cd into it.
Create a virtual environment, activate it, and install Zappa and Flask.
• mkdir zappa_appcd zappa_apppython -m venv venvsource venv/bin/activate#
on windows: venv\Scripts\activatepip install flaskpip install zappa You can
verify the installation by calling two help commands at the terminal.
• flask --helpzappa --help

12/23/2023 Priya Singh Python web development with Django Unit I 45


A Simple Flask App

Next, we'll build a simple web app with Flask. This web app is super small and basic,
but it will give you an idea of how Zappa and AWS Lambda works.
Create a file called app.py in the main project directory zappa_app we created
earlier. Inside app.py, paste the following code. This super simple Flask app creates
one webpage that displays the text Yeah, that is Zappa! Zappa! Zap! Zap!. You can
modify the text between the <h1> .... </h1> tags to include any message you want.
Copy the code below into app.py.
# app.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return '<h1>Yeah, that is Zappa! Zappa! Zap! Zap!</h1>' # We only need this for
local development.if __name__ == '__main__': app.run()
12/23/2023 Priya Singh Python web development with Django Unit I 46
Zappa (continue….)

12/23/2023 Priya Singh Python web development with Django Unit I 47


Dash Framework
Dash is an open-source Python framework used for building analytical web applications. It is a
powerful library that simplifies the development of data-driven applications. It’s especially
useful for Python data scientists who aren’t very familiar with web development. Users can
create amazing dashboards in their browser using dash.
Built on top of Plotly.js, React, and Flask, Dash ties modern UI elements like dropdowns, sliders
and graphs directly to your analytical python code.
Dash apps consist of a Flask server that communicates with front-end React components using
JSON packets over HTTP requests.
Dash applications are written purely in python, so NO HTML or JavaScript is necessary.

Dash Setup
If Dash is not already installed in your terminal, then install the below mentioned Dash libraries.
As these libraries are under active development, install and upgrade then frequently. Python 2
and 3 are also supported.
pip install dash==0.23.1 # The core dash backend
pip install dash-renderer==0.13.0 # The dash front-end

12/23/2023 Priya Singh Python web development with Django Unit I 48


Dash Setup(continue….)

Dash or App Layout


Dash apps are composed of two parts. The first part is the “layout” of the app
which basically describes how the application looks like. The second part
describes the interactivity of the application.
Core Components
We can build the layout with the dash_html_components and the
dash_core_components library. Dash provides python classes for all the visual
components of the application. We can also customize our own components with
JavaScript and React.js.
import dash_core_components as dcc
import dash_html_components as html
The dash_html_components is for all HTML tags where the
dash_core_components is for interactivity built with React.js.

12/23/2023 Priya Singh Python web development with Django Unit I 49


Dash or App Layout(continue…)

Writing Simple Dash app


We will learn how to write a simple example on dash using above mentioned library
in a file dashApp.py.
# -*- coding: utf-8 -*-import dashimport dash_core_components as dccimport
dash_html_components as html app = dash.Dash()app.layout = html.Div(children=[
html.H1(children='Hello Dash'), html.Div(children='''Dash Framework: A web
application framework for Python.'''), dcc.Graph( id='example-graph',
figure={ 'data': [ {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'Delhi'},
{'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Mumbai'}, ], 'layout': {
'title': 'Dash Data Visualization' } } )]) if __name__ == '__main__':
app.run_server(debug=True)

12/23/2023 Priya Singh Python web development with Django Unit I 50


Dash or App Layout(continue…)
Writing Simple Dash app
We will learn how to write a simple example on dash using above mentioned library in a file
dashApp.py
-import dash
import dash_core_components as dcc
import dash_html_components as html
app = dash.Dash()
app.layout = html.Div(children=[ html.H1(children='Hello Dash'), html.Div(children='''Dash
Framework: A web application framework for Python.'''), dcc.Graph( id='example-
graph',
figure={ 'data': [ {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'Delhi'}, {'x':
[1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Mumbai'}, ], 'layout': { 'title': 'Dash
Data Visualization' } } )])
if __name__ == '__main__':

12/23/2023 Priya Singh Python web development with Django Unit I 51


Running the Dash app
Note the following points while running the Dash app.
(MyDjangoEnv) C:\Users\rajesh\Desktop\MyDjango\dash>python dashApp1.py

•Serving Flask app "dashApp1" (lazy loading)


•Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
•Debug mode: on
•Restarting with stat
•Debugger is active!
•Debugger PIN: 130-303-947
•Running on http://127.0.0.1:8050/ (Press CTRL+C to quit)

12/23/2023 Priya Singh Python web development with Django Unit I 52


Running the Dash app

12/23/2023 Priya Singh Python web development with Django Unit I 53


Running the Dash app
• In above program, few important points to be noted are as follows −
• The app layout is composed of a tree of “components” like html.Div and
dcc.Graph.
• The dash_html_components library has a component for every HTML tag. The
html.H1 (children = ‘Hello Dash’) component generates a <h1> Hello Dash
</h1> HTML element in your application.
• Not all components are pure HTML. The dash_core_components describe
higher-level components that are interactive and are generated with
JavaScript, HTML, and CSS through the React.js library.
• Each component is described entirely through keyword attributes. Dash is
declarative: you will primarily describe your application through these
attributes.

12/23/2023
Priya Singh Python web development with Django 54
Unit I
CherryPy
• CherryPy allows developers to build web applications in much the same way
they would build any other object-oriented Python program.

• This results in smaller source code developed in less time. It is being used in
many production websites.
• CherryPy is a web framework of Python which provides a friendly interface to
the HTTP protocol for Python developers.
• It is also called a web application library.

• CherryPy uses Python’s strengths as a dynamic language to model and bind


HTTP protocol into an API.

• It is one of the oldest web frameworks for Python, which provides clean
interface and reliable platform.
12/23/2023 Priya Singh Python web development with Django Unit I 55
CherryPy (continue….)

Strengths of CherryPy
The following features of CherryPy are considered as its strengths −
Simplicity
Developing a project in CherryPy is a simple task with few lines of code developed as per the
conventions and indentations of Python.
CherryPy is also very modular. The primary components are well managed with correct logic
concept and parent classes are expandable to child classes.
Power
CherryPy leverages all the power of Python. It also provides tools and plugins, which are
powerful extension points needed to develop world-class applications.
Open-source
CherryPy is an open-source Python Web Framework (licensed under the open-source BSD
license), which means this framework can be used commercially at ZERO cost.

12/23/2023 Priya Singh Python web development with Django Unit I 56


CherryPy (continue….)

Community Help
It has a devoted community which provides complete support with various types of
questions and answers. The community tries to give complete assistance to the
developers starting from the beginner level to the advanced level.
Deployment
There are cost effective ways to deploy the application. CherryPy includes its own
production-ready HTTP server to host your application. CherryPy can also be
deployed on any WSGI-compliant gateway.
CherryPy comes in packages like most open-source projects, which can be
downloaded and installed in various ways which are mentioned as follows −
•Using a Tarball
•Using easy_install
•Using Subversion

12/23/2023 57
Priya Singh Python web development with Django Unit I
Turbo Gears
TurboGears is a Python web application framework, which consists of many
modules. It is designed around the MVC architecture that are similar to Ruby on
Rails or Struts. TurboGears are designed to make rapid web application
development in Python easier and more supportable.
TurboGears is a web application framework written in Python.
TurboGears follows the Model-View-Controller paradigm as do most modern web
frameworks like Rails, Django, Struts, etc. This is an elementary tutorial that covers
all the basics of TurboGears.
TurboGears is a web application framework written in Python. Originally created by
Kevin Dangoor in 2005, its latest version TurboGears (ver 2.3.7) is managed by a
group of developers led by Mark Ramm and Florent Aide.
TurboGears follows the Model-View-Controller paradigm as do most modern web
frameworks like Rails, Django, Struts, etc.

12/23/2023 Priya Singh Python web development with Django Unit I 58


Turbo Gears (continue….)
Follow the above mentioned command to serve a pre-built example project. Open
http://localhost:8080 in browser. This readymade sample application gives a brief
introduction about Turbo Gears framework itself.

12/23/2023 Priya Singh Python web development with Django Unit I 59


Flask

• Flask is a web application framework written in Python.


• Armin Ronacher, who leads an international group of Python enthusiasts
named Pocco, develops it.
• Flask is based on Werkzeug WSGI toolkit and Jinja2 template engine. Both are
Pocco projects.
• Flask is often referred to as a micro framework.
• It aims to keep the core of an application simple yet extensible.
• Flask does not have built-in abstraction layer for database handling, nor does it
have form a validation support.
• Instead, Flask supports the extensions to add such functionality to the
application.
• Importing flask module in the project is mandatory. An object of Flask class is
our WSGI application

12/23/2023 Priya Singh Python web development with Django Unit I 60


Flask(continue….)
.Flask constructor takes the name of current module (__name__) as argument.
The route() function of the Flask class is a decorator, which tells the application which
URL should call the associated function.
app.route(rule, options)
•The rule parameter represents URL binding with the function.
•The options is a list of parameters to be forwarded to the underlying Rule object.
In the above example, ‘/’ URL is bound with hello_world() function. Hence, when the
home page of web server is opened in browser, the output of this function will be
rendered.
Finally the run() method of Flask class runs the application on the local development
server.
app.run(host, port, debug, options)

12/23/2023 Priya Singh Python web development with Django Unit I 61


Flask(continue….)
Debug mode
• A Flask application is started by calling the run() method.
• However, while the application is under development, it should be restarted
manually for each change in the code. To avoid this inconvenience, enable debug
support.
• The server will then reload itself if the code changes. It will also provide a useful
debugger to track the errors if any, in the application.
• Modern web frameworks use the routing technique to help a user remember
application URLs. It is useful to access the desired page directly without having to
navigate from the home page.
• The route() decorator in Flask is used to bind URL to a function. For example −
• @app.route(‘/hello’)def hello_world():
• return ‘hello world’

12/23/2023 Priya Singh Python web development with Django Unit I 62


Flask(continue….)

• Here, URL ‘/hello’ rule is bound to the hello_world() function.

• As a result, if a user visits http://localhost:5000/hello URL, the output of


the hello_world() function will be rendered in the browser.

• The add_url_rule() function of an application object is also available to bind


a URL with a function as in the above example, route() is used.

• A decorator’s purpose is also served by the following representation −


• def hello_world():
• return ‘hello world’
• app.add_url_rule(‘/’, ‘hello’, hello_world)

12/23/2023 Priya Singh Python web development with Django Unit I 63


Web2py

• web2py is defined as a free, open-source web framework for agile development


which involves database-driven web applications. It is written and
programmable in Python. It is a full-stack framework and consists of all the
necessary components a developer needs to build fully functional web
applications.
• web2py is defined as a free, open-source web framework for agile development
which involves database-driven web applications; it is written in Python and
programmable in Python. It is a full-stack framework; it consists of all the
necessary components, a developer needs to build a fully functional web
application.
• web2py framework follows the Model-View-Controller pattern of running web
applications unlike traditional patterns.

12/23/2023 Priya Singh Python web development with Django Unit I 64


Web2py (continue…)

web2py has an in-built feature to manage cookies and sessions. After


committing a transaction (in terms of SQL), the session is also stored
simultaneously.
web2py has the capacity of running the tasks in scheduled intervals after
the completion of certain actions. This can be achieved with CRON.

12/23/2023 Priya Singh Python web development with Django 65


Unit I
Bottle

• Bottle is a fast, simple and lightweight WSGI micro web-framework for


Python. It is distributed as a single file module. There are no dependencies
other than the Python Standard Library.
• The Web Server Gateway Interface (WSGI) is a simple calling convention for
web servers to forward requests to web applications or frameworks written in
the Python programming language.
• Bottle installation
• $ sudo pip3 install bottle
• We use the pip3 tool to install Bottle.

12/23/2023 Priya Singh Python web development with Django 66


Unit I
Falcon
• Falcon is a WSGI-compliant web framework designed to build RESTful
APIs without requiring external code library dependencies.
• Falcon resources
• Building Very Fast App Backends with Falcon Web Framework on PyPy
provides a walkthrough of a web API in Falcon that runs with PyPy and
Nginx.
• Asynchronous Tasks with Falcon and Celery shows how to configure
Celery with the framework.
• The official Falcon tutorial has a meaty guide for building and deploying
your first Falcon web application.
• Building Scalable RESTful APIs with Falcon and PyPy shows a to-do list
example with Falcon running on PyPy.
12/23/2023 Priya Singh Python web development with Django 67
Unit I
Cubic Web
• CubicWeb is an open-source Python Web framework . It promotes reusability through
the usage of components (called cubes).
• CubicWeb is well-defined Python semantic web application framework that focuses on
quality, reusability and efficiency of the development solution.
• CubicWeb stands out among other Python web frameworks and is not easy to learn. It
positions itself as semantic web development framework and gives developers
opportunity to build web applications by following the well known object-oriented
design principles and reusing components called cubes.
• Cube is the core concept of the CubicWeb. Basically it is a minimal web application - a
software component that consists of three main parts: data model (schema), the logic
(entities) needed to manipulate that data, and user interface (views) that displays the
data.

12/23/2023 Priya Singh Python web development with Django 68


Unit I
Cubic Web(continue…)
How CubicWeb works
• This development tool is written in Python and includes a web engine and a data
server. The web engine replies to http requests and provides a CRUD user interface
based on the data model of the instance. The data server publishes data gathered
from data repositories. Although app construction is data-driven, CubicWeb is not just
a database Web-client construction set.

• CubicWeb contains data repository that enables access to one or more data sources
such as SQL databases, LDAP repositories, filesystems, Google App Engine’s DataStore,
and even other CubicWeb instance repositories. A data repository can be configured
to either be accessed remotely using Pyro (Python Remote Objects) or act as a
standalone server, that in turn can be accessed either via a standalone web engine or
directly. Usually the web engine and the repository are run in the same process.

12/23/2023 Priya Singh Python web development with Django 69


Unit I
Quixote
• Quixote is a framework for writing Web-based applications using Python. Its
goals are flexibility and high-performance, in that order. Quixote applications
tend to be structured like traditional applications. The logic for formatting web
pages consists of Python classes and functions. Separation of presentation logic
and "back-end" logic is not enforced by Quixote. Instead, you are encouraged to
use traditional techniques. For example, a solution is to put presentation logic in
its own sub-package.
• There are three major versions of Quixote, version 1, 2 and 3. Versions 1 and 2
are similar to each other but incompatible. Version 1 is no longer actively
maintained. Version 3 of Quixote requires Python 3 but is otherwise similar to
Quixote 2. Versions 2 and 3 of Quixote are actively maintained and are used by
numerous public sites.

12/23/2023 Priya Singh Python web development with Django 70


Unit I
Quixote(continue….)

• Download
• The latest stable version of Quixote (Python 3 only) is version 3.5 (3.4 sig),
released 2021-06-12.
• The version of the 2.x series (Python 2 compatible) is version 2.9.1 (2.9.1 sig),
released 2016-04-18.
• The latest version of the 1.x series is Quixote is version 1.3, released 2008-
08-21.
• The latest test version of Quixote is version 3.6a2 (3.6a2 sig), released 2021-
12-20

12/23/2023 Priya Singh Python web development with Django 71


Unit I
Pyramid
• Pyramid makes it easy to write web applications. You can start small with this
"hello world" minimal request/response web app.

• This may take you far, especially while learning. As your application grows,
Pyramid offers many features that make writing complex software take less
effort.

• Pyramid works in all supported versions of Python.

• Pyramid is a general, open source, web application development framework


built in python. It allows python developer to create web applications with ease.

12/23/2023 Priya Singh Python web development with Django 72


Unit I
Pyramid(continue….)
• Installing, starting up and configuring
• As described, “the start small, finish big, stay finished framework”, Pyramid is
much like Flask which takes very little effort to install and run. In fact, you’ll
recognize that some of the patterns are similar to Flask once you start building
this application.
• Following are the steps to create pyramid framework environment −
• First, create a project directory. Here, we have created a directory named
pyramidProject (you can choose any name you want).
• Next, create a virtual environment where you will install all the project specific
dependencies. Here, we created a virtual environment folder named
pyramidEnv where Pyramid is installed.
• Then, go to the directory, pyramidEnv and install the pyramid with pip install
pyramid.
12/23/2023 Priya Singh Python web development with Django 73
Unit I
Daily Quiz

1. Discuss collection container datatypes.


2. What is the role of frameworks in python.
3. Discuss any three frameworks.
4. Discuss about Turbogear.
5. Discuss implementation rule of Falcon.
6. Discuss the Zappa framework.
7. Discuss the role of Dash.
8. Discuss the application area of cherryPy.
9. Discuss about the Request Http methods in Python.
10. Discuss about Flask application.

Priya Singh Python web development with Django Unit I


12/23/2023 74
Weekly Assignment

1. What are the most important uses of Django.


2. What are the disadvantages of Django?
3. What are the different data types used in Django.
4. What are the salient features of Django.
5. What are some of the technical features that Django includes

12/23/2023 Priya Singh Python web development with Django Unit I 75


Topic Link ( YouTube & NPTEL Video Links)

YouTube /other Video Links


• https://youtu.be/eoPsX7MKfe8?list=PLIdgECt554OVFKXRpo_kuI0XpUQKk0ycO

• https://youtu.be/tA42nHmmEKw?list=PLh2mXjKcTPSACrQxPM2_1Ojus5HX88ht7

• https://youtu.be/8ndsDXohLMQ?list=PLDsnL5pk7-N_9oy2RN4A65Z-PEnvtc7rf

• https://youtu.be/QXeEoD0pB3E?list=PLsyeobzWxl7poL9JTVyndKe62ieoN-MZ3

• https://youtu.be/9MmC_uGjBsM?list=PL3pGy4HtqwD02GVgM96-V0sq4_DSinqvf

12/23/2023 Priya Singh Python web development with Django Unit I 76


MCQ s
1. What is a Django App? 2. Django was introduced by
ADjango app is an extended package with base package
is Django A. Adrian Holovaty
B. Django app is a python package with its own B. Bill Gates
components. C. Rasmus Lerdorf
C. Both 1 & 2 Option D. Tim Berners-Lee
D. All of the above
3. What are Migrations in Django
A. They are files saved in migrations directory.
B. They are created when you run make migrations
command.
C. Migrations are files where Django stores changes to
your models.
D. All of the above

4. Which architectural pattern does django follow


APHP
B. MVT
C. HTML
D. None of the above
Priya Singh Python web development with Django Unit I
12/23/2023 77
MCQ s

which of these is not a valid backend for caching in django


A. Django.core.cache.backends.sys.memory
B. django.core.cache.backends.db.DatabaseCache
C. django.core.cache.backends.locmem.LocMemCache
D. None of the above

5. Which architectural pattern does django follow


A.PHP
B. MVT
C. HTML
D. None of the above

12/23/2023 Priya Singh Python web development with Django 78


Unit I
MCQ s
6. Python is a : 7. Python is Case Sensitive when dealing with
Development environment Identifiers?
Set of editing tools Yes
Programming Language No
Sometimes Only
None Of the Above

8. What is the OUTPUT of the following Statement? 9. What is the OUTPUT when the following
print 0xA + 0xB + 0xC : Statement is executed?
0xA0xB0xC “abc”+”xyz”
33 abc
ABC abcxyz
000XXXABC abcz
abcxy

10.what is the type of a? a={1,2:3} list


set
dict
syntax error

Priya Singh Python web development with Django Unit I


12/23/2023 79
Glossary Questions
Top 10 design pattern interview questions

1. Explain Django Architecture?


2. Explain the Django project directory structure?
3. What are models in Django?
4. What are templates in Django or Django template language?
5. What are views in Django?
6. What is Django ORM?
7. What is Django Rest Framework(DRF)?
8. What is the difference between a project and an app in Django?
9. What are different model inheritance styles in the Django?
10.What are Django Signals?
12/23/2023 Priya Singh Python web development with Django Unit I 80
Expected Questions for University Exam
Top 10 design pattern interview questions

1. Explain Django Architecture?


2. Explain the Django project directory structure?
3. What are models in Django?
4. What are templates in Django or Django template language?
5. What are views in Django?
6. What is Django ORM?
7. What is Django Rest Framework(DRF)?
8. What is the difference between a project and an app in Django?
9. What are different model inheritance styles in the Django?
10.What are Django Signals?
12/23/2023 Priya Singh Python web development with Django Unit I 81
Summary
Till Now we understand The idea of this module implements specialized
container datatypes providing alternatives to Python’s general purpose built-in
containers, Tkinter is the Python interface to the Tk GUI toolkit shipped with
Python. GET and POST requests using Python, Scrapy is a Python framework for
large scale web scraping. It gives you all the tools you need to efficiently extract
data from websites, process them as you want, and store them in your preferred
structure and format. Quixote is a framework for writing Web-based
applications using Python. Its goals are flexibility and high-performance, in that
order. Pyramid makes it easy to write web applications. You can start small with
this "hello world" minimal request/response web app.
Pyramid offers many features that make writing complex software take less
effort.
12/23/2023 Priya Singh Python web development with Django Unit I 82
References
(1) Tom Aratyn, “Building Django 2.0 Web Applications: Create enterprise-grade, scalable
Python web applications easily with Django 2.0”, 2nd Edition 2018, Packt Publishing.

(2) Nigel George, “Build a website with Django”, 1st Edition 2019, GNW Independent
Publishing Edition.

(3) Ray Yao,” Django in 8 Hours: For Beginners, Learn Coding Fast!, 2nd Edition 2020,
Independently published Edition.

(4) Harry Percival, “Test-Driven Development with Python: Obey the Testing Goat: Using
Django, Selenium, and JavaScript”, 2nd Edition 2019, Kindle Edition.

12/23/2023 Priya Singh Python web development with Django Unit I 83


THANK YOU

12/23/2023 Priya Singh Python web development with Django Unit I 84

You might also like