Professional Documents
Culture Documents
Advpython
Advpython
Advpython
File Handling:
File is nothing but storing data parmenantly for future purpose.
Files are very common permanent storage areas to store our data.
Python has several functions for creating, reading, updating, and deleting files.
Types of Files:
There are 2 types of files
1. Text Files:
Usually we can use text files to store character data
eg: sample.txt
2. Binary Files:
Usually we can use binary files to store binary data like images,video files, audio files etc
Opening a File:
Before performing any operation (like read or write) on the file,first we have to open that
file.For this we should use Python's inbuilt function open()
But at the time of open, we have to specify mode,which represents the purpose of
opening file.
f = open(filename, mode)
The allowed modes in Python are
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
ex: f = open("sample.txt","w")
We are opening sample.txt file for writing data.
Closing a File:
After completing our operations on the file,it is highly recommended to close the file.
For this we have to use close() function.
f.close()
Open a File on the Server
Assume we have the following file, located in the same folder as Python:
sample.txt
The open() function returns a file object, which has a read() method for reading the content of the file:
ex:
f = open("sample.txt", "r")
print(f.read())
f.close()
o/p:
Hello Good evening.
This file is for testing purposes.
This is python training session.
f = open("sample.txt", "r")
print(f.read(5))
o/p: Hello
f = open("sample.txt", "r")
print(f.readline())
o/p:
Hello Good evening.
f = open("sample.txt", "r")
print(f.readline())
print(f.readline())
o/p:
Hello Good evening.
This file is for testing purposes.
close the file:
f = open("sample.txt", "r")
print(f.readline())
f.close()
Ex:
Open the file "sample.txt" and append content to the file:
f = open("sample.txt", "a")
f.write("welcome to hyd")
f.close()
o/p:
Hello Good evening.
This file is for testing purposes.
This is python training session.welcome to hyd
f = open("sample.txt", "w")
f.write("welcome to hyd")
f.close()
#open and read the file after the appending:
f = open("sample.txt", "r")
print(f.read())
o/p:
welcome to hyd
Delete a File:
To delete a file, you must import the OS module, and run its os.remove() function:
Ex:
Remove the file "demo.txt":
import os
os.remove("demo.txt")
Modules:
A group of functions, variables and classes saved to a file, which is nothing but module.
There are two types of modules
1.user defined module
2.pre defined module
1.user defined module:
Every Python file (.py) acts as a module.
Ex: mymodule.py
x=100
def add(a,b):
print("The Sum:",a+b)
def product(a,b):
print("The Product:",a*b)
ex:
sample.py
def wish(name):
print("hello good evening,"+name)
test.py
import sample
sample.wish("prasanna")
o/p:hello good evening ,prasanna
Note:
whenever we are using a module in our program, for that module compiled file will be
generated and stored in the hard disk permanently.
Renaming a module at the time of import (module aliasing):
Ex:
import mymodule as m
here mymodule is original module name and m is alias name.
We can access members by using alias name m
ex:
emp.py
employee={"name":"ram","age":32,"address":"hyd"}
test.py
import emp as e
print(e.employee["age"])
o/p:c:\useres\kolla>py test.py
32
2.pre defined module:
Python provides different inbuilt modules.
This module defines several functions which can be used.
The main important modules are
math module
datetime module
os module
platform module
random module etc
The Math Module:
Python has also a built-in module called math, which extends the list of mathematical functions.
To use it, you must import the math module:
import math
This module defines several functions which can be used for mathematical operations.
The main important functions are
1. sqrt(x)
2. ceil(x)
3. floor(x)
4. fabs(x)
5. log(x)
6. sin(x)
7. tan(x)
ex:
import math
print(sqrt(25))
print(ceil(10.1))
print(floor(10.1))
print(fabs(-10.6))
print(fabs(10.6))
print(math.pi)
Output
5.0
11
10
10.6
10.6
3.141592653589793
import datetime
x = datetime.datetime.now()
print(x)
o/p:2021-05-11 10:15:54.991551
import datetime
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))
o/p:
2021
Tuesday
OS Module:
The OS module in Python provides functions for interacting with the operating system. OS comes under Python’s st
andard utility modules. This module provides a portable way of using operating system-dependent functionality. The
*os* and *os.path* modules include many functions to interact with the file system.
ex:
import os
print(os.getcwd())
o/p:C:\Users\kolla>
Random Module:
The random module is a built-in module to generate the pseudo-random variables. It can be used perform some actio
n randomly such as to get a random number, selecting a random elements from a list, shuffle elements randomly, etc
.
The Platform module is used to retrieve as much possible information about the platform on which the program is be
ing currently executed.
ex:
# Python program to display platform processor
# import module
import platform
# displaying platform processor
print('Platform processor:', platform.processor())
# import module
import platform
# import module
import platform
Exception Handling:
In any programming language there are 2 types of errors are possible.
1. Syntax Errors
2. Runtime Errors
1. Syntax Errors:
The errors which occurs because of invalid syntax are called syntax errors.
Ex1:
x=10
if x==10
print("Hello")
SyntaxError: invalid syntax
Ex2:
print "Hello"
SyntaxError: Missing parentheses in call to 'print'
Note:
Programmer is responsible to correct these syntax errors. Once all syntax errors are
corrected then only program execution will be started.
2. Runtime Errors:
Also known as exceptions.
While executing the program if something goes wrong because of end user input or
programming logic or memory problems etc then we will get Runtime Errors.
Ex: print(10/0) ==>ZeroDivisionError: division by zero
print(10/"ten") ==>TypeError: unsupported operand type(s) for /: 'int' and 'str'
x=int(input("Enter Number:"))
print(x)
D:\Python_classes>py test.py
Enter Number:ten
ValueError: invalid literal for int() with base 10: 'ten'
Note: Exception Handling concept applicable for Runtime Errors but not for syntax errors
What is Exception:
An unwanted and unexpected event that disturbs normal flow of program is called
exception.
Ex:
ZeroDivisionError
TypeError
ValueError
FileNotFoundError
EOFError
SleepingError
TyrePuncturedError
It is highly recommended to handle exceptions. The main objective of exception handling
is Graceful Termination of the program(i.e we should not block our resources and we
should not miss anything)
Exception handling does not mean repairing exception. We have to define alternative way to continue rest of the pro
gram normally.
Python Exception:
An exception can be defined as an unusual condition in a program resulting in the interruption in the flow of the pro
gram.
Whenever an exception occurs, the program stops the execution, and thus the further code is not executed. Therefore
, an exception is the run-time errors that are unable to handle to Python script. An exception is a Python object that r
epresents an error
Python provides a way to handle the exception so that the code can be executed without any interruption. If we do n
ot handle the exception, the interpreter doesn't execute all the code that exists after the exception.
Python has many built-in exceptions that enable our program to run without interruption and give the output. These
exceptions are given below:
Common Exceptions:
Python provides the number of built-in exceptions, but here we are describing the common standard exceptions. A li
st of common exceptions that can be thrown from a standard Python program is given below.
Suppose we have two variables a and b, which take the input from the user and perform the division of these values.
What if the user entered the zero as the denominator? It will interrupt the program execution and through a ZeroDivi
sion exception. Let's see the following example.
Example:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d" %c)
#other code:
print("Hi I am other part of the program")
Output:
Enter a:10
Enter b:0
Traceback (most recent call last):
File "exception-test.py", line 3, in <module>
c = a/b;
ZeroDivisionError: division by zero
The above program is syntactically correct, but it through the error because of unusual input. That kind of programm
ing may not be suitable or recommended for the projects because these projects are required uninterrupted execution
. That's why an exception-handling plays an essential role in handling these unexpected exceptions. We can handle t
hese exceptions in the following way.
Exception handling in python
The try-expect statement
If the Python program contains suspicious code that may throw the exception, we must place that code in the try blo
ck. The try block must be followed with the except statement, which contains a block of code that will be executed if
there is some exception in the try block.
try:
#block of code
except Exception1:
#block of code
except Exception2:
#block of code
#other code
Consider the following example.
Example 1
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
except:
print("Can't divide with zero")
Output:
Enter a:10
Enter b:0
Can't divide with zero
We can also use the else statement with the try-except statement in which, we can place the code which will be exec
uted in the scenario if no exception occurs in the try block.
The syntax to use the else statement with the try-except statement is given below.
try:
#block of code
except Exception1:
#block of code
else:
#this code executes if no except block is executed
Enter a:10
Enter b:0
can't divide by zero
<class 'Exception'>
THe except statement with no exception:
Python provides the flexibility not to specify the name of exception with the exception statement.
Example
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except:
print("can't divide by zero")
else:
print("Hi I am else block")
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
# Using exception object with the except statement
except Exception as e:
print("can't divide by zero")
print(e)
else:
print("Hi I am else block")
Output:
Enter a:10
Enter b:0
can't divide by zero
division by zero
Points to remember:
Python facilitates us to not specify the exception with the except statement.
We can declare multiple exceptions in the except statement since the try block may contain the statements which thr
ow the different type of exceptions.
We can also specify an else block along with the try-except statement, which will be executed if no exception is rais
ed in the try block.
The statements that don't throw the exception should be placed inside the else block.
Example
try:
#this will throw an exception if the file doesn't exist.
fileptr = open("file.txt","r")
except IOError:
print("File not found")
else:
print("The file opened successfully")
fileptr.close()
Output:
else:
#block of code
Consider the following example.
try:
a=10/0;
except(ArithmeticError, IOError):
print("Arithmetic Exception")
else:
print("Successfully Done")
Output:
Arithmetic Exception
The try...finally block
Python provides the optional finally statement, which is used with the try statement. It is executed no matter what ex
ception occurs and used to release the external resource. The finally block provides a guarantee of the execution.
We can use the finally block with the try block in which we can pace the necessary code, which must be executed be
fore the try statement throws an exception.
Syntax
try:
# block of code
# this may throw an exception
finally:
# block of code
# this will always be executed
try:
fileptr = open("file2.txt","r")
try:
fileptr.write("Hi I am good")
finally:
fileptr.close()
print("file closed")
except:
print("Error")
Output:
file closed
Error
Raising exceptions:
An exception can be raised forcefully by using the raise clause in Python. It is useful in in that scenario where we ne
ed to raise an exception to stop the execution of the program.
For example, there is a program that requires 2GB memory for execution, and if the program tries to occupy 2GB of
memory, then we can raise an exception to stop the execution of the program.
Syntax
raise Exception_class,<value>
Points to remember
To raise an exception, the raise statement is used. The exception class name follows it.
An exception can be provided with a value that can be given in the parenthesis.
To access the value "as" keyword is used. "e" is used as a reference variable which stores the value of the exception.
We can pass the value to an exception to specify the exception type.
Example
try:
age = int(input("Enter the age:"))
if(age<18):
raise ValueError
else:
print("the age is valid")
except ValueError:
print("The age is not valid")
Output:
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
if b is 0:
raise ArithmeticError
else:
print("a/b = ",a/b)
except ArithmeticError:
print("The value of b can't be 0")
Output:
Enter a:10
Enter b:0
The value of b can't be 0
OOPS:
Like other general-purpose programming languages, Python is also an object-oriented language since its beginning.
It allows us to develop applications using an Object-Oriented approach. In Python, we can easily create and use clas
ses and objects.
An object-oriented paradigm is to design the program using classes and objects. The object is related to real-word en
tities such as book, house, pencil, etc. The oops concept focuses on writing the reusable code. It is a widespread tech
nique to solve the problem by creating objects.
Class
Object
Method
Inheritance
Polymorphism
Data Abstraction
Encapsulation
Python Classes/Objects:
Create a Class:
The class can be defined as a collection of objects. It is a logical entity that has some specific attributes and methods.
For example: if you have an employee class, then it should contain an attribute and method, i.e. an email id, name, a
ge, salary, etc.
Syntax:
class ClassName:
<statement-1>
.
.
<statement-N>
Example
Create a class named MyClass, with a property named x:
class MyClass:
x=5
o/p:<class '__main__.MyClass'>
Create Object:
The object is an entity that has state and behavior. It may be any real-world object like the mouse, keyboard, chair, t
able, pen, etc.
Everything in Python is an object, and almost everything has attributes and methods. All functions have a built-in att
ribute __doc__, which returns the docstring defined in the function source code.
When we define a class, it needs to create an object to allocate the memory. Consider the following example.
Example:
class car:
def __init__(self,modelname, year):
self.modelname = modelname
self.year = year
def display(self):
print(self.modelname,self.year)
c1 = car("Toyota", 2016)
c1.display()
Output:
Toyota 2016
In the above example, we have created the class named car, and it has two attributes modelname and year. We have
created a c1 object to access the class attribute. The c1 object will allocate memory for these values.
Example:
Create an object named p1, and print the value of x:
class MyClass:
x=5
p1 = MyClass()
print(p1.x)
o/p:5
The examples above are classes and objects in their simplest form, and are not really useful in real life applications.
To understand the meaning of classes we have to understand the built-in __init__() function.
All classes have a function called __init__(), which is always executed when the class is being initiated.
Use the __init__() function to assign values to object properties, or other operations that are necessary to do when th
e object is being created:
Example:
Create a class named Person, use the __init__() function to assign values for name and age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("thiru", 32)
print(p1.name)
print(p1.age)
output: thiru
32
Note: The __init__() function is called automatically every time the class is being used to create a new object.
Object Methods:
Objects can also contain methods. Methods in objects are functions that belong to the object.
Let us create a method in the Person class:
Example:
Insert a function that prints a greeting, and execute it on the p1 object:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("thiru", 32)
p1.myfunc()
o/p:
Hello my name is thiru
Note: The self parameter is a reference to the current instance of the class, and is used to access variables that belong
to the class.
It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any functi
on in the class:
Example
Use the words mysillyobject and abc instead of self:
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("thiru", 32)
p1.myfunc()
output: Hello my name is thiru
Example
Set the age of p1 to 40:
p1.age = 40
Delete Object Properties
You can delete properties on objects by using the del keyword:
Example
Delete the age property from the p1 object:
del p1.age
Delete Objects
You can delete objects by using the del keyword:
Example
Delete the p1 object:
del p1
The pass Statement:
class definitions cannot be empty, but if you for some reason have a class definition with no content, put in the pass
statement to avoid getting an error.
Example:
class Person:
pass
Inheritance:
Inheritance is a mechanism to aquired the properties from one class to another class is called inheritance.
The old class is called parentclss/base class/super class
The new clas is called child class/derived class/sub class
we can create object to sub class only
advantages:
1.Reusability
2.Code become mainatians very easily
3.parallel developement is possiable
Types:
1.single inheritance
2.multi level inheritance
3.multiple inheritance
4.hirarical inheritance
5.hybrid inherince
sample application:
class Person:
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname
def display(self):
print(self.fname, self.lname)
class Student(Person):
pass
x = Student("thiru", "kolla")
x.display()
o/p:thiru kolla
mysql queries:
1)create a database:
create database databasename;
ex:create database employee;
2)display the database:
show databases;
3)use/select the database:
use databasename;
ex:use employee;
4)delete the database:
drop database databsename;
ex:drop database covid19;
5)create table:
create table tablename(colomn1,colomn2,---);
ex:create table pythonemp(id int ,name varchar(40),desig varchar(20),age int,primary key(id));
6)display the table:
show tables;
7)see the table structure:
describe tablename
ex:describe pythonemp;
8)alter the table:
alter table tablename add newcolomn[first|after colomn name]
ex:alter table pythonemp add address varchar(40);
9)deleting the column:
alter table pythonemp drop column desig;
10)select the table:
select *from tablename;
ex:select * from employee;
11)rename the table:
alter table tablename rename to newtablename;
ex:alter table pythonemp rename to emptable;
12)inserting table values:
insert into tablename values();
ex:insert into emptable(101,"Ram","hyd")
13)update the queary:
update emptable set name="john",address="blr" where id=101;
14)deleting the query:
delete from emptable where id="101"
15)deleting the table:
drop table tablename;
drop table emptable;
MySQL Database:
Install MySQL Driver:
Python needs a MySQL driver to access the MySQL database.
we will use the driver "MySQL Connector".
We recommend that you use PIP to install "MySQL Connector".
PIP is most likely already installed in your Python environment.
Download and install "MySQL Connector":
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>python -m pip install mysql-connector
-python
Test MySQL Connector:
To test if the installation was successful, or if you already have "MySQL Connector" installed, create a Python page
with the following content:
demo_mysql_test.py:
import mysql.connector
#if this page is executed with no errors, you have the "mysql.connector" module installed.
Create Connection:
Start by creating a connection to the database.
demo.py:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
print(mydb)
There are the following steps to connect a python application to our database.
('demodb',)
('empdatabase',)
('employee',)
('hospital',)
('hospitaldb',)
('information_schema',)
('kolladb',)
('library',)
>>> db=mysql.connector.connect(host="localhost",user="root",password="Kolla*1986",database="hospitaldb")
>>> cur=db.cursor()
>>> cur.execute("create table hospital(code int,name varchar(20),address varchar(20))")
>>> cur.execute("show tables")
>>> for x in cur:
print(x)
('hospital',)
>>> db=mysql.connector.connect(host="localhost",user="root",password="Kolla*1986",database="hospitaldb")
>>> cur=db.cursor()
>>> sql="insert into hospital(code,name,address) values(%s,%s,%s)"
>>> val=(1,"prime","Hyderabad")
>>> cur.execute(sql,val)
>>> db.commit()
>>> cur.execute("select * from hospital")
>>> res=cur.fetchall()
>>> for x in res:
print(x)
Numpy:
NumPy is a Python library used for working with arrays.
It also has functions for working in domain of linear algebra, fourier transform, and matrices.
NumPy was created in 2005 by Travis Oliphant. It is an open source project and you can use it freely.
NumPy stands for Numerical Python.
In Python we have lists that serve the purpose of arrays, but they are slow to process.
NumPy aims to provide an array object that is up to 50x faster than traditional Python lists.
The array object in NumPy is called ndarray, it provides a lot of supporting functions that make working with ndarra
y very easy.
Arrays are very frequently used in data science, where speed and resources are very important.
NumPy arrays are stored at one continuous place in memory unlike lists, so processes can access and manipulate the
m very efficiently.
This is the main reason why NumPy is faster than lists. Also it is optimized to work with latest CPU architectures.
NumPy is a Python library and is written partially in Python, but most of the parts that require fast computation are
written in C or C++.
Installation of NumPy:
If you have Python and PIP already installed on a system, then installation of NumPy is very easy.
import numpy
Now NumPy is imported and ready to use.
Example
import numpy
print(arr)
o/p:[1 2 3 4 5]
Now the NumPy package can be referred to as np instead of numpy.
Example
import numpy as np
print(arr)
o/p:[1 2 3 4 5]
Create a NumPy ndarray Object:
NumPy is used to work with arrays. The array object in NumPy is called ndarray.
Example
import numpy as np
print(arr)
print(type(arr))
o/p:
[1 2 3 4 5]
<class 'numpy.ndarray'>
type(): This built-in Python function tells us the type of the object passed to it. Like in above code it shows that arr is
numpy.ndarray type.
To create an ndarray, we can pass a list, tuple or any array-like object into the array() method, and it will be converte
d into an ndarray:
Dimensions in Arrays:
A dimension in arrays is one level of array depth (nested arrays).
0-D Arrays:
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.
Example
Create a 0-D array with value 42
import numpy as np
arr = np.array(20)
print(arr)
o/p:20
1-D Arrays:
An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.
Example
Create a 1-D array containing the values 1,2,3,4,5:
import numpy as np
print(arr)
o/p:
[1 2 3 4 5]
2-D Arrays:
An array that has 1-D arrays as its elements is called a 2-D array.
NumPy has a whole sub module dedicated towards matrix operations called numpy.mat
Example
Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6:
import numpy as np
print(arr)
o/p:
[[1 2 3]
[4 5 6]]
Access Array Elements:
Array indexing is the same as accessing an array element.
The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.
Example
Get the first element from the following array:
import numpy as np
print(arr[0])
print(arr[-2])
o/p:
1
3
Example
Get third and fourth elements from the following array and add them.
import numpy as np
print(arr[2] + arr[3])
o/p:37
Access 2-D Arrays:
To access elements from 2-D arrays we can use comma separated integers representing the dimension and the index
of the element.
Example
Access the 2nd element on 1st dim:
import numpy as np
Example
Print the last element from the 2nd dim:
import numpy as np
Example
Slice elements from index 1 to index 5 from the following array:
import numpy as np
print(arr[1:5])
o/p:[2 3 4 5]
Shape of an Array:
The shape of an array is the number of elements in each dimension.
Example
Print the shape of a 2-D array:
import numpy as np
print(arr.shape)
o/p:(2, 4)
Sorting Arrays:
Sorting means putting elements in an ordered sequence.
Ordered sequence is any sequence that has an order corresponding to elements, like numeric or alphabetical, ascendi
ng or descending.
The NumPy ndarray object has a function called sort(), that will sort a specified array.
Example
Sort the array:
import numpy as np
print(np.sort(arr))
o/p:[0 1 2 3]
Searching Arrays:
You can search an array for a certain value, and return the indexes that get a match.
Example
Find the indexes where the value is 4:
import numpy as np
x = np.where(arr == 4)
print(x)
o/p:(array([3, 5, 6]),)
Addition and Multiplication of Matrix:
Django:
Web Application:
The applications which will provide services over the web are called web applications.
Ex: gmail.com, facebook.com, etc
Every web application contains 2 main components
1) Front-End
2) Back-End
1) Front-End:
It represents what user is seeing on the website
We can develop Front-End content by using the following technologies:
HTML, JS, CSS, JQuery and BootStrap
JQuery and Bootstrap are advanced front-end technologies, which are developed by
using HTML, CSS and JavaScript only.
HTML: HyperText Markup Language
Every web application should contain HTML. i.e HTML is the mandatory technology for
web development.It represents structure of web page
CSS: Cascading Style Sheets
It is optional technology, still every web application contains CSS.
The main objective of CSS is to add styles to the HTML Pages like colors, fonts, borders etc.
Java Script:
It allows to add interactivity to the web application including programming logic. The main objective of Java Script
is to add functionality to the HTML Pages. ie to add dynamic nature to the HTML Pages.
HTML Meant for Static Responses
HTML+JS Meant for Dynamic Responses
Ex1: To display "Welcome to DURGASOFT" response to the end user only HTML is
enough,b'z it is static response.
Ex2: To display current server date and time to the end user, only HTML is not enough
we required to use some extra technology like JavaScript,JSP,ASP,PHP etc as it is
dynamic response
Static Response vs Dynamic Response:
If the response is not varied from time to time and person to person then it is considered
as static response.
Eg: Login Page of Gmail
Home Page of ICICI Bank
If the response is varied from time to time and person to person then it is considered as
dynamic response.
Ex: Inbox Page of Gmail
Balance Page of ICICI Bank
2) Back End:
It is the technology used to decide what to show to the end user on the Front-End.
ie Backend is responsible to generate required response to the end user,which is
displayed by the Front-End.
Back-End has 3 important components:
1) The Language like Java,Python etc
2) The Framework like DJango,Pyramid,Flask etc
3) The Database like SQLite,Oralce,MySQL etc
For the Backend language Python is the best choice b'z of the following reasons:
Simple and easy to learn, libraries and concise code.
For the Framework DJango is the best choice b'z it is Fast, Secure and Scalable.
Django is the most popular web application framework for Python. DJango provides inbuilt database which is nothi
ng but SQLite, which is the best choice for database.
The following are various popular web applications which are developed by using
Python and DJango
YouTube, Dropbox, Quora, Instagram, Reddit, Yahoo Maps etc
DJango:
Django is a free and open-source web framework.
It is written in Python.
It follows the Model-View-Template (MVT) architectural pattern.
It is maintained by the Django Software Foundation (DSF)
It is used by several top websites like Youtube,Google,Dropbox,Yahoo Maps,
Mozilla,Instagram,Washington Times,Nasa and many more
https://www.shuup.com/blog/25-of-the-most-popular-python-and-django-websites/
Django was created in 2003 as an internal project at Lowrence Journal-World News
Paper for their web development.
The Original authors of Django Framework are: Adrian Holovaty, Simon Willison
After Testing this framework with heavy traffics, Developers released for the public as
open source framework on July 21st 2005.
The Django was named in the memory of Guitarist Django Reinhardt.
Official website: djangoproject.com
Top 5 Features of Django Framework:
Django was invented to meet fast-moving newsroom deadlines, while satisfying the tough
requirements of experienced Web developers.
The following are main important features of Django
1) Fast:
Django was designed to help developers take applications from concept to completion
as quickly as possible.
2) Fully loaded:
Django includes dozens of extras we can use to handle common Web development
tasks. Django takes care of user authentication, content administration, site maps, RSS
feeds, and many more tasks.
3) Security:
Django takes security seriously and helps developers avoid many common security
mistakes, such as SQL injection, cross-site scripting, cross-site request forgery and
clickjacking. Its user authentication system provides a secure way to manage user
accounts and passwords
4) Scalability:
Some of the busiest sites on the planet use Django’s ability to quickly and flexibly scale
to meet the heaviest traffic demands.
5) Versatile:
Companies, organizations and governments have used Django to build all sorts of
things — from content management systems to social networks to scientific
computing platforms.
Note:
1) As Django is specially designed web application framework, the most commonly
required activities will takes care automatically by Django and Hence Developer's life
will be simplified and we can develop applications very easily.
2) As Django invented at news paper,clear documentation is avilable including a sample
polling application.
3) https://docs.djangoproject.com/en/2.1/contents/
Django & Atom Installation AndDevelopment of First Web Application:
How to install django:
1. Make sure Python is already installed in our system
python --version
2. Install django by using pip
pip install django
pip install django == 1.11.9
D:\>pip install django
Collecting django
Downloading
https://files.pythonhosted.org/packages/51/1a/6153103322/Django-2.1-py3-none any.whl (7.3MB) 100% || 7.3MB 4
7kB/s
Collecting pytz (from django)
Downloading https://files.pythonhosted.org/packages/30/4e/
53b898779a/pytz-2018.5-py2.py3-none-any.whl (510kB)
100% || 512kB 596kB/s
Installing collected packages: pytz, django
Successfully installed django-2.1 pytz-2018.5
You are using pip version 9.0.3, however version 18.0 is ava
You should consider upgrading via the 'python -m pip install
3. To check django version:
py -m django --version
ATOM IDE/Editor:
Install ATOM IDE from the following link https://atom.io/
Speciality of ATOM IDE:
It is freeware.
It is open source.
It supports cross platform.
It provides several auto completion short-cuts for easy development etc
How to Configure Atom for Python:
1) Terminal Installation:
File-->Settings-->Install-->In the searchbox just type terminal->platform ide terminal
2) Python AutoCompletion:
File-->Settings-->Install-->In the searchbox just type python-->autocomplete-python
3) django:
File-->Settings-->Install-->In the searchbox just type django-->atom-django
4) How to Change Terminal from Powershell to Normal Command Prompt:
File-->Settings-->Install-->In the searchbox just type terminal-->platform-ide terminal -->settings-->Shell Override
C:\Windows\System32\cmd.exe
Django Project vs Django Application:
A Django project is a collection of applications and configurations which forms a full web application.
Ex: Bank Project
A Dango Application is responsible to perform a particular task in our entire web
application.
Ex: loan app
registration app
polling app etc
Project = Several Applications + Configuration Information
Note:
1) The Django applications can be plugged into other projects.ie these are reusable.
(Pluggable Django Applications)
2) Without existing Django project there is no chance of existing Django Application.
Before creating any application first we required to create project.
How to create Django Project:
Once we installed django in our system, we will get 'django-admin' command line tool,
which can be used to create our Django project.
django-admin startproject firstProject
D:\>mkdir djangoprojects
D:\>cd djangoprojects
D:\djangoprojects>django-admin start-project firstProject
The following project structure will be created
D:\djangoprojects>
|
+---firstProject
¦
¦---manage.py
¦
+---firstProject
¦---settings.py
¦---urls.py
¦--wsgi.py
¦-- __init__.py
__init__.py:
It is a blank python script.Because of this special file name, Django treated this folder as
python package.
Note: If any folder contains __init__.py file then only that folder is treated as Python
package.But this rule is applicable until Python 3.3 Version
settings.py:
In this file we have to specify all our project settings and and configurations like
installed applications, middileware configurations, database configurations etc
urls.py:
Here we have to store all our url-patterns of our project.
For every view (web page), we have to define separate url-pattern. End user can use
url-patterns to access our webpages.
wsgi.py:
wsgi Web Server Gateway Interface.
We can use this file while deploying our application in production on online server.
manage.py:
The most commonly used python script is manage.py
It is a command line utility to interact with Django project in various ways like to run
development server, run tests, create migrations etc.
How to Run Django Development Server:
We have to move to the manage.py file location and we have to execute the following
command.
py manage.py runserver
D:\djangoprojects\firstProject>py manage.py startserver
Performing system checks...
System check identified no issues (0 silenced).
You have 13 unapplied migration(s). Your project may not work properly until you apply
the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
August 03, 2018 - 15:38:59
Django version 1.11, using settings 'firstProject.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Now the server started
How to Send First Request:
Open browser and send request:
http://127.0.0.1:8000/
The following should be response if everything goes fine.
------------------------------------------------------------------------------
It worked!
Congratulations on your first Django-powered page.
Next, start your first app by running python manage.py startapp [app_label].
You're seeing this message because you have DEBUG = True in your Django settings file
and you haven't configured any URLs. Get to work!