Join Club ShowMeDo to Learn Python!

This series is a part of Club ShowMeDo. Click to learn why you should join our club with a simple monthly subscription.

  • We teach Python and all the cool modules
  • Topics include beginner Python, GUIs, Web and Desktop Apps
  • Long, specially crafted video tutorials just for you
  • Club video tutorials extend our normal Free content
  • Save your time - we've done the research for you
  • Keep your skills up-to-date
  • Learn at your own pace, everything you need is shown to you
  • Over 12 hours of archived material are waiting for you in the club

Name: [011] John Montgomery
Member: 102 months
Authored: 21 videos
Description: I'm a C/C++, Java and Python programmer living in Hove, UK. ...

Writing a Python CGI Wiki - saving changes and browser redirects [ID:680] (6/6)

in series: Introduction to Python web-programming: CGI

(Showmedo is undergoing major changes. To report any problems viewing the videos please email us and include browser and OS specifics. Cheers - Kyran.)

In this episode we modify our Python CGI wiki script so we can save edits we make to our pages. In addition after the changes are saved we issue a browser redirect, so the user will see the new changes without having to worry about resubmitting the edit form.

This episode highlights a minor drawback with the CGIHTTPServer module - it does not let us issue 302 Redirects. As this is the case we use an alternative method for our redirect. The correct method is outlined in more detail in this Python Cookbook Recipe.

#!/usr/bin/python

import cgi
import cgitb; cgitb.enable()
import os
import urllib

CONTENTS_DIR="contents"

def redirect(url):
	#print "Status: 302 Moved"
	#print "Location: %s" % url
	#print
	
    print "Content-Type: text/plain"
    print "Refresh: 0; url=%s" % url
    print
    print "Redirecting..."

def url(**kw):
    params=["%s=%s" % (key,urllib.quote_plus(value)) for key,value in kw.items()]
    return "?" + "&".join(params)

def page_file_name(page):
    file_name="%s.txt" % urllib.quote_plus(page)
    return os.path.join(CONTENTS_DIR,file_name)

def page_contents(page):
    file_name=page_file_name(page)
    if not os.path.exists(file_name):
        return None
    return file(file_name).read()

def save_page_contents(page,contents):
    file_name=page_file_name(page)
    file(file_name,'w').write(contents)

def page_header(title):
    print "Content-Type: text/html"
    print
    print "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt'>"
    print "<html xmlns='http://www.w3.org/1999/xhtml'>"
    print "<head>"
    print "<title>%s</title>" % cgi.escape(title)
    print "</head>"
    print "<body>"

def page_footer(page=None):
	print "<div class='footer_links'>"
	if page is not None:
		print "[<a href='%s'>%s</a>]" % (cgi.escape(url(page=page,action='edit')),'edit')
	print "</div>"
	print "</body>"
	print "</html>"

def view_page(page,params):
    contents=page_contents(page)
    if contents is None:
        edit_page(page,params)
        return
    
    page_header(page)
    print "<h1>%s</h1>" % cgi.escape(page)
    print "<div class='contents'>"
    print cgi.escape(contents)
    print "</div>"
    page_footer(page=page)

def edit_page(page,params):
    title='Edit'
    contents=page_contents(page)
    if contents is None:
        contents=''
        title='Add'

    page_header(title)
    print "<h1>%s: %s</h1>" % (title,cgi.escape(page))
    print "<div class='contents'>"
    print "<form method='post'>"
    print "<input type='hidden' name='page' value='%s' />" % cgi.escape(page)
    print "<input type='hidden' name='action' value='save' />"
    print "<textarea name='contents' rows='20' cols='80'>%s</textarea>"  % cgi.escape(contents)
    print "<div><input type='submit' value='Save' /></div>"
    print "</form>"
    print "</div>"
    page_footer(page=page)

def save_page(page,params):
    contents=params.getfirst('contents',None)
    if contents is not None:
        save_page_contents(page,contents)
	#view_page(page,params)
    redirect(url(page=page,action='view'))

views = { 'view': view_page, 'edit': edit_page, 'save': save_page }

def execute(params):
	page=params.getfirst('page','main')
	action=params.getfirst('action','view')
	view=views.get(action,view_page)
	view(page,params)

params=cgi.FieldStorage()
execute(params)

Got any questions?

Get answers in the ShowMeDo Learners Google Group.

Video statistics:

  • Video's rank shown in the most popular listing
  • Video plays: 51 (since July 30th)
  • Plays in last week: 0
  • Published: 76 months ago

Thank-yous, questions and comments

If this video tutorial was helpful please take some time to say thank-you to the authors for their hard work. Feel free to ask questions. Let the author know why their video tutorial was useful - what are you learning about? Did the video tutorial save you time? Would you like to see more?

You may also want to see our ShowMeDo Google Group to speak to our active users and authors.

Your email address will not be published.

Show some quick comments >>








All comments excluding tick-boxed quick-comments

very nice...i hope you find time to finish the project.


Dang, there was a bug, now fixed. This video now plays just fine, sorry about that!

Ian.


Is part 6 broken? I can't view it or download it.


Hi John, nice video. I hadn't realised that the CGIHTTPServer didn't handle 302 redirects and it would have taken me a while to figure out the solution you've presented - grand stuff.

Ian.


Video published, thanks for contributing to ShowMeDo


Showmedo is a peer-produced video-tutorials and screencasts site for free and open-source software (FOSS)- with the exception of some club videos, the large majority are free to watch and download.

how to help » about » faq »

Educating the Open-source Community With Showmedo

Although as important as the software it supports, education and documentation are relatively neglected in the Open-source world. Coders love to code, and explaining how best to use or improve the software tends to be deferred or even sidelined.

At Showmedo we believe the community can play a vital role here and also say thanks for the tools and software that make our lives easier. If you have a piece of software you love or a programming langugage you are enthusiastic about, why not make a screencast showing others how to use it? All the stuff you wish you'd been told, the tips, tricks, insights that would have saved you time and frustration.

Screencasting is easier than you think, and we're happy to help you. You can emailus for advice or just use some of the how-to screencasts on the site. This screencasting learning-pathis a good place to start.

Kudos and Thanks for John

Content

Feedback

Showmedo's development is fairly rapid and bugs will inevitably creep in. If you have any problems please drop us a line using the contact address below. Likewise, any suggestions for improvements to the site are gratefully received.

feedback@showmedo.com