Uploaded by Yuvraj Singh

WEB DEVELOPMENT USING PYTHON(ROSHAN) (1)

advertisement
WEB DEVELOPMENT USING PYTHON
A SUMMER INTERNSHIP REPORT
Submitted by
SAHU ROSHAN ROHITKUMAR
In fulfilment for the award of the degree of
BACHELOR OF ENGINEERING
in
Electronics and Communication Engineering
Government Engineering College, Bharuch
Gujarat Technological University, Ahmedabad
July, 2022
Government Engineering College Bharuch
Electronics and Communication Engineering
2022
CERTIFICATE
Date:
This is to certify that the dissertation entitled “WEB DEVELOPMENT USING
PYTHON” has been carried out by SAHU ROSHAN ROHITKUMAR under my
guidance in fulfilment of the degree of Bachelor of Engineering in ELECTRONICS
AND
COMMUNICATION
ENGINEERING
(7th
Semester)
of
Gujarat
Technological University, Ahmedabad during the academic year 2022-23.
Guided by:
Prof. Hiren J. Vasava
Head of the Department
Prof. Kunjal Tandel
Government Engineering College, Bharuch
Opp. Govt. Guest House, Bholav, Bharuch – 392002
CERTIFICATE
This is to certify that SAHU ROSHAN ROHITKUMAR has successfully
completed the summer internship entitled WEB DEVELOPMENT
USING PYTHON in partial fulfillment for the degree of Bachelor of
Engineering Electronics and Communication Engineering, 7 th Semester of
Gujarat Technological University, Ahmedabad during the academic year
2022-23.
Examiner 1
Examiner 2
CERTIFICATE OF COMPLETION
Government Engineering College, Bharuch
Opp. Govt. Guest House, Bholav, Bharuch – 392002
DECLARATION
I hereby declare that the Summer Internship report submitted along with
the Summer Internship entitled WEB DEVEPOLMENT USING
PYTHON submitted in partial fulfilment for the degree of Bachelor of
Engineering in Electronics and Communication Engineering to Gujarat
Technological University, Ahmedabad, is a Bonafede record of original
project work carried out by me at INFOLABZ IT SERVICES PVT. LTD and
that no part of this report has been directly copied from any students’
reports or taken from any other source, without providing due references.
Name of the Student
Sign of Student
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
ACKNOWLEDGEMENT
I would like to extend my sincerest of thanks to our internal guide Mr. Hiren J. Vasava for their
useful guidance for my project. He helped us quite for project and report.
This movement asks for a token of gratitude to them for giving us this opportunity to undertake
a project firm. My heartiest of thank to you sir.
Special thanks to our HOD sir Mr. Kunjal Tandel and my project in charge Mr. Hiren J. Vasava
for opening up a new way of seeing things and doing project.
Sahu Roshan Rohitkumar
190140111116
6
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
ABSTRACT
Python is very famous because of its wide area of applications. One of the applications of
python is web development. Many frameworks of python are available for web development
for example Django, Flask, Web2py, CherryPy etc. Django is very popular framework and
huge acceptance in corporate industry. In this internship we will going to develop website along
with real time API handling. This web page will fetch live data and display in well-structured
and responsive manner.
7
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
COMPANY PROFILE
Established in 2016, incorporation with our parent IT company, INFOLABZ IT
SERVICES PVT. LTD. has managed to make it's own position in IT Sector. We
are involved in Web Development, App Development, Progressive Web
Application Development, IOT solutions, Graphics & Designing, Digital
Marketing, Domain & Hosting services, SMS services etc.
In the span of six years we have managed to deliver all projects on time with
utmost accuracy to our clients across the globe. We have dedicated teams of
experienced and hard working developers. Our developers who are always willing
to take new challenges and looking forward to learn new things, are heart of this
company.
Our objective is to sustain with exponential growth in IT industry. Our mission is
to deliver the best with top notch quality every quarter and vision is to develop a
product with one of its kind concept which could be used by millions of people.
8
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
LIST OF FIGURES
Figure 2.3 Django Architecture
26
Figure 3.2 Structure data
48
Figure 3.3 Data flow diagram using JSON
48
Figure 5.3 Rest API Architectute
51
9
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
TABLE OF CONTENTS
Contents
CERTIFICATE
2
DECLARATION
5
ACKNOWLEDGEMENT
6
ABSTRACT
7
LIST OF FIGURES
9
TABLE OF CONTENTS
10
CHAPTER 1
12
1st WEEK
12
1.1 PYTHON introduction
12What is Python?
12
13
What can Python do? ....................................................................................................... 13
Why Python? .................................................................................................................... 13
Good to know................................................................................................................... 13
Python Syntax compared to other programming languages ............................................ 14
1.2 PYTHON GETTING STARTED
14
How to install Python on Windows?
14
Download and Install Python: ..................................................................................... 15
1.3 BASICS OF DICTIONARY
18
Python Dictionary
18
Creating Python Dictionary
18
Python Dictionary Methods
19
Python Dictionary Comprehension
20
Dictionary Built-in Functions .......................................................................................... 21
CHAPTER 2
Ошибка! Закладка не определена.
2.1 Django introduction
22
What is Django
22
How does Django Work?
22
Django Project MVT Structure
22
Model
22
View
22
Template
23
URLs
23
10
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
So, What is Going On?
23
Django History
23
2.2 Django Getting Started
23
Django Requires Python
24
PIP
24
Install Django
24
Check Django Version
25
What's Next?
25
Python Web Development
25
Why Django Framework?
26
2.3 Django Architecture
26
2.4 My First Project
27
Run the Django Project
27
2.5 Django Create App
28
What is an App?
28
Create App
29
CHANGE SETTINGS:
30
2.6 Django Views
31
Views
31
2.8 Django Templates
33
Templates
33
Modify the View
34
2.9 Assignment 1
36
CHAPTER 3
46
2nd WEEK
46
3.1 BASIC OF JSON
46
JSON Example
46
What is JSON?
46
Why Use JSON?
46
Storing Data
47
3.2 Data flow diagram using JSON
48
3.3 Structure data
48
CHAPTER 4
49
4.1 Request package
49
11
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
Definition and Usage
48
Download and Install the Requests Module
48
Syntax
48
Methods
48
CHAPTER 5
50
5.1 API FETCHING in python
50
Steps to pull data from an API using Python
49
Example 1: Pulling data from an Open source COVID API ........................................... 49
5.2 What is an API?
50
Making API Requests in Python
50
5.3 REST API Architecture
51
5.4 Assignment 2
52
CONCLUSION
64
REFERENCES
65
12
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
CHAPTER 1
1st WEEK
1.1 Python Introduction
What is Python?
 Python is a popular programming language. It was created by Guido van
Rossum, and released in 1991.




It is used for:
web development (server-side),
software development,
mathematics,
system scripting.
What can Python do?





Python can be used on a server to create web applications.
Python can be used alongside software to create workflows.
Python can connect to database systems. It can also read and modify files.
Python can be used to handle big data and perform complex mathematics.
Python can be used for rapid prototyping, or for production-ready software
development.
Why Python?





Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.
Python runs on an interpreter system, meaning that code can be executed as soon
as it is written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-oriented way or a functional
way.
Good to know

The most recent major version of Python is Python 3, which we shall be using in
this tutorial. However, Python 2, although not being updated with anything other
than security updates, is still quite popular.
13
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON

In this tutorial Python will be written in a text editor. It is possible to write Python
in an Integrated Development Environment, such as Thonny, Pycharm, Netbeans
or Eclipse which are particularly useful when managing larger collections of
Python files.
Python Syntax compared to other programming languages

Python was designed for readability, and has some similarities to the English
language with influence from mathematics.
Python uses new lines to complete a command, as opposed to other programming
languages which often use semicolons or parentheses.
Python relies on indentation, using whitespace, to define scope; such as the scope
of loops, functions and classes. Other programming languages often use curlybrackets for this purpose.


EXAMPLE
INPUT
OUTPUT
1.2 PYTHON GETTING STARTED
How to install Python on Windows?
Python is a lot easier to code and learn. Python programs can be written on any
plain text editor like notepad, notepad++, or anything of that sort. One can also
use an online IDE for writing Python codes or can even install one on their
system to make it more feasible to write these codes because IDEs provide a lot
of features like intuitive code editor, debugger, compiler, etc.
To begin with, writing Python Codes and performing various intriguing and
useful operations, one must have Python installed on their System. This can be
done by following the step by step instructions provided below:
What if Python already exists? Let’s check
To check if your device is pre-installed with Python or not, just go to
the Command
line(search
for cmd in
the
Run
dialog( +
R).
14
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
Now run the following command:
python --version
If Python is already installed, it will generate a message with the Python version
available.
Download and Install Python:
Before starting with the installation process, you need to download it. For that
all versions of Python for Windows are available on python.org.
Download the required version and follow the further instructions for the
installation process.
15
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
Beginning the installation.
Getting Started:
Installing Libraries:
16
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
Installing pip and other features:
Finishing Installation:
To verify the installation enter the following commands in your Terminal.
python
17
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
1.3 BASICS OF DICTIONARY
Python Dictionary
In this tutorial, you'll learn everything about Python dictionaries; how they are created,
accessing, adding, removing elements from them and various built-in methods.
Python dictionary is an unordered collection of items. Each item of a dictionary has
a key/value pair.
Dictionaries are optimized to retrieve values when the key is known.
Creating Python Dictionary
Creating a dictionary is as simple as placing items inside curly braces {} separated by
commas.
An item has a key and a corresponding value that is expressed as a pair (key: value).
While the values can be of any data type and can repeat, keys must be of immutable
type (string, number or tuple with immutable elements) and must be unique.
EXAMPLE
18
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
Python Dictionary Methods
Methods that are available with a dictionary are tabulated below.
Method
Description
clear()
Removes all items from the dictionary.
copy()
Returns a shallow copy of the dictionary.
fromkeys(seq[, v])
Returns a new dictionary with keys from
seq and value equal to v (defaults to None ).
get(key[,d])
Returns the value of the key . If the key
does not exist, returns d (defaults to None ).
items()
Return a new object of the dictionary's
items in (key, value) format.
keys()
Returns a new object of the dictionary's keys.
pop(key[,d])
Removes the item with the key and returns its
value or d if key is not found. If d is not provided
and the key is not found, it raises KeyError .
popitem()
Removes and returns an arbitrary item (key,
value). Raises KeyError if the dictionary is
empty.
setdefault(key[,d])
Returns the corresponding value if the key is in
the dictionary. If not, inserts the key with a value
of d and returns d (defaults to None ).
update([other])
Updates the dictionary with the key/value pairs
from other , overwriting existing keys.
values()
Returns a new object of the dictionary's values
19
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
EXAMPLE
Python Dictionary Comprehension
Dictionary comprehension is an elegant and concise way to create a new dictionary from an
iterable in Python.
Dictionary comprehension consists of an expression pair (key: value) followed by
a for statement inside curly braces {}.
Here is an example to make a dictionary with each item being a pair of a number and its
square.
INPUT
OUTPUT
20
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
Dictionary Built-in Functions
Built-in functions like all(), any(), len(), cmp(), sorted(), etc. are commonly used with
dictionaries to perform different tasks.
Function
Description
all()
Return True if all keys of the dictionary are True (or if the dictionary is empty).
Return True if any key of the dictionary is true. If the dictionary is empty,
any()
return False .
len()
Return the length (the number of items) in the dictionary.
cmp()
Compares items of two dictionaries. (Not available in Python 3)
sorted()
Return a new sorted list of keys in the dictionary.
EXAMPLE
OUTPUT
21
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
CHAPTER 2
2.1 DJANGO INTRODUCTION
What is Django?
Django is a Python framework that makes it easier to create web sites using Python.
Django takes care of the difficult stuff so that you can concentrate on building your web
applications.
Django emphasizes reusability of components, also refereed to as DRY (Don't Repeat
Yourself), and comes with ready-to-use features like login system, database connection and
CRUD operations (Create Read Update Delete).
Django is especially helpful for database driven websites.
How does Django Work?



Django follows the MVT design pattern (Model View Template).
Model - The data you want to present, usually data from a database.
View - A request handler that returns the relevant template and content - based on the request
from the user.
Template - A text file (like an HTML file) containing the layout of the web page, with logic
on how to display the data.
Django Project MVT Structure
Django is based on MVT (Model-View-Template) architecture. MVT is a software design
pattern for developing a web application.
MVT Structure has the following three parts -
Model
The model provides data from the database.
In Django, the data is delivered as an Object Relational Mapping (ORM), which is a
technique designed to make it easier to work with databases.
The most common way to extract data from a database is SQL. One problem with SQL is that
you have to have a pretty good understanding of the database structure to be able to work
with it.
Django, with ORM, makes it easier to communicate with the database, without having to
write complex SQL statements.
The models are usually located in a file called models.py.
View
A view is a function or method that takes http requests as arguments, imports the relevant
model(s), and finds out what data to send to the template, and returns the final result.
22
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
The views are usually located in a file called views.py.
Template
A template is a file where you describe how the result should be represented.
Templates are often .html files, with HTML code describing the layout of a web page, but it
can also be in other file formats to present other results, but we will concentrate on .html
files.
Django uses standard HTML to describe the layout, but uses Django tags to add logic:
The templates of an application is located in a folder named templates.
URLs
Django also provide a way to navigate around the different pages in a website.
When a user requests a URL, Django decides which view it will send it to.
This is done in a file called urls.py.
So, What is Going On?
1.
2.
3.
4.
5.
When you have installed Django and created you first Django web application, and the
browser requests the URL, this is basically what happens:
Django receives the URL, checks the urls.py file, and calls the view that matches the URL.
The view, located in views.py, checks for relevant models.
The models are imported from the models.py file.
The view then sends the data to a specified template in the template folder.
The template contains HTML and Django tags, and with the data it returns finished HTML
content back to the browser.
Django can do a lot more than this, but this is basically what you will learn in this tutorial,
and are the basic steps in a simple web application made with Django.
Django History
Django was invented by Lawrence Journal-World in 2003, to meet the short deadlines in the
newspaper and at the same time meeting the demands of experienced web developers.
Initial release to the public was in July 2005.
Latest version of Django is 4.0.5 (March 2022).
2.2 Django Getting Started
To install Django, you must have Python installed, and a package manager like PIP.
PIP is included in Python from version 3.4.
23
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
Django Requires Python
To check if your system has Python installed, run this command in the command prompt:
If Python is installed, you will get a result with the version number, like this
If you find that you do not have Python installed on your computer, then you
can download it for free from the following website: https://www.python.org/
PIP
To install Django, you must use a package manager like PIP, which is included in Python
from version 3.4.
To check if your system has PIP installed, run this command in the command prompt:
If PIP is installed, you will get a result with the version number.
For me, on a windows machine, the result looks like this:
If you do not have PIP installed, you can download and install it from this
page: https://pypi.org/project/pip/
Install Django
Finally, we can install Django.
24
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
Remember to install Django while you are in the virtual environment!
Django is installed using pip, with this vs code:
Open the terminal write this code:
Which will give a result that looks like this (at least on my Windows machine):
That's it" Now you have installed Django in your new project, running in a virtual
environment!
Check Django Version
You can check if Django is installed by asking for its version number like this:
What's Next?
Now you are ready to create a Django project in a virtual environment on your computer.
We will create a Django project and look at the various features of Django and hopefully
make you a Django developer.
Python Web Development
Python Django is a web framework that allows to quickly create efficient web pages.
Django is also called batteries included framework because it provides built-in features
25
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
such as Django Admin Interface, default database – SQLite3, etc. When you’re building a
website, you always need a similar set of components: a way to handle user authentication
(signing up, signing in, signing out), a management panel for your website, forms, a way to
upload files, etc. Django gives you ready-made components to use.
Why Django Framework?




Excellent documentation and high scalability.
Used by Top MNCs and Companies, such as Instagram, Disqus, Spotify, Youtube,
Bitbucket, Dropbox, etc. and the list is never-ending.
Easiest Framework to learn, rapid development, and Batteries fully included.
Django is a rapid web development framework that can be used to develop fully
fleshed web applications in a short period of time.
The last but not least reason to learn Django is Python, Python has a huge library
and features such as Web Scrapping, Machine Learning, Image Processing,
Scientific Computing, etc. One can integrate all this with web applications and do
lots and lots of advanced stuff.
2.3 Django Architecture
Django is based on MVT (Model-View-Template) architecture which has the following three
parts –



Model: The model is going to act as the interface of your data. It is responsible
for maintaining data. It is the logical data structure behind the entire application
and is represented by a database (generally relational databases such as MySql,
Postgres).
View: The View is the user interface that you see in your browser when you
render a website. It is represented by HTML/CSS/Javascript and Jinja files.
Template: A template consists of static parts of the desired HTML output as well
as some special syntax describing how dynamic content will be inserted. To check
more, visit – Django Templates
Figure 2.3 Django Architucture
26
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
2.4 My First Project
Once you have come up with a suitable name for your Django project, like mine: infolabz,
navigate to where in the file system you want to store the code (in the virtual environment),
and run this command in the command prompt:
Django creates a infolabz folder on my computer, with this content:
These are all files and folders with a specific meaning, you will learn about some of them
later in this tutorial, but for now, it is more important to know that this is the location of your
project, and that you can start building applications in it.
Run the Django Project
Now that you have a Django project, you can run it, and see what it looks like in a browser.
Navigate to the /infolabz folder and execute this command in the command prompt:
27
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
Which will produce this result:
Open a new browser window and type 127.0.0.1:8000 in the address bar.
The result:
2.5 Django Create App
What is an App?
An app is a web application that has a specific meaning in your project, like a home page, a
contact form, or a members database.
We will create an app that allows us to list and register members in a database.
But first, let's just create a simple Django app.
28
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
Create App
I will name my app new.
Start by navigating to the selected location where you want to store the app, and run the
command below.
If the server is still running, and you are not able to write commands, press [CTRL] +[C] to
stop the server and you should be back in the virtual environment.
Django creates a folder named new in my project, with this content:
These are all files and folders with a specific meaning. You will learn about most of them
later in this tutorial.
First, take a look at the file called views.py.
This is where we gather the information, we need to send back a proper response.
29
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
CHANGE SETTINGS:
Inform Django project – add app in settings.py
To be able to work with more complicated stuff than we have to tell Django that a new app is
created.
This is done in the settings.py file in the infolabz folder.
Look up the INSTALLED_APPS[ ] list and add the new app like this.
Then run this command:
Which will produce this output:
30
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
2.6 Django Views
Views
Django views are Python functions that takes http requests and returns http response, like
HTML documents.
A web page that uses Django is full of views with different tasks and missions.
Views are usually put in a file called views.py located on your app's folder.
There is a views.py in your new folder that looks like this:
Find it and open it, and replace the content with this:
This is a simple example on how to send a response back to the browser.
But how can we execute the view? Well, we must call the view via a URL
2.7 URLs
Create a file named urls.py in the same folder as the views.py file, and type this code in it:
31
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
The urls.py file you just created is specific for the new application. We have to do some
routing in the root directory infolabz as well. This may seem complicated, but for now, just
follow the instructions below.
There is a file called urls.py on the infolabz folder, open that file and add the include module
in the import statement, and also add a path() function in the urlpatterns[] list, with arguments
that will route users that comes in via 127.0.0.1:8000
Then your file will look like this:
Execute this command in the command prompt:
32
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
In the browser window, type http://127.0.0.1:8000/ in the address bar.
2.8 Django Templates
Templates
We learned that the result should be in HTML, and it should be created in a template, so let's
do that.
Create a templates folder inside the new folder, and create a HTML file named index.html.
The file structure should be something like this:
33
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
Open the HTML file and insert the following:
Modify the View
Open the views.py file and replace the index view with this:
Execute this command:
34
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
The result should look like this:
35
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
1.10 ASSIGNMENT 1
36
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
Q-1 Create a Django project with name=> gtu.
Step 1: Open terminal and type this command.
This command will install Django in your virtual environment and will make it error free.
Step 2: After that, type this command.
The result will look like this:
Step-3: type this command.
python manage.py makemigrations:
which is responsible for creating new migrations based on the changes you have made to
your models.
Step 4: type this command:
python manage.py migrate
Which is responsible for applying and unapplying migrations.
Step 5: type this code in command:
37
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
Q-2 Create any 3 superusers(admin), 2admins must not be able to add or delete other admins.
Step 1: Creating 1st superuser(admin)
First, we’ll need to create a user who can login to the admin site.
Enter your desired username and press Enter.
You will then be prompted for your desired email address.
The final step is to enter your password. You will be asked to enter your password twice, the
second time as a confirmation of the first.
Step 2: Create 2nd superuser.
Step 3: Create 3rd superuser
38
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
The Django admin site is activated by default Let’s start the development server and explore
it,
Type this command:
Now, open a web browser and go to http://127.0.0.1:8000/admin and press Enter.
Login screen will show you
Step 4: login from gtu
Click on Users
39
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
Now click on gec
In Permissions section disable
 Superuser status
User permissions.
Choose all
But remove 4 permissions
40
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
Save the file
Step 5: click on department from gtu login
Apply same process as applied on gec
Which means User gec and department are not allow to view, delete, change, or add any user.
Q-3 Create an app name it=> internship
Type this command:
Now app is created in Django project name gtu.
inform Django project add app in sitting.py of gtu
Then run server
The app will show on server
41
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
Q-4 Create 1st table name it Category-> column (category name) and
Q-5 Create 2nd table name it product-> column (categoryname[foreignkey], product name,
price, quantity, description) in this you have to search how to add and load html page in app)
In our internship app, we’ll Create two models: Category and product
Write code in admin.py inside internship app:
42
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
Run server:
In Browser category and product will display:
Click Categories:
Click product:
43
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
Q-6 Create one web page index.html in app(internship) and load it as default page when we
run project.
Create HTML page
Create a directory named templates inside the newly created internship apps directory.
write in terminal:
The folder is created inside app internship, now inside the templates dir, Create a file name
index.html
Write the code inside internship/templates/index.html
Setup views.py and urls.py
44
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
Run server:
You can see the HTML page Create being rendered.
45
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
CHAPTER 3
2nd WEEK
3.1 BASIC OF JSON
JSON stands for JavaScript Object Notation
JSON is a text format for storing and transporting data
JSON is "self-describing" and easy to understand
JSON Example
This example is a JSON string:



It defines an object with 3 properties:
name
age
car
Each property has a value.
If you parse the JSON string with a JavaScript program, you can access the data as an object:
What is JSON?





JSON stands for JavaScript Object Notation
JSON is a lightweight data-interchange format
JSON is plain text written in JavaScript object notation
JSON is used to send data between computers
JSON is language independent *
Why Use JSON?
The JSON format is syntactically similar to the code for creating JavaScript objects. Because
of this, a JavaScript program can easily convert JSON data into JavaScript objects.
Since the format is text only, JSON data can easily be sent between computers, and used by
any programming language.
JavaScript has a built in function for converting JSON strings into JavaScript objects:
JSON.parse()
JavaScript also has a built in function for converting an object into a JSON string:
JSON.stringify()
You can receive pure text from a server and use it as a JavaScript object.
You can send a JavaScript object to a server in pure text format.
You can work with data as JavaScript objects, with no complicated parsing and translations.
46
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
Storing Data
When storing data, the data has to be a certain format, and regardless of where you choose to
store it, text is always one of the legal formats.
JSON makes it possible to store JavaScript objects as text.
3.2 Structure data
Figure 3.2 structure data
3.3 Data flow diagram using JSON:
Figure 3.3 data flow diagram
47
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
CHAPTER 4
4.1 REQUESTS PACKAGE
Definition and Usage
The requests module allows you to send HTTP requests using Python.
The HTTP request returns a Response Object with all the response data (content, encoding,
status, etc).
Download and Install the Requests Module
Navigate your command line to the location of PIP, and type the following:
Syntax
requests.methodname(params)
Methods
Method
Description
delete(url, args)
Sends a DELETE request to the specified url
get(url, params, args)
Sends a GET request to the specified url
head(url, args)
Sends a HEAD request to the specified url
patch(url, data, args)
Sends a PATCH request to the specified url
post(url, data, json, args)
Sends a POST request to the specified url
put(url, data, args)
Sends a PUT request to the specified url
request(method, url, args)
Sends a request of the specified method to
the specified url
48
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
CHAPTER 5
5.1 API FETCHING IN PYTHON
Steps to pull data from an API using Python
Let us now focus on the steps that we need to follow in order to pull out the particular data
from an API.
Example 1: Pulling data from an Open source COVID API
In this example, we would be connecting to an Open source COVID API just to extract and
parse the json information in an customized manner.
1. Connect to an API
At first, we need to connect to an API and make a secure connection as shown below–
In this article, we have used the COVID19-India API to fetch the data of the cases from the
state-wise list.
import requests
import json
response_API = requests.get('https://api.covid19india.org/state_district_wise.json')
#print(response_API.status_code)
As we are pulling the data from an API, we have used the get() function to get the
information from the API.
2. Get the data from API
After making a healthy connection with the API, the next task is to pull the data from the
API. Look at the below code!
data = response_API.text
The requests.get(api_path).text helps us pull the data from the mentioned API.
3. Parse the data into JSON format
Having extracted the data, its now the time to convert and decode the data into proper JSON
format as shown below–
json.loads(data)
The json.loads() function parses the data into a JSON format.
parse_json['Andaman and Nicobar Islands']['districtData']['South Andaman']['active']
You can find the entire code below!
import requests
import json
response_API = requests.get('https://api.covid19india.org/state_district_wise.json')
#print(response_API.status_code)
data = response_API.text
parse_json = json.loads(data)
active_case = parse_json['Andaman and Nicobar Islands']['districtData']['South Andaman']['active']
print("Active cases in South Andaman:", active_case)
49
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
Output:
Active cases in South Andaman: 19
5.2 What is an API?
An API, or Application Programming Interface, is a server that you can use to retrieve and
send data to using code. APIs are most commonly used to retrieve data, and that will be the
focus of this beginner tutorial.
When we want to receive data from an API, we need to make a request. Requests are used all
over the web. For instance, when you visited this blog post, your web browser made a request
to the Dataquest web server, which responded with the content of this web page.
API requests work in exactly the same way – you make a request to an API server for data,
and it responds to your request.
Making API Requests in Python
In order to work with APIs in Python, we need tools that will make those requests. In Python,
the most common library for making requests and working with APIs is the requests library.
The requests library isn’t part of the standard Python library, so you’ll need to install it to get
started.
If you use pip to manage your Python packages, you can install requests using the following
command:
pip install requests
If you use conda, the command you’ll need is:
conda install requests
Once you’ve installed the library, you’ll need to import it. Let’s start with that important step:
import requests
Now that we’ve installed and imported the requests library, let’s start using it.
50
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
5.3 REST API Architecture
Figure 5.3 Rest API Architecture
51
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
2.4 Assignment 2
52
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
Step1:
Create new project name newschannel
Step 2: Create app name news
Step 3: Create a folder inside the news apps name static inside static create two folder name
css, image
Inside css create file name style.css
Step 4: Create folder inside news apps name templates inside templates folder create files
name index.html, business.html, sports.html, technology.html, world.html .
Write code in index.html
<!DOCTYPE html>
<html>
<head>
{% load static%}
<link rel="stylesheet" href="{% static 'css/style.css'%}">
<title>
Simple web Development Template
</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
integrity="sha384BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstraptheme.min.css" integrity="sha384rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp"
crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"
integrity="sha384Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
crossorigin="anonymous"></script>
53
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
</head>
<body>
<nav class="navbar background">
<ul class="nav-list">
<div class="logo">
<img src="{%static 'images/bbcnews.png'%}" onclick="viewmsg();"/>
</div>
<li><a class= "navbar-brand" href="{% url 'sports' %}">
SPORTS</a></li>
<li><a class= "navbar-brand" href="{% url 'business' %}"> BUSINESS
</a></li>
<li><a class= "navbar-brand" href="{% url 'world' %}"> WORLD
</a></li>
<li><a class= "navbar-brand" href="{% url 'technology' %}"> TECHNOLOGY
</a></li>
</ul>
<div class="rightNav">
<input type="text" name="search" id="search">
<button class="btn btn-sm">Search</button>
</div>
</nav>
<section class="firstsection">
<div class="box-main">
<div class="firstHalf">
<h1 class="text-big" id="sports">
SPORTS
</h1>
<p class="text-small">
Sports journalism is a form of writing that reports on
matters pertaining to sporting topics and competitions. Sports journalism
started in the early 1800s when it was targeted to the social elite and
transitioned into an integral part of the news business with newspapers having
dedicated sports sections.<br/>
<img src="{%static 'images/sportsnews.webp'%}" height="200px"
width="200px" onclick="viewmsg();"/>
<a href="{% url 'sports' %}">GO TO SPORTS NEWS PAGE</a>
</p>
</div>
</div>
</section>
54
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
<section class="secondsection">
<div class="box-main">
<div class="secondHalf">
<h1 class="text-big" id="business">
BUSINESS
</h1>
<p class="text-small">
A business is defined as an organization or enterprising
entity engaged in commercial, industrial, or professional activities.
Businesses can be for-profit entities or non-profit organizations. Business
types range from limited liability companies to sole proprietorships,
corporations, and partnerships.<br/>
<img src="{%static 'images/businessnews.jpg'%}" height="200px"
width="200px" onclick="viewmsg();"/>
<a href="{% url 'business' %}">GO TO BUSINESS NEWS PAGE</a>
</p>
</div>
</div>
</section>
<section class="section">
<div class="paras">
<h1 class="sectionTag text-big">WORLD</h1>
<p class="sectionSubTag text-small">
News of the World is a 2020 American Western film co-written
and directed by Paul Greengrass, based on the 2016 novel of the same name by
Paulette Jiles, and starring Tom Hanks and Helena Zengel.<br/>
<img src="{%static 'images/worldnews.webp'%}" height="200px"
width="200px" onclick="viewmsg();"/>
<a href="{% url 'world' %}">GO TO WORLD NEWS PAGE</a>
</p>
</div>
</section>
<section class="section">
<div class="paras">
<h1 class="sectionTag text-big">TECHNOLOGY</h1>
<p class="sectionSubTag text-small">
Technology news is so important that many news websites have
created dedicated pages purely to report on technological developments.
Naturally industries such as computing and video gaming are heavily interested
in the developments reported as part of technology news stories.<br/>
55
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
<img src="{%static 'images/technologynews.jpg'%}" height="200px"
width="200px" onclick="viewmsg();"/>
<a href="{% url 'world' %}">GO TO WORLD NEWS PAGE</a>
</p>
</div>
</section>
<footer class="background">
<p class="text-footer">
Copyright ©-All rights are reserved
</p>
</footer>
</body>
</html>
Write code in business.html
56
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
Write code in sports.html
Write code in technology.html
57
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
Write code in world.html
Write code in folder css in file style.css
<style>
* {
margin: 0;
padding: 0;
}
.navbar {
display: flex;
align-items: center;
justify-content: center;
position: sticky;
top: 0;
cursor: pointer;
}
.background {
background: black;
background-blend-mode: darken;
background-size: cover;
}
.nav-list {
width: 70%;
58
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
display: flex;
align-items: center;
}
.logo {
display: flex;
justify-content: center;
align-items: center;
}
.logo img {
width: 180px;
border-radius: 50px;
}
.nav-list li {
list-style: none;
padding: 26px 30px;
}
.nav-list li a {
text-decoration: none;
color: white;
}
.nav-list li a:hover {
color: grey;
}
.rightnav {
width: 30%;
text-align: right;
}
#search {
padding: 5px;
font-size: 17px;
border: 2px solid grey;
border-radius: 9px;
}
.firstsection {
background-color: green;
height: 400px;
}
.secondsection {
background-color: blue;
59
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
height: 400px;
}
.box-main {
display: flex;
justify-content: center;
align-items: center;
color: black;
max-width: 80%;
margin: auto;
height: 80%;
}
.firsthalf {
width: 100%;
display: flex;
flex-direction: column;
justify-content: center;
}
.secondhalf {
width: 30%;
}
.secondhalf img {
width: 70%;
border: 4px solid white;
border-radius: 150px;
display: block;
margin: auto;
}
.text-big {
font-family: 'Piazzolla', serif;
font-weight: bold;
font-size: 35px;
}
.text-small {
font-size: 18px;
}
.btn {
padding: 8px 20px;
margin: 7px 0;
border: 2px solid white;
border-radius: 8px;
background: none;
60
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
color: white;
cursor: pointer;
}
.btn-sm {
padding: 6px 10px;
vertical-align: middle;
}
.section {
height: 400px;
display: flex;
align-items: center;
justify-content: center;
max-width: 90%;
margin: auto;
}
.section-Left {
flex-direction: row-reverse;
}
.paras {
padding: 0px 65px;
}
.thumbnail img {
width: 250px;
border: 2px solid black;
border-radius: 26px;
margin-top: 19px;
}
.center {
text-align: center;
}
.text-footer {
text-align: center;
padding: 30px 0;
font-family: 'Ubuntu', sans-serif;
display: flex;
justify-content: center;
color: white;
}
</style>
61
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
Add some images in images folder for decoration.
Step 5: modify views,py inside news app
from nturl2path import url2pathname
from django.shortcuts import render
import requests
def index(request):
return render(request, "index.html")
def about(request):
return render(request,'about.html')
def sports(request):
records ={}
url ="http://inshortsapi.vercel.app/news?category=sports"
response= requests.get(url=url)
inshorts_data= response.json()
records['sportsdata'] = inshorts_data
return render(request,'sports.html',records)
def business(request):
records ={}
url ="http://inshortsapi.vercel.app/news?category=business"
response= requests.get(url=url)
inshorts_data= response.json()
records['businessdata']= inshorts_data
return render(request,"business.html",records)
def world(request):
records ={}
url ="http://inshortsapi.vercel.app/news?category=world"
response= requests.get(url=url)
inshorts_data= response.json()
records['worlddata']= inshorts_data
return render(request,"world.html",records)
def technology(request):
records ={}
url ="http://inshortsapi.vercel.app/news?category=world"
response= requests.get(url=url)
inshorts_data= response.json()
records['technologydata']= inshorts_data
return render(request,"technology.html",records)
62
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
Step 6: Modify urls.py inside news app
Run server:
The result will show in browser:
63
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
CONCLUSION
Django is a rapid web development framework and if you want to get your application
built fast within a few days, there is no better framework than Django Web
Framework. Django gives all the features included, also called “Batteries Included
Framework”. It has a built-in admin interface which makes it easy to work with it.
Django is a high-level python-based web framework which allows you to quickly
create web applications without all of the installation or dependency problems that
you normally will find with other frameworks. For developing a Web Application or
API Backend.
For Rapid Development of some web application, Deploying the application Fast and
Scaling it according to your needs, A Perfect ORM for working with databases
instead of database queries, To develop a secure single-page application for either
retrieving data or posting data.
64
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Project ID - 250867
WEB DEVELOPMENT USING PYTHON
REFERENCES
[1]. https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django
[2]. https://wiki.python.org/moin/ReferenceBooks
[3]. https://dl.acm.org/doi/abs/10.1145/2157136.2157353
[4]. https://www.w3schools.com/django/
[5]. https://www.geeksforgeeks.org/python-web-development-django-tutorial/
65
GOVERNMENT ENGINEERING COLLEGE BHARUCH
Download