04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

474 CHAPTER 25 ■ PROJECT 6: REMOTE EDITING WITH CGI<br />

As you’ll see, all of this is quite easy to do with the standard Python library module cgi and<br />

some plain Python coding. However, the techniques used in this application can be used for<br />

creating Web interfaces to all of your Python programs—pretty useful. (For example, you use<br />

the same CGI techniques in Chapter 15.)<br />

Useful Tools<br />

The main tool when writing CGI programs is, as discussed in Chapter 15, the cgi module, along<br />

with the cgitb module for debugging. See Chapter 15 for more information.<br />

Preparations<br />

The steps needed for making your CGI script accessible through the Web are described in detail<br />

in Chapter 15 in the section “Dynamic Web Pages with CGI.” Just follow those steps, and you<br />

should be fine.<br />

First Implementation<br />

The first implementation is based on the basic structure of the greeting script shown in<br />

Listing 15-7 (Chapter 15). All that’s needed for the first prototype is some file handling...<br />

For the script to be useful, it must store the edited text between invocations. Also, the<br />

form should be made a bit bigger than in the greeting script (simple3.cgi from Listing 15-7 in<br />

Chapter 15) and the text field should be changed into a text area. You should also use the POST<br />

CGI method instead of the default GET method. (Using POST is normally the thing to do if you<br />

are submitting large amounts of data.)<br />

The general logic of the program is as follows:<br />

1. Get the CGI parameter text with the current value of the data file as the default.<br />

2. Save the text to the data file.<br />

3. Print out the form, with the text in the textarea.<br />

In order for the script to be allowed to write to your data file, you must first create such a<br />

file (for example, simple_edit.dat). It can be empty or perhaps contain the initial document<br />

(a plain text file, possibly containing some form of markup such as XML or HTML). Then you<br />

must set the permissions so that it is universally writable, as described in Chapter 15. The<br />

resulting code is shown in Listing 25-1.<br />

Listing 25-1. A Simple Web Editor (simple_edit.cgi)<br />

#!/usr/bin/env python<br />

import cgi<br />

form = cgi.FieldStorage()

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!