234 CHAPTER 10 (Web server setup) BATTERIES INCLUDED Caution As

234 CHAPTER 10 BATTERIES INCLUDED Caution As you can see, the program specifies the file name C:database.dat. If you, by any chance, have a database by that name that the shelve module can use, it will and that database will be modified. So make sure that you use a file name for your database that isn t in use already. After running this program, the proper file appears. The program shown in Listing 10-8 has several interesting features: I have wrapped everything in functions to make the program more structured. (A possible improvement is to group those functions as the methods of a class.) I have put the main program in the main function, which is called only if __name__ == ‘__main__’. That means you can import this as a module and then call the main function from another program. I open a database (shelf) in the main function, and then pass it as a parameter to the other functions that need it. I could have used a global variable, too, because this program is so small, but it s better to avoid global variables in most cases, unless you have a reason to use them. After reading in some values, I make a modified version by calling strip and lower on them because if a supplied key is to match one stored in the database, the two must be exactly alike. If you always use strip and loweron what the user enters, you can allow him or her to be sloppy about using uppercase or lowercase letters and additional whitespace. Also, note that I ve used capitalize when printing the field name. I have used try and finally to ensure that the database is closed properly. You never know when something might go wrong (and you get an exception), and if the program terminates without closing the database properly, you may end up with a corrupt database file that is essentially useless. By using try and finally, you avoid that. So, let s take this database out for a spin. Here is the interaction between the program and me: Enter command (? for help): ? The available commands are: store : Stores information about a person lookup : Looks up a person from ID number quit : Save changes and exit ? : Prints this message Enter command (? for help): store Enter unique ID number: 001 Enter name: Mr. Gumby Enter age: 42 Enter phone number: 555-1234 Enter command (? for help): lookup Enter ID number: 001 What would you like to know? (name, age, phone) phone Phone: 555-1234 Enter command (? for help): quit
Check Tomcat Web Hosting services for best quality webspace to host your web application.

Comments are closed.