3 ms·
Let's look at something trivially more complex than a Hello World: a form handler. The form is just HTML, asking for a name: <html> <body> <form ac
by Jach 15y ago
Let's look at something trivially more complex than a Hello World: a form handler. The form is just HTML, asking for a name:
<html>
<body>
<form action="handlerhere" method="post">
<label>Name: <input type="text" name="name" /></label>
<input type="submit" name="submit" value="Submit" />
<input type="hidden" name="submitted" value="TRUE" />
</form>
</body>
</html>
The handler is a separate file. This whole example is from back around my first year of programming, when (among other silly things) I thought indentation was stupid. (Which was one reason I didn't like Python to begin with even though I love it now.) The PHP handler:
<html>
<body>
<?php
if (isset($_POST['submitted'])) {
$name = htmlentities(stripslashes($_POST['name']));
echo "<p>The submitted name was \"$name\"</p>";
}
?>
</body>
</html>
And the Python version (notice the silly one space indent (I use two now!) and the silly semicolons):
#!/usr/bin/python
import cgi;
def main():
form = cgi.FieldStorage(); # instantiate only once!
name = form.getfirst('name', 'empty');
# Avoid script injection escaping the user input
name = cgi.escape(name);
print "Content-Type: text/html\n";
print """\
<html>
<body>
<p>The submitted name was "%s"</p>
</body>
</html>""" % name
if __name__ == "__main__":
main();
Oh, and with the Python version I had to add this file to the directory it was in which I didn't totally understand at the time:
Options +ExecCGI
AddHandler cgi-script .py
Options +Indexes
Admittedly not that hard. I had an .htaccess file already for fun 404 handlers. I vaguely remember being confused for a while because the .py script didn't have the right permissions on it so the server's apache just refused to execute.
The complexity isn't that much different, it's just that Python provided no compelling reason for me to switch to it. (And, frankly, even with Flask still doesn't for simple single-file web-page scripts. Applications, on the other hand...)