4.3.1. Dynamically Created Static Local Pages from Python¶
The result of processing a PIH file is Python code; this code must be indented. Since a PIH script is a mixture of HTML, in which indentation has no other meaning than readability, and of chunks of Python code, it may be difficult to produce a code that is easily readable and correctly indented 7.3.3.1 Basics. Visualize Execution Live Programming Mode. Write and run Python code using our online compiler (interpreter). You can use Python Shell like IDLE, and take inputs from the user in our Python compiler.
For the rest of this chapter, the example files will come from thewww directory under the main examples directory you unzipped. Iwill refer to example file there as “example www files”.
As the overview indicated, dynamic web applications typicallyinvolve getting input from a web page form, processing the inputin a program on the server, and displaying output to a web page.Introducing all these new ideas at once could be a lot to absorb,so this sectionuses familiar keyboard input into a regular Python programand then, like in the final version,processes the input and produces the final web page output.
Follow this sequence of steps:
- Open the example www file
hello.html
in your browser, to see whatit looks like. - Change your browser view - for instance go back to the previouspage you displayed.
- Open the same hello.html file in Kompozer, if that works for you,or another editor that will show the html source, as discussed inHTML Source Markup.
- If using Kompozer, switch to the Source view (clicking the Source tab).Sometimes you will want to copy HTML text into a Python program.For instance, I selected and copied the entire contents of the
hello.html
source view and pasted it into a multi-line string inthe Python program shown and discussed below. - Careful, note the change from past practice here: Start Pythonfrom inside the www directory. In Windows you may start Idle withthe IdleOnWindows shortcutthat I placed in the www directory, not the original exampledirectory.
- Open the www example program
helloWeb1.py
in an Idleedit window. - Run it.
You should see a familiar web page appear in yourdefault browser (possibly not the one you have been using). Thisis obviously not a very necessary program, since you can selectthis page directly in your browser! Still, one step at a time: itillustrates several useful points. The program is copied below.Read it:
This program encapsulates two basic operations into the last twofunctions that will be used over and over. The first,strToFile
, has nothing new, it just puts specified text in afile with a specified name. The second, browseLocal
, does more.It takes specified text (presumably a web page), puts it in a file,and directly displays the file in your default web browser. It uses theopen
function from the webbrowser
module to start the newpage in your web browser.
The open function here requires the name of afile or URL. Since the page is automatically generated by the programfor one-time immediate viewing, it automatically usesthe same throwaway filename, tempBrowseLocal.html
specified as the default in the keyword parameter. If youreally want another specific, name you could pass it as a parameter.
In this particular program the text that goes in the file is justcopied from the literal string named contents
in the program.
This is no advance over just opening the file in the browserdirectly! Still, it is a start towards the aim of creating webcontent dynamically.
An early example in this tutorial displayed the fixedHelloWorld!'
to the screen. This was later modified inhello_you4.py
to incorporate user input using the string formatmethod of Dictionaries and String Formatting,
Similarly, I can turn the web page contents into a format string,and insert user data. Load and run the www example programhelloWeb2.py
.
The simple changes from helloWeb1.py
are marked at thebeginning of the file and shown below. I modified the web page textto contain ‘Hello, {person}!’ in place of ‘Hello, World!’,making the string into a format string, which I renamed to themore appropriate pageTemplate
. The changed initial portion withthe literal string and and the main program then becomes
Now the line
incorporaties the person’s name into the contents for the web pagebefore saving it to a file and displaying it.
In this case, I stored the literal format string inside the Pythonprogram, but consider a different approach:
Load and run the www example program helloWeb3.py
. It behavesexactly like helloWeb2.py, but is slightly different internally -it does not directly contain the web page template string. Insteadthe web page template string is read from the filehelloTemplate.html
.
Below is the beginning of helloWeb3.py, showing the only newfunctions. The first, fileToStr
, will be a standard functionused in the future. It is the inverse of strToFile
.
The main program obtains the input. In this simple example, theinput is used directly, with little further processing. It isinserted into the web page, using the file helloTemplate.html
as a format string.
Although helloTemplate.html
is not intended to be viewed by theuser (being a template), you should open it in a browser or web editor(Kompozer or ...) to look at it. It is legal to create a web page in a webpage editor with expressions in braces embedded in it! If you lookin the source view in Kompozer or in a web source editor,you will see something similar tothe literal string in helloWeb2.py, except the lines are broken updifferently. (This makes no difference in the formatted result,since in html, all white space is considered the same.)
Back in the Normal mode in Kompozer, or in source mode for any html editor, add anextra line of text right after the line “Hello, {person}!”.Then save the file again (under the samename). Run the program helloWeb3.py
again, and see that youhave been able to change the appearance of the output withoutchanging the Python program itself. That is the aim of using thetemplate html page, allowing the web output formatting to bemanaged mostly independently from the Python program.
A more complicated but much more common situation is where theinput data is processed and transformed into results somehow, andthese results, often along with some of the original input, areembedded in the output web page that is produced.
As a simple example, load and run the www example programadditionWeb.py
, which uses the template fileadditionTemplate.html
.
The aim in the end of this chapter is to have user input come froma form on the web rather than the keyboard on a local machine, butin either case the input is still transformed into results and allembedded in a web page. To make parts easily reusable, I obtainthe input in a distinct place from where the input isprocessed. In keeping with the later situation with web forms,all input is of string type (using keyboard input
for now).
Look at the program. You will see only a few new lines! Because ofthe modular design, most of the program is composed of recentstandard functions reused.
The only new code is at the beginning and is shown here:
The input is obtained (via input
for now), and it is processedinto a web page string, and as a separate step it is displayed in alocal web page.
There are a few things to note:
- All input is strings. Before the numerical calculations, thedigit strings must be converted to integers.
- I do calculate (a very simple!) result and use it in the outputweb page.
- Although it is not in the Python code, an important part of theresult comes from the web page format string inadditionTemplate.html, which includes the needed variable names inbraces, {num1}, {num2}, and {total}. View it in your browseror in a web editor.
When you write your own code, you might modify additionWeb.py
,or you can start from a stripped down skeleton in the example www folder,skeletonForWeb.py
, with comments about whereto insert your special code.
We will examine the bottom part of the following diagram later.The top part outlines the flow of data from string input toweb page in your browser for a regular Python program likewhat we have been describing, with the processing outlined in themiddle line. The parts in the middle will be common to the laterclient/server program, that manges input and output with the bottom line,that we will discuss later.
Again, this last section was somewhat artificial. You are not in the endlikely to find such programs practical as end products. Howeversuch programs are reasonable to write and test and they include almost allthe code you will need for a more practical (but harder to debug)CGI program, coming next....
4.3.1.1. Quotient Web Exercise¶
* Save additionWeb.py
or skeletonForWeb.py
asquotientWeb.py
. Modify it todisplay the results of a division problem in a web page.As in the exercises in Chapter 1, display a full sentencelabeling the initial data and both the integer quotient and the remainder.You cantake your calculations from Quotient String Return Exercise.You shouldonly need to make Python changes to the processInput
andmain
functions. You will also need the HTML for the output pagedisplayed. Make a web page template file calledquotientTemplate.html
and read it into your program.Turn in both quotientWeb.py
and quotientTemplate.html
.
Contents
- Using Python to Control Firefox
Lesson Goals
This lesson uses Python to create and view an HTML file. If you writeprograms that output HTML, you can use any browser to look at yourresults. This is especially convenient if your program is automaticallycreating hyperlinks or graphic entities like charts and diagrams.
Here you will learn how to create HTML files with Python scripts, andhow to use Python to automatically open an HTML file in Firefox.
Files Needed For This Lesson
obo.py
If you do not have these files from the previous lesson, you candownload programming-historian-5, a zip file from the previous lesson.
Creating HTML with Python
At this point, we’ve started to learn how to use Python to downloadonline sources and extract information from them automatically. Rememberthat our ultimate goal is to incorporate programming seamlessly into ourresearch practice. In keeping with this goal, in this lesson and thenext, we will learn how to output data back as HTML. This has a fewadvantages. First, by storing the information on our hard drive as anHTML file we can open it with Firefox and use Zotero to index andannotate it later. Second, there are a wide range of visualizationoptions for HTML which we can draw on later.
If you have not done the W3 Schools HTML tutorial yet, take a fewminutes to do it before continuing. We’re going to be creating an HTMLdocument using Python, so you will have to know what an HTML documentis!
“Hello World” in HTML using Python
Compiler Python
One of the more powerful ideas in computer science is that a file thatseems to contain code from one perspective can be seen as data fromanother. It is possible, in other words, to write programs thatmanipulate other programs. What we’re going to do next is create an HTMLfile that says “Hello World!” using Python. We will do this by storingHTML tags in a multiline Python string and saving the contents to a newfile. This file will be saved with an .html
extension rather than a.txt
extension.
Python Html Test Runner
Typically an HTML file begins with a doctype declaration. You sawthis when you wrote an HTML “Hello World” program in an earlier lesson.To make reading our code easier, we will omit the doctype in thisexample. Recall a multi-line string is created by enclosing the text inthree quotation marks (see below).
Save the above program as write-html.py
and execute it. Use File ->Open in your chosen text editor to open helloworld.html
to verify thatyour program actually created the file. The content should look likethis:
Now go to your Firefox browser and choose File -> New Tab, go to thetab, and choose File -> Open File. Select helloworld.html
. Youshould now be able to see your message in the browser. Take a moment tothink about this: you now have the ability to write a program which canautomatically create a webpage. There is no reason why you could notwrite a program to automatically create a whole website if you wantedto.
Using Python to Control Firefox
We automatically created an HTML file, but then we had to leave oureditor and go to Firefox to open the file in a new tab. Wouldn’t it becool to have our Python program include that final step? Type or copythe code below and save it as write-html-2.py
. When you execute it, itshould create your HTML file and then automatically open it in a new tabin Firefox. Sweet!
Mac Instructions
Mac users will have to specify to the precise location of the .html
file on their computer. To do this, locate the programming-historian
folder you created to do these tutorials, right-click it and select “GetInfo”.
You can then cut and paste the file location listed after “Where:” andmake sure you include a trailing slash (/) to let the computer know youwant something inside the directory (rather than the directory itself).
Html Test Runner Python
If you’re getting a “File not found” error you haven’t changed thefilename path correctly.
Windows Instructions
***
Intallation
Not only have you written a Python program that can write simple HTML,but you’ve now controlled your Firefox browser using Python. In the nextlesson, we turn to outputting the data that we have collected as an HTMLfile.
Suggested Readings
- Lutz, Learning Python
- Re-read and review Chs. 1-17
Run Python
Code Syncing
To follow along with future lessons it is important that you have theright files and programs in your “programming-historian” directory. Atthe end of each lesson in the series you can download the “programming-historian” zipfile to make sure you have the correct code. If you are following alongwith the Mac / Linux version you may have to open the obo.py
file andchange “file:///Users/username/Desktop/programming-historian/” to thepath to the directory on your own computer.
- python-lessons6.zip zip sync