Software Environment
Software Environment
$ python
Python 2.4.3 (#1, Nov 11 2010, 13:34:43)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
Type the following text at the Python prompt and press the Enter −
1
If you are running new version of Python, then you would need to use print
statement with parenthesis as in print ("Hello, Python!");. However in Python
version 2.4.3, this produces the following result −
Hello, Python!
Script Mode Programming
Invoking the interpreter with a script parameter begins execution of the script and
continues until the script is finished. When the script is finished, the interpreter is
no longer active.
Let us write a simple Python program in a script. Python files have extension .py.
Type the following source code in a test.py file −
Live Demo
print "Hello, Python!"
We assume that you have Python interpreter set in PATH variable. Now, try to
run this program as follows −
$ python test.py
This produces the following result −
Hello, Python!
Let us try another way to execute a Python script. Here is the modified test.py file
−
Live Demo
#!/usr/bin/python
2
We assume that you have Python interpreter available in /usr/bin directory. Now,
try to run this program as follows −
Hello, Python!
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module
or other object. An identifier starts with a letter A to Z or a to z or an underscore
(_) followed by zero or more letters, underscores and digits (0 to 9).
Class names start with an uppercase letter. All other identifiers start with a
lowercase letter.
Starting an identifier with a single leading underscore indicates that the identifier
is private.
3
If the identifier also ends with two trailing underscores, the identifier is a
language-defined special name.
Reserved Words
The following list shows the Python keywords. These are reserved words and you
cannot use them as constant or variable or any other identifier names. All the
Python keywords contain lowercase letters only.
The number of spaces in the indentation is variable, but all statements within the
block must be indented the same amount. For example −
if True:
print "True"
else:
4
print "False"
However, the following block generates an error −
if True:
print "Answer"
print "True"
else:
print "Answer"
print "False"
Thus, in Python all the continuous lines indented with same number of spaces
would form a block. The following example has various statement blocks −
Note − Do not try to understand the logic at this point of time. Just make sure you
understood various blocks even if they are without braces.
#!/usr/bin/python
import sys
try:
# open file stream
file = open(file_name, "w")
except IOError:
print "There was an error writing to", file_name
sys.exit()
print "Enter '", file_finish,
print "' When finished"
while file_text != file_finish:
file_text = raw_input("Enter text: ")
5
if file_text == file_finish:
# close the file
file.close
break
file.write(file_text)
file.write("\n")
file.close()
file_name = raw_input("Enter filename: ")
if len(file_name) == 0:
print "Next time please enter something"
sys.exit()
try:
file = open(file_name, "r")
except IOError:
print "There was an error reading file"
sys.exit()
file_text = file.read()
file.close()
print file_text
Multi-Line Statements
Statements in Python typically end with a new line. Python does, however, allow
the use of the line continuation character (\) to denote that the line should
continue. For example −
total = item_one + \
item_two + \
item_three
Statements contained within the [], {}, or () brackets do not need to use the line
continuation character. For example −
6
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string
literals, as long as the same type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines. For example,
all the following are legal −
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
Comments in Python
A hash sign (#) that is not inside a string literal begins a comment. All characters
after the # and up to the end of the physical line are part of the comment and the
Python interpreter ignores them.
Live Demo
#!/usr/bin/python
# First comment
print "Hello, Python!" # second comment
This produces the following result −
Hello, Python!
You can type a comment on the same line after a statement or expression −
7
name = "Madisetti" # This is again comment
You can comment multiple lines as follows −
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
Following triple-quoted string is also ignored by Python interpreter and can be
used as a multiline comments:
'''
This is a multiline
comment.
'''
Using Blank Lines
A line containing only whitespace, possibly with a comment, is known as a blank
line and Python totally ignores it.
#!/usr/bin/python
8
Here, "\n\n" is used to create two new lines before displaying the actual line.
Once the user presses the key, the program ends. This is a nice trick to keep a
console window open until the user is done with an application.
Multiple Statements on a Single Line
The semicolon ( ; ) allows multiple statements on the single line given that
neither statement starts a new code block. Here is a sample snip using the
semicolon.
import sys; x = 'foo'; sys.stdout.write(x + '\n')
Multiple Statement Groups as Suites
A group of individual statements, which make a single code block are called
suites in Python. Compound or complex statements, such as if, while, def, and
class require a header line and a suite.
Header lines begin the statement (with the keyword) and terminate with a colon
( : ) and are followed by one or more lines which make up the suite. For example
−
if expression :
suite
elif expression :
suite
else :
suite
Command Line Arguments
Many programs can be run to provide you with some basic information about
how they should be run. Python enables you to do this with -h −
$ python -h
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
9
-c cmd : program passed in as string (terminates option list)
-d : debug output from parser (also PYTHONDEBUG=x)
-E : ignore environment variables (such as PYTHONPATH)
-h : print this help message and exit
You can also program your script in such a way that it should accept various
options. Command Line Arguments is an advanced topic and should be studied a
bit later once you have gone through rest of the Python concepts.
Python Lists
The list is a most versatile datatype available in Python which can be written as a
list of comma-separated values (items) between square brackets. Important thing
about a list is that items in a list need not be of the same type.
10
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses containing nothing −
tup1 = ();
To write a tuple containing a single value you have to include a comma, even
though there is only one value −
tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced, concatenated,
and so on.
Live Demo
#!/usr/bin/python
tup1[0]: physics
tup2[1:5]: [2, 3, 4, 5]
Updating Tuples
11
Accessing Values in Dictionary
To access dictionary elements, you can use the familiar square brackets along
with the key to obtain its value. Following is a simple example −
Live Demo
#!/usr/bin/python
dict['Name']: Zara
dict['Age']: 7
If we attempt to access a data item with a key, which is not part of the dictionary,
we get an error as follows −
Live Demo
#!/usr/bin/python
dict['Alice']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'
12
Updating Dictionary
You can update a dictionary by adding a new entry or a key-value pair,
modifying an existing entry, or deleting an existing entry as shown below in the
simple example −
Live Demo
#!/usr/bin/python
dict['Age']: 8
dict['School']: DPS School
Delete Dictionary Elements
You can either remove individual dictionary elements or clear the entire contents
of a dictionary. You can also delete entire dictionary in a single operation.
To explicitly remove an entire dictionary, just use the del statement. Following is
a simple example −
Live Demo
#!/usr/bin/python
13
del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
Note − del() method is discussed in subsequent section.
(a) More than one entry per key not allowed. Which means no duplicate key is
allowed. When duplicate keys encountered during assignment, the last
assignment wins. For example −
Live Demo
#!/usr/bin/python
14
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
print "dict['Name']: ", dict['Name']
When the above code is executed, it produces the following result −
dict['Name']: Manni
(b) Keys must be immutable. Which means you can use strings, numbers or
tuples as dictionary keys but something like ['key'] is not allowed. Following is a
simple example −
Live Demo
#!/usr/bin/python
Live Demo
#!/usr/bin/python
15
tup2 = ('abc', 'xyz');
To explicitly remove an entire tuple, just use the del statement. For example −
Live Demo
#!/usr/bin/python
16
After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in <module>
print tup;
NameError: name 'tup' is not defined
DJANGO
Django is a high-level Python Web framework that encourages rapid
development and clean, pragmatic design. Built by experienced developers, it
takes care of much of the hassle of Web development, so you can focus on
writing your app without needing to reinvent the wheel. It’s free and open source.
Django's primary goal is to ease the creation of complex, database-driven
websites. Django emphasizes reusabilityand "pluggability" of components, rapid
development, and the principle of don't repeat yourself. Python is used
throughout, even for settings files and data models.
17
Django also provides an optional administrative create, read, update and
delete interface that is generated dynamically through introspection and
configured via admin models
Create a Project
Whether you are on Windows or Linux, just get a terminal or a cmd prompt and
navigate to the place you want your project to be created, then use this code −
myproject/
manage.py
myproject/
__init__.py
settings.py
urls.py
wsgi.py
The Project Structure
18
The “myproject” folder is just your project container, it actually contains two
elements −
manage.py − This file is kind of your project local django-admin for interacting
with your project via command line (start the development server, sync db...). To
get a full list of command accessible via manage.py you can use the code −
urls.py − All links of your project and the function to call. A kind of ToC of your
project.
DEBUG = True
This option lets you set if your project is in debug mode or not. Debug mode lets
you get more information about your project's error. Never set it to ‘True’ for a
live project. However, this has to be set to ‘True’ if you want the Django light
server to serve static files. Do it only in the development mode.
19
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'database.sql',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
Database is set in the ‘Database’ dictionary. The example above is for SQLite
engine. As stated earlier, Django also supports −
MySQL (django.db.backends.mysql)
PostGreSQL (django.db.backends.postgresql_psycopg2)
Oracle (django.db.backends.oracle) and NoSQL DB
MongoDB (django_mongodb_engine)
Before setting any new engine, make sure you have the correct db driver
installed.
Now that your project is created and configured make sure it's working −
20
Validating models...
0 errors found
September 03, 2015 - 11:41:50
Django version 1.6.11, using settings 'myproject.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Create an Application
We assume you are in your project folder. In our main “myproject” folder, the
same folder then manage.py −
myapp/
__init__.py
admin.py
models.py
tests.py
views.py
__init__.py − Just to make sure python handles this folder as a package.
admin.py − This file helps you make the app modifiable in the admin interface.
21
models.py − This is where all the application models are stored.
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
)
Creating forms in Django, is really similar to creating a model. Here again, we
just need to inherit from Django class and the class attributes will be the form
fields. Let's add a forms.py file in myapp folder to contain our app forms. We
will create a login form.
myapp/forms.py
22
from django import forms
class LoginForm(forms.Form):
user = forms.CharField(max_length = 100)
password = forms.CharField(widget = forms.PasswordInput())
As seen above, the field type can take "widget" argument for html rendering; in
our case, we want the password to be hidden, not displayed. Many others widget
are present in Django: DateInput for dates, CheckboxInput for checkboxes, etc.
def login(request):
username = "not logged in"
if request.method == "POST":
#Get the posted form
MyLoginForm = LoginForm(request.POST)
if MyLoginForm.is_valid():
username = MyLoginForm.cleaned_data['username']
23
else:
MyLoginForm = Loginform()
<html>
<body>
<br>
24
<br>
</center>
</div>
</form>
</body>
</html>
The template will display a login form and post the result to our login view
above. You have probably noticed the tag in the template, which is just to prevent
Cross-site Request Forgery (CSRF) attack on your site.
{% csrf_token %}
Once we have the login template, we need the loggedin.html template that will be
rendered after form treatment.
<html>
25
<body>
You are : <strong>{{username}}</strong>
</body>
</html>
Now, we just need our pair of URLs to get started: myapp/urls.py
urlpatterns = patterns('myapp.views',
url(r'^connection/',TemplateView.as_view(template_name = 'login.html')),
url(r'^login/', 'login', name = 'login'))
When accessing "/myapp/connection", we will get the following login.html
template rendered −
Setting Up Sessions
In Django, enabling session is done in your project settings.py, by adding some
lines to the MIDDLEWARE_CLASSES and the INSTALLED_APPS options.
This should be done while creating the project, but it's always good to know, so
MIDDLEWARE_CLASSES should have −
'django.contrib.sessions.middleware.SessionMiddleware'
And INSTALLED_APPS should have −
'django.contrib.sessions'
By default, Django saves session information in database (django_session table
or collection), but you can configure the engine to store information using other
ways like: in file or in cache.
26
When session is enabled, every request (first argument of any view in Django)
has a session (dict) attribute.
Let's create a simple sample to see how to create and save sessions. We have
built a simple login system before (see Django form processing chapter and
Django Cookies Handling chapter). Let us save the username in a cookie so, if
not signed out, when accessing our login page you won’t see the login form.
Basically, let's make our login system we used in Django Cookies handling more
secure, by saving cookies server side.
For this, first lets change our login view to save our username cookie server side
−
def login(request):
username = 'not logged in'
if request.method == 'POST':
MyLoginForm = LoginForm(request.POST)
if MyLoginForm.is_valid():
username = MyLoginForm.cleaned_data['username']
request.session['username'] = username
else:
MyLoginForm = LoginForm()
27
def formView(request):
if request.session.has_key('username'):
username = request.session['username']
return render(request, 'loggedin.html', {"username" : username})
else:
return render(request, 'login.html', {})
Now let us change the url.py file to change the url so it pairs with our new view −
urlpatterns = patterns('myapp.views',
url(r'^connection/','formView', name = 'loginform'),
url(r'^login/', 'login', name = 'login'))
When accessing /myapp/connection, you will get to see the following page
28