import
The real power of Python is in its library modules. They provide a large and consistent set of Application Programming Interfaces (APIs) to many system libraries (often in a way independent of the operating system).
For example, if you need to use a random number generator, you can do:
>>> import random
>>> print random.randint(0, 9)
5
This prints a random integer between 0 and 9 (including 9), 5 in the example. The function randint
is defined in the module random
. It is also possible to import an object from a module into the current namespace:
>>> from random import randint
>>> print randint(0, 9)
or import all objects from a module into the current namespace (discouraged):
>>> from random import *
>>> print randint(0, 9)
or import everything in a newly defined namespace:
>>> import random as myrand
>>> print myrand.randint(0, 9)
In the rest of this book, we will mainly use objects defined in modules os
, sys
, datetime
, time
and cPickle
.
All of the web2py objects are accessible via a module called
gluon
, and that is the subject of later chapters. Internally, web2py uses many Python modules (for examplethread
), but you rarely need to access them directly.
In the following subsections we consider those modules that are most useful.
os
This module provides an interface to the operating system API. For example:
>>> import os
>>> os.chdir('..')
>>> os.unlink('filename_to_be_deleted')
Some of the
os
functions, such aschdir
, MUST NOT be used in web2py because they are not thread-safe.
os.path.join
is very useful; it allows the concatenation of paths in an OS-independent way:
>>> import os
>>> a = os.path.join('path', 'sub_path')
>>> print a
path/sub_path
System environment variables can be accessed via:
>>> print os.environ
which is a read-only dictionary.
sys
The sys
module contains many variables and functions, but the one we use the most is sys.path
. It contains a list of paths where Python searches for modules. When we try to import a module, Python looks for it in all the folders listed in sys.path
. If you install additional modules in some location and want Python to find them, you need to append the path to that location to sys.path
.
>>> import sys
>>> sys.path.append('path/to/my/modules')
When running web2py, Python stays resident in memory, and there is only one sys.path
, while there are many threads servicing the HTTP requests. To avoid a memory leak, it is best to check if a path is already present before appending:
>>> path = 'path/to/my/modules'
>>> if not path in sys.path:
... sys.path.append(path)
datetime
The use of the datetime module is best illustrated by some examples:
>>> import datetime
>>> print datetime.datetime.today()
2008-07-04 14:03:90
>>> print datetime.date.today()
2008-07-04
Occasionally you may need to time-stamp data based on the UTC time as opposed to local time. In this case you can use the following function:
>>> import datetime
>>> print datetime.datetime.utcnow()
2008-07-04 14:03:90
The datetime module contains various classes: date, datetime, time and timedelta. The difference between two date or two datetime or two time objects is a timedelta:
>>> a = datetime.datetime(2008, 1, 1, 20, 30)
>>> b = datetime.datetime(2008, 1, 2, 20, 30)
>>> c = b - a
>>> print c.days
1
In web2py, date and datetime are used to store the corresponding SQL types when passed to or returned from the database.
time
The time module differs from date
and datetime
because it represents time as seconds from the epoch (beginning of 1970).
>>> import time
>>> t = time.time()
1215138737.571
Refer to the Python documentation for conversion functions between time in seconds and time as a datetime
.
cPickle
This is a very powerful module. It provides functions that can serialize almost any Python object, including self-referential objects. For example, let’s build a weird object:
>>> class MyClass(object): pass
>>> myinstance = MyClass()
>>> myinstance.x = 'something'
>>> a = [1 , 2, {'hello':'world'}, [3, 4, [myinstance]]]
and now:
>>> import cPickle
>>> b = cPickle.dumps(a)
>>> c = cPickle.loads(b)
In this example, b
is a string representation of a
, and c
is a copy of a
generated by de-serializing b
.
cPickle can also serialize to and de-serialize from a file:
>>> cPickle.dump(a, open('myfile.pickle', 'wb'))
>>> c = cPickle.load(open('myfile.pickle', 'rb'))