Script for Displaying the Environment

While it is all very well and good to display simple HTML text in a Python script, there is obviously nothing very exciting about static text. The purpose of using Python in a Web script is to generate dynamic data. In this example, you are going to output, for the user, the current environment variable settings on the system. Note that these settings will be for the machine running the scripts, not the user's machine containing the browser. For testing purposes, this is usually the same...

Blank except Clauses

You might wonder what you do when you know there are possible exceptions out there, but really don't know what they might be. For example, as we've seen, there are numerous exceptions that can be thrown for a simple input statement. There are probably dozens of other possible errors that could occur for a single Python statement. How can you possibly write enough exception handling code to deal with them all Do you really have to list every single error that can occur and deal with each one...

Command Line Arguments

When you are working in the IDLE editor, it is normal to simply prompt the user for whatever information you want, or to simply set a variable equal to whatever you might want to use in your program in the interpreter. However, in the real world, it is quite common to use Python scripts from the command line to accomplish things. We do this sort of thing all the time, and rarely think about it. For example, we might want to use the command prompt to rename a file. To accomplish this, you open a...

Configure IDLE

The IDLE environment is extremely configurable. It provides ways to change virtually all of the key bindings, colors, and behaviors of the system. This is done within the configuration dialog. When you select the Configure IDLE option in the menu, you will be presented with the following dialog and the following tab on that dialog, as shown in Figure 3.13. IDLE configuration Fonts Tabs tab. The font part of the tab is fairly straightforward you can select the font that you want the text...

Context Menus

If you are accustomed to working on Windows or the Macintosh, you probably are accustomed to working with context menus. Context menus, or right-click menus as they are sometimes called, are menus that pop up when you press the right mouse button within a given context. For example, ifyou are working on an editing program, the context menu might contain editing commands like cut, copy, and paste. Adding these commands to your Python Tkinter program is really easy, and is something you should...

Creating a Class to Handle User Interfaces

There are two good reasons to wrap up the functionality for a given set of user interface code into a class. First, it makes it easier to read and edit the code for the user interface, and it makes the code a lot cleaner. Secondly, and more importantly, it makes it vastly easier to reuse and extend the code in other applications. It is extremely rare for a given piece of user interface functionality to be used only in one place at one time. Instead, it is much more common that you end up...

Creating a New Database

In order to create a new database, we will be using the MySQL Administrator GUI application. This application will be found in your MySQL group on the Start button of your Windows desktop. Launching the program will result in the display of the login screen, as shown in Figure 14.1. Your server host should be your local machine (localhost). You can leave all of the other bits of information alone, except for filling out the root password that you created during the install. You did remember to...

Decision Making and Iteration Keywords

Python contains multiple keywords used for looping, decision-making, and controlling of execution statement order. Here's a list of those keywords, along with a simple example of each one. You will learn more about decision-making and iteration control keywords in Chapter 4. Q break The break statement stops execution of a loop in Python. For example, you might want to stop a given loop when a condition is met. The following example will break out of a loop when the index value is odd. This...

Defining Functions in Python

The keyword for defining functions in Python is def. You use the def keyword (which has nothing to do with rap music or other musical things) in the following manner When the Python interpreter encounters a def statement, it knows that it is not supposed to actually execute the code. You can think of the function definition as a template (not in the standard programming terminology, but rather in the English usage) for code that will be executed only when it is needed. You can have as many...

Deleting Books

The final piece of the system that we will look at in this chapter is the deletion of books. There is one other component that will need to be written, modifying a book, but that code has really already been done here several times, and there is no good reason to go over it again. Simply placing the current value into the form fields and using an update statement rather than an insert statement will accomplish this task. Deletion, however, requires something new. You need not only to remove the...

Downloading and Installing

The first thing you will need to do to use the MySQL system in Python is to download it and install it. As of the writing of this book, the current version of MySQL is 5.0. You can obtain the binaries and installers for the system from www.mysql.com just click the Downloads button and navigate to the Community Server edition. The remainder of the install is fairly automatic. Simply select all of the default values. You will be asked for a root password. Enter one and remember to write it down...

Drawing on the Image

It really isn't a great deal of excitement to create a blank image. What people want to see is some sort of information displayed on the image surface. That's what we live for, as programmers, after all. The PIL modules provide a pretty rich set of functionality for drawing on an image surface, as well as ways in which to load existing images and modifying them. For now, however, let's just consider the various ways in which you might want to draw things on an image canvas. 1. Create a new file...

Dynamic HTML Displays Based on User Input

Suppose that you were creating a Web site that allowed the user to trade stocks. This Web site might have various elements to it, such as looking at your current stock portfolio, trading stocks, or simply seeing an account overview ofyour account. It would really be nice ifyou could simply allow the user to log in once to the site and specify what he wanted to do at the same time. Once his login credentials had been verified, it would be nice to be able to take him directly to the page that he...

Frame Widgets and Centering

Now that you understand how to create a simple window and add a label to it, let's add a little bit of complexity to the process. In this case, you are going to create a new type of widget, called a Frame, to the window, and center it within the parent window vertically and horizontally. You will then add a label as a child of the frame, also centered within the parent. To make the whole thing even more useful, you are going to actually specify a size for the main window, so that you can see...

General Language Keywords

The Python language has a number of keywords that can be used in virtually any kind of a statement, from a decision to a print statement. Here are a few of them that should be reasonably obvious to any programmer. Q and The and keyword is used to combine two values for boolean True or False equivalence. If a is True, as well as b being True, then a and b are True together. This is a normal programming convention. Q in The in keyword is used to see if something is a member of any sequence or...

Go to File Line

This option would appear to be the same as the Edit menu version of Go to Line. It is quite different however, as you will see. First, with the IDLE editor open in Immediate mode, and no modules listed, select the menu item. You will see an error message displayed that says The line you point at doesn't appear to be a valid file name followed by a line number. Well, that was clear as mud, wasn't it Actually, what the error is telling you is absolutely true. You may remember a while back we...

How Do You Pass an Argument to a Function

When you have a function defined, you list the names of the arguments you want the user to pass to the function. As you'll see in just a bit, they don't always have to pass in all of the arguments, but it is a good assumption to begin with. Arguments can be mutable, meaning that they can be modified within the function and returned changed to the caller. However, only some arguments can be mutable. Simple data types cannot be changed in a function. To illustrate this, let's look at some real...

Implementing the Database Tables

In order to implement your new application, you are going to need a new database in which to store the data. Let's call this database books, since that is the kind of information you are going to be storing in the database. To create a new database, you will use the MySQL Administration GUI application, as shown in Figure 15.1. This screen assumes that you have launched the administrator program and logged in as a root-level user with the correct password, as we covered in the previous chapter....

Implementing the Forms

The forms for your application will be created in scripting code, because you need to have various parts of the forms generated dynamically, based on the state of the system and what the user has selected. We'll begin with the main menu form, which looks like the one shown in Figure 15.4. Note that this is the view of the main form only when no one is currently logged in. When someone has logged into the system, it will appear to look like Figure 15.5. However, through the magic of Python...

In Conclusion

This chapter has been a fairly low-key tour of a major component of the Python programming language functions. As you have learned, functions are a great way to encapsulate code and hide the implementation of algorithms from the user, allowing them access to functionality without needing to understand how it works. We will be using functions and modules quite a bit in the remainder of the book, so it is important that you understand them now. In the next chapter, we'll be talking about a form...

Info

Taking a look at what is going on in this application, you see a few new items. The Entry field is created in the DoinputForm() function. The entry field creates a text entry area that the user can type whatever they want into it. You might notice the use of the grid() layout manager to define where the text entry fields and prompts appear on the form. The concept of a grid is certainly not new in user interfaces spreadsheets and such have been around for years. In Tkinter, the grid layout...

Inheritance

In several of the examples we've looked at so far in this chapter, you have seen a class defined in the following way Up to this point, we've pretty much ignored this part of the class definition, with the exception of the class name field itself. However, that little area within the parentheses is rather interesting. When you create a class and place the name of another class in the parentheses, you are inheriting from the parenthetical class. That is, your class name is really of type object....

Listing the Reviews

Obviously, if you are going to have people review books, you will want the ability to see what other people have said about the book. Listing the reviews is the step we will approach next. The process is pretty much the same as listing the books themselves, but with one important twist. Rather than simply selecting all of the books and displaying them, you need to use the information about the book to display all the connected records in the database. This is done by the select statement in...

Multiple except Clauses

The problem with errors isn't that they occur, but that they occur in such varied ways. For example, imagine that you are going to ask the user to enter a number and then use that number for a mathematical calculation. How many things can go wrong in this simple little exercise Quite a few, really. First, the user could interrupt the input, as we saw in the previous example. Next, he could enter a value that isn't a valid number, generating a ValueError that would crash your program. We could...

Multiple Inheritance

Python supports multiple inheritance, allowing you to derive from more than one base class at a time. This is different than chaining up from a single base class along a specific route of inherited classes. In multiple inheritance, you combine separate base classes that are not involved with each other to form a group of classes from which a derived class is 'built. Before we discuss multiple inheritance, a few warnings are in order. First, there are those in the object-oriented community who...

Opening an Existing Database

In order to work with a database, you need to connect to it first. Let's write a very simple program that will do this 1. Create a new file using the IDLE editor or your favorite text editor. Call the file 2. Enter the following code into your new file Do the proper import import MySQLdb db user python-test, passwd python, db python-test) Note that although some lines may appear to be on multiple lines, they are really a single line in the editor. They may be too long to place on a single line...

Package and Module Handling Keywords

As you will see later, Python provides ways to organize your code. The methods include packaging your code or writing your own modules. To utilize these organizational techniques, you use the package and module handling keywords. We will learn more about these keywords and their usage in Chapter 6, Input and Output. Q global The global statement makes a variable that would otherwise be defined locally to be available outside the scope of the function you are using it in. For example, if you...

Path Browser

The Python system uses the sys.path value to determine the roots from which to load all modules and search for things. For example, in the Open Module menu selection, the sys. path path is used to define the directories on the local system and any network paths to use to find things. Now, you might wonder where this information comes from. There is no setting in the IDLE application to define the system path, but the Path Browser is something else entirely. So before...

Properties

Python classes would be of very little use as data collections if there were no way to store data in one, so Python provides a way to store data in classes. This is called a property definition (or, in Fythonese, an attribute) for a class. Unlike some other languages, Python provides no way to predefine a property for a class. Instead, property definitions simple come into being as soon as they are used. For example, you could define a class with a property called name like this You access the...

Python Language Overview

In order to really understand a language, you need to know the components that make up that language. In the case of a programming language, the elements that make up the language are its syntax, its keywords, and the style with which the language expresses itself. To begin with, let's take a simple look at some Python code. Since Python is an interpreted language, there is really no need for the usual start and end blocks you can simply select the pieces that you want to run and type them into...

Radio Buttons and Check Button

When it comes to allowing the user to make choices, there are really two ways programming languages go about it. First, you can allow the user to simply type in an answer to a question. This goes along the lines of What color do you want the background to be followed by an input field that lets you type in things like white or red. Obviously, aside from the problem of misspellings, this is a process that is fraught with error. You can get all sorts of answers you never expected, like the color...

Reading from a Database

Writing data to a database is easy enough, but the actual excitement for the user is seeing what is in that database. To find out what is in the database, you need to read the data from the database and then present it to the user. The reading function in SQL is called the select statement. The general form of the select statement is SELECT column-names-or-asterisk FROM table-names The reason for the ellipsis following the statement is that there are other, optional parts of the select...

Receiving Data from an HTML File

While one-sided conversations between a Web server and a Python script are often useful, it is considerably more interesting and useful to be able to supply a Python script with information from a Web page, and to generate output based on that input. In Python, the CGI module provides access to information sent by HTML pages containing input fields. These pages, called forms in the HTML world, can do the job of obtaining input from the user in a clean and user-friendly manner, and then pass...

Special Sequence Characters

In addition to the standard set of characters shown in the previous table, there are also some special sequence characters associated with regular expression parsing in Python (and all other languages that support regular expression parsing). The six most important sequence characters are Q d Matches any decimal digit. This is really the same as writing 0-9 , but is done so often that it has its own shortcut sequence. Q D Matches any non-decimal digit. This is the set of all characters that are...

System

The system module provides an interface to many of the Python specific routines that you need to provide a really nice user experience. In addition, it provides ways for you to get at information that you need when writing applications, and often the only way to get some of the information. For example, if you wanted to know what modules were compiled into the current interpreter, as opposed to those loaded at runtime, you would use the builtin_module_names attribute of the system module >...

The Edit Window

There are quite a few other windows within the IDLE environment, and we will discuss most of them as we get to them. The most important one to consider, for now at least, is the Editing window. To get to the Editing window, select File New Window from the main menu in IDLE. You should see a window that looks remarkably like the one shown in Figure 3.18. The majority of the menus and functionality of the Editing window are very similar to, if not the same as, the main IDLE Interpreter window....

The for Loop

The for loop is the basic looping structure in Python. The for loop is used for a lot of things, but primarily it is a foreach style loop, always working its way through a set of data values. If you are accustomed to working in another language, such as C or C++, you may be used to a for loop structure looking something like this for ( int i 1 i< 10 ++i ) do something. The basic structure of a for loop (or do loop, in some languages) in most languages is three-phase. First, there is an...

The GUI Tklnter

In today's programming world, the graphical user interface is king. Users no longer want command line programs that require them to type in commands or enter cryptic sequences of characters to accomplish their tasks. Instead, the computer world is all about point-and-click, drag-and-drop, Laurel and Hardy and, wait. No Laurel and Hardy, sorry, just got a bit carried away there. Hopefully, you get the idea. Today's world is about simplicity, and simplicity is about the easiest and most...

The input Function

The input() function is the first of the ways in which you can get data from the user in Python Command Line programs. The syntax of the input function is really quite simple. It looks like this < return> input( < prompt> ) prompt is a string that will be displayed for the user to view, which should give some sort of indication of the usage and type of data you are expecting. return is the returned value from the function. This will be the evaluated version of whatever is input....

The self Object

We briefly looked at an example, while looking at properties, of the sel f object. Put simply, the self object is the instance of the class that you are presently working upon within a class method. This isn't always clear, so let's look at a few very simple examples of what self means Assuming, in this code, that Foo is a class, then al, a2, and a3 are all instances of the Foo class. When you create them, you get a variable that you can use. Now, again assuming that the print_me method below...

The stat Module File Statistics

When you are working on a computer, you often want to know things about the files on your file system. For example, it is nice to know what files have been modified in a given directory, so that you can back them up to some sort of an archive system. When I am writing a book, for example, I often ask the file system for a list of files that have been modified most recently, in order to make sure that my backup copies are up-to-date. Have you ever wondered just how the file system knows what...

The Web Server Apache

The most popular use of Python in the corporate world is for writing scripts to be called from Web pages. In order to use a Web page, of course, you must somehow serve up that page to the user, so that he can interact with your scripts. The serving up of pages is accomplished by a Web server. The most popular open source Web server is the Apache Web Server from the Apache Software Foundation. You can find the Apache Web server at www.apache.org or httpd.apache.org. The Web server itself is...

Updating a Database

In the real world, things change, whether they are publication dates for new releases, or quantities for items for sale. Obviously, if you are using a database system to store information about your business, you need the ability to update the information when it changes. The SQL language was designed for such needs. The update statement is used to modify values in a database, allowing you to change data in a single record in the database or across all of the records at...

What Are Arguments

An argument is a bit of data that is passed into a function to provide a way to customize the functionality (if you will excuse the description) of the function. For example, you might pass in the current name of the user to a function used to greet people so that you can greet each user differently. Arguments can be any valid Python type, from strings to numbers, to tuples, dictionaries, or lists. The advantage to being able to pass in a function argument, rather than simply having functions...

What Is a Database

Put simply, a database is an organized collection of information. There are more technical definitions, but they really don't say much more than this. A text file is a database, as is a pile of magazines. There is nothing that says that a database must have a specific format, or be organized in particular ways, although we have come to understand that when a person says database, what he really mean is a relational database. A relational database is an organized collection of information that...

Working with Entry Fields and Grid Layouts

The most common use of user interface windows is to gather information from the user. Often, this information is in the form of free-form text, which cannot be collected by using a button or other selection mechanism, but must be typed in manually by the user. For this purpose, the Tkinter library provides the entry field widget. As a simple example, consider the input form shown in Figure 12.5. There is nothing particularly special about this input form. You might see something like this in...

Working with List Boxes

A common problem when dealing with user interface design is how to allow the user to select from a set of options, when that set of options may be variable in length. You might think to present a series of buttons, which we have already looked at, or a list of check boxes, which we will look at soon. A better alternative, however, is the list box. A list box displays a list of strings and allows the user to select one or more of the strings (at the programmer's discretion) to do something with....

Working with the Exception Information

When you are programming in Python and working with exceptions, there is information available to you that will allow you to print out things you want the end user to see, while permitting you to ignore showing the user things that really won't mean anything to them. There are three basic variables that you need to know about when you are working with Python exception handling, which are exc_type, exc_value, and exc_traceback. Let's take a brief look at each one and see what they are and why...

Working with Tklnter

There are two basic steps to creating a Tkinter application. First, you must import the Tkinter module. This is done using the standard import statement in Python. At the top of any application using Tkinter, you should add the following line Normally, you would never do something like this in Python, since it means importing the entire module and all of its components into your application. This is usually overkill for a module, as it will often have a lot of things you really don't need....

HTML Elements

Just to illustrate how all of the HTML elements map to their Python equivalents and how you can check to see what you are getting, let's write a very simple program that shows off the various types of HTML elements, such as radio buttons, check boxes, and so forth. Your input form is going to look like the one shown in Figure 13.8, which presents a very simple order form for pizzas. The HTML for this input form looks like this lt TITLE gt Choose your Pizza lt TITLE gt lt FORM lt First, the...

Your First Python CGI Script Hello Apache

The CGI Common Gateway Interface protocol is a standard way for external programs and application environments to interact with Web servers. While a plain HTML file on the Web is static, a CGI program or script is executed at the time that the request is made from the user, and the content is created on the fly. To see how this works, let's create a simple script in Python and have it executed by the Apache Web server. 1. Create a new file using the IDLE editor or your favorite text editor. 2....