status 0913.2005: accurate. weblib hasn't changed at all. however: platonic+wsgi+rest would be a much better first lesson
Michal Wallace
Sat, 4 May 2002 23:28:43 -0400 (Eastern Daylight Time)The traditonal introduction to a computer language is the "Hello, World!" program. In python, it's a one-liner:
print "hello, world!"
Easy, huh? If you load up a python interpreter and type that line, it'll print "hello, world!" to the screen.
Web apps don't print their output to a screen, but send it across the internet. For this reason (and others I'll go into later on), we redirect the output to a response object. In the framework that I use, this object is called RES:
print >> RES, "hello, world!"
That's it! Our first web application!
So how can we see it work?
To run this on a cornerhost server, put it in a text file
with the extension ".app". Call this one
hello.app and upload it to your account.
Now load it in your browser as if it were a normal web page. If all goes well, you should see:
hello, world!
If you get an error message, double check that you have the filename correct and that the file contains no leading tabs or spaces - python has very strict rules about whitespace.
Let's personalize our greeting a bit. Python lets us insert a variable (a defined value) into our output by using the percent sign:
name = "Orville" print >> RES, "hello, %s!" % name
If you upload this script and load it in the browser, the result should be:
hello, Orville!
Of course, most of the people using your app won't be named Orville. One way of passing a name into our app would be to include it in the query string:
http:// ... /hello.app?name=Gomer
We can read the query string with the REQ (Request) object:
name = REQ.get("name")
Better yet, we can provide a default:
name = REQ.get("name", "whoever you are")
print >> RES, "hello, %s!" % name
Try running this with and without a "?name=whatever" appended to the url.
But why settle for a default, when we can simply ask users what their names are? This next example uses the REQ.has_key() method to tell if a name has been passed in. If so, it says hello. If not, it shows an HTML form:
if REQ.has_key("name"):
print >> RES, "hello, %s!" % REQ.get("name")
else:
# notice the single quotes, to prevent conflict with HTML:
print >> RES, '<form action="hello.app" method="GET">'
print >> RES, 'What is your name?'
print >> RES, '<input type="text" name="name" value="">'
print >> RES, '<input type="submit">'
print >> RES, '</form>'
There's nothing wrong with that code, but it sure isn't pretty. If you wanted to make the form look nicer, you'd have to add a whole lot more of those "print >> RES" lines, and that would get old real fast. Worse, it's hard to read and hard to maintain.
In the next lesson, we'll look at a way of solving these problems by separating the logic of an app from its presentation.
----- (c)2002 sabren enterprises inc feel free to forward this to a friend!