We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 134
Python
The Complete Manual
The essential handbook for Python usersMARA AD
hi hR Rae
PARADA OD
AAAAAAAAAMAA A A
AAAAMAAAAAAAAA A
AAAAAMAAAMAAA A
AAAAAMAAAMAAA A he
AAAAAMAAAAAAA A
AAAAAAALAAAAA 4 db
AAAAAMAAAAAAAA A
AAAAAAA A 4
AAAAMAAAA A
AAAAMAA A he
er
4AAA 4A
4AMAA 4A
AAhA sa
AAA A
AAAAdAhd badd ddWelcome to
Python
The Complete Manual
Python is a versatile language and its rise in popularity is
certainly no surprise Its similarity to everyday language has
made ita perfect companion for the Raspberry Pi, which
is often a first step into practical programming. But don't
be fooled by its beginner-riendly credentials - Python has
plenty of more advanced functions. In this new edition,
you wil earn how to program in Python, discover amazing
projects to improve your understanding, and find ways to
Use Python to enhance your experience of computing, Youll
also create fun projects including programming a Space
Invaders clone and teaching your Raspberry Pi to multi-task.
Let's get coding!Python
The Complete Manual
Future PLE Quay House, The Ambury ath, BAL ILA,
Eaitorat
Compiles by Aiden Dalby & Adam Markiewicz
ead of Arta Design Greg Whitaker
Esitrial rectordon Whit
Managing Drector Grainne MeKenna
Photography
‘All copyrights and trademarsaare recognised and respacteck
Advertising
edt packs are avalableon request
‘Commercial Director Clare Dove
Intemational
Head of Pint Licensing Rachel Shaw
Teensingeafuturenetcom
Circulation
ood of Nevstrade Tm Mathers
Production
Hood of Production Mark Constance
Preducton Project Manager Matthew Eglinton
Aasertsing Production Manager Joanne Crosby
Digital Editions Controller Jason Hudson
Prosuction Managers Keely Miler, Nola Cokely,
‘Vivienne Calvert, Fran Twentyman
Distributed by Marketer, Church Place Canary Wharf Landon, EU SHU
‘ewvimarketorcecouk Tet C203 787 9001
Python The Complete Manual Fifteenth Edtion (CMBS6SS)
FUTURE Connectors
Wide
foee
26
Make web apps
Master this starter project
Build an app for Android
Take your appson the move
50 Python tips
Aselection of handy tips
Work with Python
50
58
64
72
Replace your shell
Say goodbye to Bash
Scientific computing
Discover NumPy’s power
Python for system admins
How to tweak your settings
Scrape Wikipedia
Start using Beautiful Soup
Create with Python
80 Tictactoewith Kivy
Programa simple game
86 MakeaPongclone
Enhance your game skills
aa
|
88 Programa Space
Invaders clone
Have fun with Pivaders
94 Space Invaders clone 2
Continue making Pivaders
Get started
with
On
8 Masterdass
Discover the basics of Python
Use Python with Pi
100
106
no
14
120
Using Python on Pi
Optimise your code
Use Python in Minecraft
Produce fantastic creations
Handle multiple task
Learn to multi-task with
your Raspberry Pi
Create a Pi-powered
virtual reality setup
Use Python-VRZero
Find and check
your phone
Discover andlog
Bluetooth devicesPython is a great programming language for both beginners and experts. It
is designed with code readability in mind, making it an excellent choice for
beginners who are still getting used to various programming concepts.
The language is popular and has plenty of libraries available, allowing
programmers to get a lot done with relatively little code.
You can make all Kinds of applications in Python: you could use the
Pygame frarnework to write simple 2D games, you could use the GTK
libraries to create a windowed application, or you could try something
a little ore ambitious lke an app such as creating one using Python's
; Bluetooth and Input libraries to capture the input from a USB keyboard and
~ relay the input events to an Android phone.
A For this tutorial we're going to be using Python 2 since that is the
A version that is most likely to be installed on your Linux distribution, 4
Inthe following tutorials, you'l leam how to create popular games using @
{
te
SN Pythi Well also sh how to add sound and Alt.
a oN ees fell also show you how to add sound and Al to o¢9
Se I ma og,Get started with Python Getting startedHello World
Let's get stuck in, and what better way than with the programmer's
bestfriend, the Hello World’ application! Start by opening a terminal.
its current working directory will be your home directory. I's probably
a good idea to make a directory for the files that well be creating in
this tutorial, rather than having then loose in your home directory.
You can create a directory called Python using the command mkdir
Python, Youtl then want to change into that directory using the
command cd Python,
The next step isto create an empty file using the command ‘touch’
followed by the filename. Our expert used the command touch
hello_world py. The final and most important part of setting up the
files making it executable. This allows us to run code inside the hello_
world,py fle. We do this with the command chmod +x hello_world
py. Now that we have our file set up, we can go ahead and open it up
in nano, or alternatively any text editor of your choice. Geciit is a great
editor with syntax highlighting support that should be available on any
distribution. Youll be able to install it using your package manager if
you don't have it already,
I Ciianetian-taptop ~18 mkdir Python
[liam@liam-laptop ~]$ cd Python/
I Cliam@liam-laptop Python]$ touch hello_world.py
[Liam@liam-laptop PythoniJ$ chmod +x hello_world.py
I Criametiam-taptop Pythons nano hello_world.py
ur Hello World program is very simple, it only needs two lines,
The fist line begins with a‘shebang’ (the symbol #! ~ also knownGet started with Python Getting started
as a hashbang) followed by the path to the Python interpreter. The
program loader uses this line to work out what the rest of the lines
need to be interpreted with. If youre running this in an IDE like IDLE,
you don't necessarily need to do this.
“The code that is actually read by the Python interpreters only a
single line. Were passing the value Hello World to the print function by
placing it in brackets immediately after we've called the print function.
Hello World is enclosed in quotation marks to indicate that it is a literal
value and should not be interpreted as source code. As we would
expect, the print function in Python prints any value that gets passed
toit from the console.
You can save the changes you've just made to the file in nano using
the key combination Ctrl+O, followed by Enter. Use Ctr}+X to exit nano.
H usr/bin/env python2
H printcHelto World”)
You can run the Hello World program by prefixing
its filename with / —in this case youd type:
Shello_world py
I Cliam@liam-laptop Python]$ ./hello_world.py
B tetto World
Variables and data types
A variable s @ name in source code that is associated with an area in
memory that you can use to store data, which isthen called upon
throughout the code. The data can be one of many types, including:
Ter Cesc
Float Rees eer eed
Corse ey
Sc aS cl Wo
Br)
‘A variable is associated with an area in
memory that you can use to store data”Getting started
Get started with Python
‘As well as these main data types, there are sequence types (technically,
asstring isa sequence type but is so commonly used we've classed it
asa main data type)
ited Ceres cubeeicce en
Pen eee cen es Cece cis
ees
tuple would be used for something like a co-ordinate, containing
an xand y value stored as a single variable, whereas a list is typicelly
used to store larger collections, The data stored in a tuple is immutable
because you aren't able to change values of individual elements in a
tuple. However, you can do so ina list.
It will also be useful to know about Python’ dictionary type. A
dictionary is a mapped data type. It stores data in key-value pairs.
This means that you access values stored in the dictionary using that
value's corresponding key, which i cfferent to how you would do it
with alist. In a list, you would access an element of the ist using that
element's index (a number representing where the element s placed
in the list).
Let’s work on a program we can use to demonstrate how to use
variables and different data types. I's worth noting at this point that
you don't always have to specify data types in Python, Feel free to
create this file in any editor you like. Everything will work just fine as
long as you remember to make the file executable. Were going to call
cours variables py.
Interpreted vs compiled languages
ted to machine
oRtaaan: Te)
aero clFull code listing
The following line creates
an integer variable called
hello_int with the #
value of 21, Notice how
itdoesn't need to goin
uotatton marks
The same principals
true of Boolean values
We create a tuple in
the following way
And alistin this way
You could
also create the
same lstin the
following way
Get started with Python Getting started
#V/usr/bin/env python2
4#We create a variable by writing the name of the
variable we want followed# by an equals sign,
which is followed by the value we want to store
in thee variable. For example, the following line
creates a variable called hello_str, containing the
string Hello World,
hello_str = “Hello World”
hello_int = 21
hello_bool = True
hello_tuple = (21, 32)
hello_list = [“Hello,”, “this”, “is”,
“a”, List")
4 This list now contains 5 strings. Notice that
there are no spaces# between these strings so if
you were to join them up so make a sentence #
you'd have to add a space between each element.
hello_list = list.
hello_list.append(“Hello,”)
hello_list.append(“this")
hello_list.append(“is")
hello_list.append(“a")
hello_list.append("list”) ww r )
following lines use the appendt function
ofthe ist type toad elements tothe
list This way of using af list sit
really very useful when working
with stings you know ofin
advance, butit canbe
useful when working with
dynamic data such as
user input. Thislist,
will overwrite the
firstlist without
any waning ¢Getting started
Get started with Python
We might as well as wet are using the same variable name as the
create dictionary previous lst
while we're at it
Notice how weve
hello_dict = { “first_name” : “Liam”,
aligned the colons “last_name”
below to make the “Fraser”,
code tidy “eye_colour” : “Blue” }
# Let's access some elements inside our
collectionst Well start by changing the value
of the last string in our hello_list and# add an.
exclamation mark to the end. The"list’string is
the Sth element # in the list. However, indexes
in Python are zero-based, which means the
# first element has an index of 0
Notice that there -
print(hello_list(4])
pes nae cee hello_list{4] += *
exclamation marks
ee ¥ The above line is the same as
print the element hello_list[4] = hello_list[4] + “!”
print(hello_list[4])
Remember =
that tuples are print(strhello_tuplefa))
immutable, — We can't change the value of those elements
although we Uke we just did with the list
can access the # Notice the use of the str function above to
elements of them explicitly convert the integer
tke so # value inside the tuple toa string before
printing it
Let's create a
sentence using -
the data in our __| print(hello_dict["first_name"] +""+ hello_
hello_dict dict(“last_name"] +"has" +
hello_dictl"eye_colour’} +" eyes”)
Amuch tidier way
Cf doing this would =
Betouse Pythons print(“(0}{1}has {2} eyes“formatthello_
sting formatter [| dictt’first_name"],
hello_dict("last_name"),
hello_dict{*eye_colour')))Get started with Python Getting started
Indentation in detail
tation
SCCM ec eae
ir ae
Tener
ne editor
Control structures
In programming, a control structure is any kind of statement that can
change the path that the code execution takes. For example, a control
structure that decided to end the program if a number was less than 5
would look something like this:
#1/usr/bin/env python2
import sys # Used for the sys.exit function
int_condition = 5
if int_condition < 6:
sys.exit(“int_condition must be >= 6")
else:
print(“int_condition was >= 6 - continuing”)
The path that the cade takes will depend on the value of
the integer int_condition. The code in the ‘i’ block will only be
executed if the condition is true. The import statement is used to
load the Python system library; the latter provides the exit function,
allowing you to exit the program, printing an error message. Notice
that indentation (in this case four spaces per indent) is used to indicate Sea
which statement a block of code belongs to. 'f' statements are
probably the most commonly used control structures. Other control
“The path the code takes will depend on
the value of the integer int_condition’Getting started Get started with Python
structures include: the following items, which you should be aware
of when using Python:
For statements, which allow you to iterate over items in
collections, or to repeat a piece of code again a certain number
of times;
= While statements, a loop that continues while the condition
istrue.
Wete going to write a program that accepts user input from the
ser to demonstrate haw control structures work Wete calling tt
constructpy. The for loop is using a local copy of the current value,
which means any changes inside the loop won't make any changes
affecting the list. On the other hand however, the ‘while’ loop is
directly accessing elements in the list, so you could change the list
there should you want to do so. We wil talk about variable scope in
some more detail later on in the article. The output from the above
program is as follows:
[liamélian-Laptop Python]$ ./
construct.py
How many integers? acd
You must enter an integer
(liamélian-Laptop Python]$ ./
construct.py
How many integers? 3
Please enter integer 1: t
You must enter an integer
Please enter integer 1: 5
Please enter integer 2: 2
Please enter integer 3: 6
Using a for loop
5
2
6
Using a while loop
5
2
6
“The ‘for’ loop uses a local copy, so
changes in the loop won't affect the list”Get started with Python Getting started
Full code listing
‘#1/ust/bin/env python
# We're going to write a program that will ask the
user to input an arbitrary
# number of integers, store them ina collection,
{and then demonstrate how the
Henne # collection would be used with various control
integers we want
in thelist structures.
import sys # Used for the sys.exit
function
target_int = raw_input(“How many
integers? “)
By now, the variable target_int contains a string
representation of
‘# whatever the user typed. We need to try and
convert that to an integer but
4 be ready to # deal with the error ifit’s not
Otherwise the program will
crash,
try:
lee io ste te) target_int = int(target_int)
integers except Valuefrror:
sys.exit(“You must enter an
integer”)
ints = listo) Ce.
These are used L
to keep track
ofhow many L count =? oe.
integers we
curently haveGetting started
Get started with Python
ifthe above
succeeds then
isint will be set
to true:isint
True
By now, the
user has given
up or we have
alistfiled with
integers. We can
loop through
these ina couple
of ways. The fist
iswith a forloop
# Keep asking for an integer until we have the
required number
while count < target_int:
new_int raw_input(“Please enter
integer {0}: “.format(count + 1))
isint = False
try
—f new.int = int(new.int)
except
print(“You must enter an
integer")
# Only carry on if we have an integer. IF not,
welllloop again
# Notice below | use ==, which is different from
=. The single equals isan
# assignment operator whereas the double
equals is a comparison operator.
if isint == True:
4# Add the integer to the collection
ints.append(new_int)
# Increment the count by 1
count #= 1
print(“Using a for loop")
for value in ints:
print(str(value))
# Orwith a while loop:
print(“Using a while loop”)
# We already have the total above, but knowingGet started with Python Getting started
the len function is very
# useful
total = len(ints)
count = @
while count < total:
print(str(intsfcount]))
count += 1
More about a Python list
Functions and variable scope
Functions are used in programming to break processes down
into smaller chunks. This often makes code much easier to read.
Functions can also be reusable if designed in a certain way. Functions
can have variables passed to them. Variables in Python are always
passed by value, which means that a copy of the variable is passed
to the function that is only valid in the scope of the function. Any
changes made to the original variable inside the function will be
discarded. However, functions can also return values, so this isn't an
issue. Functions are defined with the keyword def, followed by the
name of the function. Any variables that can be passed through are
put in brackets following the function's name, Multiple variables are
separated by commas. The names given to the variables in these
brackets are the ones that they will have in the scope of the function,
regardless of what the variable that's passed to the function is called.
Let's see this in action. The output from the program opposite is
as follows:
“Functions are defined with the keyword
def, then the name of the function”Getting started
Get started with Python
We are now outside
of the scope of
the modify_string
function, as we have
reduced the level of
indentation
———— 7
The test string
won't be changed
in this code
However, we
ccan call the
function lke this
#l/ust/bin/env python? # Below is a function
called modify_string, which accepts a variable
# that willbe called original in the scope of the
function. Anything # indented with 4 spaces
Under the function definition isin the
# scope.
def modify_string(original):
original += “ that has been
modified.”
# At the moment, only the local copy of this
string has been modified
def modify_string_return(original):
original += “ that has been
modified.”
# However, we can return our local copy to the
caller. The function ends as soon as the return
statement is used, regardless of where it # is in
the function,
return original
test_string = “This is a test string”
modify_string(test_string)
print(test_string)
test_string = modify_string_
return(test_string)
print(test_string)
# The function’s return value is stored in the
variable test string, # overwriting the original and
therefore changing the value that i # printed,
lliam@liam-laptop Python|$ /functions_and.
scope.py
This isa test string
Thisis a test string that has been modified,
Scope is an important thing to get the hang of otherwise it can
get you into some bad habits. Let's write a quick program to
demonstrate this. t's going to have a Boolean variable called cont,
which will decide ifa number will be assigned to a variable in an if
statement. However, the variable hasn't been defined anywhere
apart from in the scope ofthe if statement. Well finish off by trying
to print the variable.Get started with Python Getting started
‘#Y/ust/bin/env python2
cont = False
ifcont
var = 1234
printivar)
In the section of code above, Python will convert the integer toa string
before printing it. However, it's always a good idea to expicitly convert
things to strings — especially when it comes to concatenating strings
together. you try to use the + operator on a string and an integer,
there wil be an error because it's not explicitly clear what needs to
happen. The + operator would usually add two integers together.
Having said that, Python’ string formatter that we demonstrated
earlier is a cleaner way of doing that. Can you see the problem? Var has
only been defined in the scope of the ifstatement. This means that we
geta very nasty error when we try to access var.
{liameliam-laptop Python|s /scope-py
Traceback (most recent call last)
File*/scope.py' line 8, in
print var
Namefrror:name’var'is not defined
fF cont is set to True, then the variable will be created and we can
access itjust fine. However, ths is a bad way to do things. The correct
way is to initialize the variable outside of the scope of the if statement.
syusrbinlenv python2 a
cont = False
if cont y 2
var= 1234
ifvar =o:
printivar)Getting started
Seis
Get started with Python
The variable var is defined in a wider scope than the ifstatement,
and can still be accessed by the ifstatement. Any changes made to
var inside the ifstaternent are changing the variable defined in the
larger scope. This example doesnt realy do anything useful apart
from illustrate the potential problem, but the worst-case scenario has
gone from the program crashing to printing a zero. Even that doesn't
happen because we've added an extra construct to test the value of
var before printing it.
“Google, or any other search engine,
is very helpful if you are stuck with
anything, or have an error message you
can't work out how to fix"
eee
Bee ieee eee nana
aGet started with Python Getting started
Coding style
Its worth taking a littl time to talk about coding style. It’s simple to
write tidy code, The key is consistency. For example, you should always
name your variables in the same manner. It doesn't matter if you want
to use camelCase or use underscores as we have. One crucial thing is
to use self-documenting identifiers for variables. You shouldn't have
to guess what.a variable does. The other thing that goes with this isto
always comment your code. This will help anyone else who reads your
code, and yourselfin the future. It’s also useful to put a brief summary
at the top of a code file describing what the application does, or a part
of the application ifit's made up of multiple files.
Summary
This article should have introduced you to the basics of programming
in Python. Hopefully you are getting used to the syntax, indentation
and general look and feel of a Python program. The next step is
to lea how to come up with a problem that you want to solve,
and break it down into small steps that you can implement in a
programming language. Google, or any other search engine, is very
helpful. If you are stuck with anything, or have an error message you
can’t work out how to fix, stick it into Google and you should be a lot
closer to solving your problem. For example, if we Google ‘play mp3
file with python, the first link takes us to a Stack Overflow thread with a
bunch of useful replies. Don't be afraid to get stuck in - the real fun of
programming is solving problems one manageable chunk at a time.Introducing Python — Pythonessentials
Lay the foundations and build your knowledge
NSM Cuno t lpi pon era
edsse Mn Rur a aie syoke see) irises)
Mee nenge lee iNee ie o sigu ils ge)
systems (p.32) and the worldwide web (p.26). These easy 10-
follow tutorials will help you to cement the Python language
that you've learned, while developing a skill that is very helpful
in the current technology market. Welllfinish up by giving you
50 essential Python tips (p.40) to increase your knowledge and
TaPython essentialsIntroducing Python
What you'll need...
Python 2.7:
itpsiiwwrpytbonrgitownload/
releoses27
Django version 1.4:
tps eran dangopeojectcon
Make web apps with Python
Make web
apps with
Python
Python provides quick and easy way to build
oplications, including web apps. Find out how to
it to builc ‘ure-complete web app
Python is known for its simplicity and capabilities. At this point it is
so advanced that there is nothing you cannot do with Python, and
conqueting the web is one of the possibilities. When you are using
Python for web development you get access to a huge catalogue
of modules and community support ~ make the most of them.
Web development in Python can be done in many different
ways, right from using the plain old CGI modules to utilising fully
groomed web frameworks, Using the latter is the most popular
method of building web applications with Python, since it allows
you to build applications without worrying about al that low-level
implementation stuff. There are many web frameworks available for
Python, such as Django, TurboGears and Web2Py, For this tutorial
we will be using our current preferred option, Django.
The Django Project portable and can be integrated with
‘nei ther Django sites with very tte effort.
magazine issue tracker H's django adnin.py startproject
ludissueTracker
OT me seseeiringyfictues | Arie cectoy wl rested
tocteatenew Djangoproects. _Thiswill also act as the oot of your
Let's create one forourissuetracker —_—_ development web server that comes
project here with Django. Under the project
in Django, a projectrepresentsthe directory you wilfin the folowing
site andits settings. An application,on items.
theother hand, represents aspectic -_- manage.py:ython script to work with
feature ofthe site ike blogging or your project
tagging, The benefit ofthis approach is__ludlssueTracker: A python package
thatyour Django application becomes @directory with _init__py le) forMake web apps with Python
your project. This package isthe one
Containing your project’ settings and
configuration data
ludissueTracker/settings py: Thisfile
contains the configuration options
for the project.
ludissueTracker/urs py: Ths ile
contains various URL mappings.
wsgippy: An entry-point for WSG-
compatible web servers to serve your
project. Only useful when you are
deploying your project. For this tutorial
we wont be needing it,
Configuring the
Django project
0 Before we start working
Con the application, let's
configure the Django project,
as per our requirements
EditludlssueTrackersettings py
as follows (only pars requiring
modification are shown:
Database Settings: We willbe
Using SOLite3 as our database
system here
NOTE: Red text indicates new
code or
Updated code.
‘default’: {
I “ENGINE:
{jango.db, backends.
slites’,
‘NAME’: ludsite.
db3,
Path settings
Django requires an absolute
path for directory settings.
But we want to be able to
‘pass in the relative directory
teferences. In order todo that
we will add a helper Python
function. Insert the following
code at the top of the settings.
py file:
import os
Hl der getabspath(x):
return os,path.join(os.
path.abspath(os.path.
dirmane(_file_)), *)
Now update the path options:
ecode
Bf teecate_oirs = (
sgetabspath(‘tenplates')
BE septa root =
getabspath(‘nedia’)
Bi vepra_ur. = ‘/nedia"
Now we will need to enable the
‘admin interface for our Django
site, Ths is a neat feature of Django
‘which allows automatic creation of
an admin interface ofthe site based
con the data model. The admin
interface can be used to add and
manage content for a Django site
Uncomment the following line
BE InsTaLLeD_aPPs = (
H‘ajango.contrib.auth’,
‘django.contrib.
contenttypes",
‘django. contrib. sessions’,
‘django.contrib. sites’,
“django. contriib.messages'
HB ‘jango.contrib,
staticfiles’,
“django.contrib. admin’,
He # ‘django.contrib.
adnindocs’,
)
Creating ludissues app
OB nieservewserserte
primary app for oursite, called
ludissues. To do that, we will use the
manage py script:
I python manage.py startapp
“When you are using Python for web
Introducing Python
ludissues
We will need to enable this app in the
config file as well
IE INSTALLED_APPS = ¢
HB ‘django.contrib.adnin’,
Sudissues',
)
Creating the data model
OF Ressteparneve
define the data model
for our app. Please see the inline
comments to understand what is
happening here.
From djangodb import models:
Il We are importing the
user authentication module so
that we use the built
I in authentication model
in this app
I From django.contrib.auth
models import User
IE & We would also create an
admin interface for our app
from django.contrib import
admin
HA tuple to hold the
multi choice char fields
H+ First represents the
field name the second one
repersents the display name
TSSUE_STATUS CHOICES = (
Cnew’, ‘New’),
accepted’ ’Accepted’),
reviewed’ ’Reviewed’),
started’ Started’),
(closed’,'Closed"),
development you get access to a huge
catalogue of modules and support”Introducing Python
[elas Issue(nodels.Model):
TB # owner will be a
foreign key to the User
model which is already built
in Django
owner = models.Foreignke
y(User, nul =True,blank=True)
4 multichoice with
defaulting to “new
status = models.
CharField(nax_.
length=25,choices=ISSUE_
‘STATUS_CHOICES,default='new')
summary = models.
TextField()
# date time field which
will be set to the date time
when the record is created
opened_on = models.
DateTineField(‘date opened’,
‘auto_now_add=True)
‘modified_on = models,
DateTimeField(‘date modified’,
‘auto_now-True)
def name(self):
return self.sunmary.
split¢"\n’,1){)
IL & Admin front end for the
‘app. We are also configuring
some of the
He buitt in attributes for
the admin interface on
I & how to display the list,
how it willl be sorted
I # what are the search
fields etc.
class Issuesdmin(adnin,
NodelAdmin):
date hierarchy =
“opened_on’
List filter =
(‘status’,’owner’)
list_display = Cid’,’n
‘ame’,’status','owner",nodifi
ed_on’)
search fields =
['description’,'status’]
He register our site with
‘the Django admin interface
admin.site.
Make web apps with Python
register(Issue, IssueAdmnin)
To have the created data model
reflected in the database, un the
following command:
$ python manage.py synedb
Youll be also asked to create a
superuser frit:
You just installed Django’s auth
system, which means you don’t
have any superusers defined.
Would you like to create one
now? (yes/no): yes
Enabling the admin site
OS Tensesatey
enabled, but we need to enable
itn the usp fle — this contains
the regex-based URL mapping from
‘model to view. Update the ur.py fle
asfolows
BE from django.conf.urls import
patterns, include, url
Il from django.contrib import
admin
adinin.autodiscover()
B uripatterns = patterns(",
unl¢r’*acinin/”,
include(@dnin.site.urls),
)
Starting the Django
web server
Djangoincludesa builtin
web server whichis very
handy to debug and test Ojango
applications Let startit to see how
our admin interface works.
To stat the web server:
Is python manage.py
Ifyou do nothave any ertorsin your
code, the server should be available
‘on port 8000. To launch the admin
interface, navigate your browser to
http/flocalhost800dvadmin.
You wil be asked to log in here
Enter the username and password
thatyou created while you were
syncing the database
After logging in you will notice that
allthe apps installed in your pioject are
avalable here. We ae only interested in
the Auth and Ludlssues app.
You can dickthe +Add to add a
record, Click the Add button next to
Users and adda few users to the ste.
‘Once you have the users inside the
system, you can now adda few issues
tothe system
Home » Ludasues Issues» Add issue
Add issue
Owner
seas: mn
ome
omar
Click the Add button next to sues,
Here you will notice that you can enter
(Owner Status and Summary for the
issue. But what about the opened_on
and modified_on field that we
“It’s great that
the owner field
is automatically
populated with
details of the users
inside the site”Make web apps with Python Introducing Python
Site administration
~ Recent Actions
Soe add 7Change My Actions
Users acd Change None avalable
Issues Aad 7Change
sites add 7Change
Select issue to change
a
defined while modeling the app? Creating the public user include(edmin.site.urls)),
They are not here because thay are interface for ludissues >
not supposed to be entered by the * This ensures that all the requests wil be
User opened_on will automatically [At this point the admin processed by ludissues.ur ist.
cevotmssetmerscresars — OZ ineraces orn bt
modified_on will automaticaly set weneed a way todisplay the Creating ludissues.url
tothe date time on which an issue data that we have added using -
ismodified. the admin interface. But theres
Another coo thing stat no public interface. Let create aia eee
the onmer fields automatically itnow, iy) with the folowing content
populated with all the users inside We will have'to begin by W tron django.cont-uris
se oti ee import patterns, include, url
‘We have defined our Ist view to Urbspy (udissuetrackerus py laces aesneetesel|
show ID name status ovner and I urtpatterns = patterns¢”, Mseceteriaes
‘modified on'in the model. You I Tissues
canget to this view by navigating (7° include ludissues.
tohttpr/localhost8000/admin/ urls’),
+ dictionary wi
ludissues/ssue/ Be (r*adnins’, Il # dictionary with all theIntroducing Python
objects in ludissues
info = (
‘queryset':ludissues.
objects.all(),
3
If To save us writing lots of
python code
I # we are using the list_
detail generic view
H flist detail is the name of
view we are using
B urtpatterns =
patterns(‘django.views.generic.
List detail’,
I #issue-list and issue-detail
are the tenplate names
BE tuhich will be looked in the
default tenplate
directories
Burts object_
List’ info,nane="issue-list"),
url(r"*(P
To display an issue list and detail,
we are using a Django feature called
generic views In this case we are
Using views called ist and details This
allow us to create an issue list view
and issue detall view. These views are
then applied using the ssue_isthiml
‘and ssue_detailhtm template. In
the following steps we wil create the
template fies.
Setting up template and
media directories
In this step we will ceate the
template and media directories.
We have already mentioned the
template directory as,
‘TEMPLATE_DIRS = (
getabspath( templates’)
)
Make web apps with Python
Which translates to ludissusTracker!
ludisueTracker/templates/ Since
‘we willbe accessing the templates
from the ludissues app, the
complete drectory path would be
ludlssueTrackerudssueTiacker”
templates/ludissues, Create these
folders in your proect folder.
‘Ao, create the directory
ludisueTracker/ludissueTracker/media/
for holding the CSS fle. Copy the style
«ssl from the resources directory
ofthe code folder. To serve fies from
this folder, make itavalable publi.
(Open settings py and add these lines in
ludissueTracker/ludissucTracker/ spy:
I fron django.conf.urls import
patterns, include, url
HF from django.cont import
settings
[E+ Uncomment the next two
Lines to enable the adnin:
I from django.contrib import
adnin
‘adnin.autodiscover()
I uripatterns = patterns(“,
(7 include(‘ludissues.
urls’),
(r'tadnin/", includecadnin.
site.url),
("medias
(GPspatho.98django.views,
static.serve’,
(‘docunent_root':settings.
MEDIA_ROOT))
)
Creating the template files
TO mrpzsviloe loses
from the ludissueTiacker/
ludissueTiacker/templates directory
“To display an issue list and details here,
In Django, we start with the
ludlssueTrackertualssuetracker/
templates/basehhtm templte. Think of
itasthe master template which can be
inherited by slave ones
ludssuetrackerudssuetracker!
templates/basehtml
IDOCTYPE htm. PUBLIC “//
WaC//OTD XHTML Strict//EN”
BD + HYPERLINK “http://awa.
W3.org/TR/shtml1/OTD/xhtml-
strict.dtd” hetp://w.v3.0rg/TR/
xhtml1/OTD/xhtnli-strict.dtd">
LUD
Issue Tracker
1
XY" class="sel">View Issues
ev/l>
Admin
Sites/ar
1
HG endblock %
Here we are inheriting the base
himifile that we created eater.
for issue in object_Ist 96) runson the
object sent by the urlspy. Then we
are iterating on the object_Ist for
issueid and issuename.
Now we will crate ssue_detal
html. Thistemplate i responsible for
displaying the deta view of acase.
ludssueTiackerudlsucTracker!
‘templates/udssues/ssue_detal
him
BE (% extends ‘base.html’ %)
HG block title xIssue #(
object.id }} ~ (% endblock %}
BG block content %}
B shaatssue #(( object.id )
{{_object.status }}
span>
Rick Sekuloski - PYTHON - Master Python OOP Programming With One Guide Only! A Lot of Coding, Practice and Theory Learn Python With Hands-On Projects (2022)