[Tutor] Re: Translating to Python [perl --> python]

Derrick 'dman' Hudson dman@dman.ddts.net
Mon, 1 Jul 2002 17:58:52 -0500


--X1bOJ3K7DJ5YkBrT
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Mon, Jul 01, 2002 at 10:10:02PM +0000, Kyle Babich wrote:
| Thank you, that's just what I was looking for.  I like it, err...
| one problem, my server doesn't.  505

I found 3 problems with Danny's code (must not have been tested :-)),
and 2 problems with Kyle's code.

| Results of python -c index.py
|=20
| Traceback (innermost last):
|   File "<string>", line 1, in ?
| NameError: index

First, "index.py" is a valid python statement only when
    1)  A variable named 'index' exists
and
    2)  that object has a member named 'py'

What you meant to write was
    $ python index.py

Still, that wouldn't help you to debug a CGI script unless you also
first created the rest of the environment that apache would create for
the script.
=20
| Exactly what index.py says:

| form =3D cgi.FieldStorage()
| 	c =3D cgi['c'].value
  ^
| 	content =3D 'c'
  ^
| 		if c =3D=3D 'abc':
  ^     ^
|     		content =3D "abc123"
  ^^^^^ ^

That indentation is not valid syntax in python.  That's probbly what
is causing your 505 error.  A good idea is to look at the web server's
error log since it will (at least for apache) contain the error
message.

Be very consistent in your indentataion or else python will beat you
with a cluestick :-).

Rule #1 (this applies to any language, python just enforces it) :
    Indent blocks of statements at the same indentation level.
    Indent nested blocks by 1 additional indentation level.

If you don't indent consistently, then the code is nearly impossible
to read.  While C, Perl, etc, will let you get away with it (assuming
the code is correct in the first place and you haven't merely fooled
yourself), Python won't let you get away with it -- it will be even
more fooled than you are.

Rule #2 (this also applies to everything but Makefiles, IMO) :
    Never use tabs.
    Always keep your tabstop set at 8.

Any decent editor can be configured to insert/remove the proper number of
spaces when you press the buttons on your keyboard labeled "tab" and
"backspace".  Thus the tab character (ASCII 0x09) never needs to be
stored in the file itself.  Also note that whenever python sees a tab
character, it treats it as 8 spaces.  If you muck with the size your
editor displays a tab as, you'll get very confusing syntax errors from
python because it doesn't see the same thing your eyes see.

For vim, I recommend these settings :


" make tabs visible
set lcs=3Dtab:>-
set list

augroup Python
    au!
    au FileType python set sts=3D4 sw=3D4 et tw=3D80 fo=3Dcroq2 hls

    " override C preprocessor indenting
    au FileType python inoremap # X<C-H>#

    au FileType python set foldmethod=3Dindent
    " do I want everything collapsed when I open the file?
    au FileType python set nofoldenable

augroup END


Now to correct the bugs in Danny's code :


#!/usr/bin/env python

import cgi
import cgitb
cgitb.enable()


# Bug #1:  print the headers first.  Otherwise it is possible to print
# that "error: content failed" message before the headers are printed.
print "Content-type: text/html\n\n"


form =3D cgi.FieldStorage()
# Bug #3:  handle the situation where the script was not passed a
#          parameter 'c'.  Unlike perl/sh, in python accessing undefined
#          variables is an error, not the empty string.
try :
    # Bug #2: s/cgi/form/  Danny meant to index the form object, not
    #         the cgi module.
    c =3D form['c'].value
except KeyError :
    # What to do if the parameter doesn't exist.  I suppose
    # considering it to be the empty string is what is desired in this
    # case.
    c =3D ""
content =3D 'c'
if c =3D=3D 'abc':
    content =3D "abc123"
elif c =3D=3D 'def':
    content =3D "def456"
else:
    print "error: content failed\n"

file =3D open("text.txt")
text =3D file.read()
file.close()

print """

%(content)s


<br>&nbsp;<br>&nbsp;<br>&nbsp;

%(text)s

""" % vars()


HTH,
-D

--=20

Like a gold ring in a pig's snout
is a beautiful woman who shows no discretion.
        Proverbs 11:22
=20
http://dman.ddts.net/~dman/


--X1bOJ3K7DJ5YkBrT
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAj0g3qsACgkQO8l8XBKTpRTU9gCgxQimIQNcvqv9L/rXQZU4YiXg
J0AAoL69T0cJ59ksv3DyV+c6IrWtzPPq
=sRkc
-----END PGP SIGNATURE-----

--X1bOJ3K7DJ5YkBrT--