Since Python is not specifically designed for web development, a number of technologies created by Python users exist that aim to provide a web development environment. While the exact approach to the situation varies among each framework, a few of these frameworks really stand out in the crowd. One such framework is Karrigell. Read on to learn more.
In askName.py, one thing seems to be very noticeable: there are a lot of print statements in the code. Wouldn't it be nice if we could eliminate them? Fortunately, Karrigell provides a method that does just that. It's called HTML Inside Python, and it allows all those nasty print statements to be eliminated. It isn't very hard to convert askName.py to an HTML in Python file, either. We simply need to remove the print statements and change the extension. Delete askName.py's print statements and rename it to askName.hip:
if QUERY.has_key ( "name" ): "Your name is", _name + "." else: "What is your name?<br />" "<form method='POST'>" "<input type='text' name='name' /><br />" "<input type='submit' value='Proceed' />" "</form>"
Truthfully, that's all there is to HTML Inside Python. Karrigell will examine your file and add print statements when necessary. HTML Inside Python is a wonderful demonstration of the simplicity of Karrigell.
Python Inside HTML
Since Karrigell features HTML Inside Python, it's only logical to contain Python Inside HTML. The underlying idea – and even the look of the finished code – is common, and it's been featured in other frameworks. Special tags are wrapped around Python code, and the overall result is sent to the user's browser. Let's create a simple example, random.pih:
<% import random %> Random number: <b><% print random.random() %></b>
As you can see, the concept behind Python Inside HTML is pretty simple. Also, note that the block of code that prints the random number could be shortened even more:
<%= random.random() %>
However, what about more complex operations, such as handling form data? Form data can be accessed just like it can be in Python scripts. Here is a recreation of the askName.py script, called askName.pih:
<% if QUERY.has_key ( "name" ): %> Your name is <%= _name %>. <% end %> <% else: %> What is your name?<br /> <form method='POST'> <input type='text' name='name' /><br /> <input type='submit' value='Proceed' /> </form> <% end %>
Notice the use of <% end %>. This simply marks the end of a block of indentation, such as the indentation called for by our conditional statement. An alternative is the indent tag, which uses the indentation present in the code:
<indent> <% if QUERY.has_key ( "name" ): %> Your name is <%= _name %>. <% else: %> What is your name?<br /> <form method='POST'> <input type='text' name='name' /><br /> <input type='submit' value='Proceed' /> </form> </indent>