views:

50

answers:

3

Hey all,

I've been teaching myself python and cgi scripting, and I know that your basic script looks like

#!/usr/local/bin/python
import cgi
print "Content-type: text/html"
print 
print "<HTML>"
print  "<BODY>"
print "HELLO WORLD!"
print "</BODY>"
print "</HTML>"

My question is, if I have a big HTML file I want to display in python (it had lines and lines of code and sone JS in it) do I have to manually add 'print' in front of each line and turn "s into \" , etc? Or is there a method or script that could convert it for me?

Thanks!

+2  A: 

If that big html file is called (for example) 'foo.html' and lives in the current directory for your CGI script, then all you need as your script's body is:

print "Content-type: text/html"
print
with open('foo.html') as f:
  print f.read()

If you're stuck with Python 2.5, add from __future__ import with_statement as the start of your module's body. If you're stuck with an even older Python, change the last two lines into

print open('foo.html').read()

Note that you don't need to import cgi when you're using none of the functionality of the cgi module, which is the case both in your example and in this answer.

Alex Martelli
Thanks Alex, much appreciated!
Parker
So would foo.html have to be in cgi-bin if that's where the script was?
Parker
@Parker: For the example, yes. But you can specify the path when opening the file if it's somewhere else.
Ignacio Vazquez-Abrams
@Parker, yes, exactly in the same directory (for the code I've posted to work; otherwise you have to know, and give, the complete path to the file, not just the name).
Alex Martelli
+1  A: 

Python supports multiline strings, so you can print out your text in one big blurb.

print '''<html>
<head><title>My first Python CGI app</title></head>
<body>
<p>Hello, 'world'!</p>
</body>
</html>'''

They support all string operations, including methods (.upper(), .translate(), etc.) and formatting (%), as well as raw mode (r prefix) and the u unicode prefix.

Ignacio Vazquez-Abrams
So I can copy and paste any HTML like that? Don't I have to add / before each " ?
Parker
With multiline strings, only the same triple-quote sequence that opened the string can close it.
Ignacio Vazquez-Abrams
Ignacio, you've saved me hours of unnecessary "print" tags and quotes. Thanks!
Parker
A: 

When I was first experimenting with decorators, I wrote this little CGI decorator to handle the HTML head and body tag boilerplate stuff. So that you can just write:

@CGImethod(title="Hello with Decorator")
def say_hello():
    print '<h1>Hello from CGI-Land</h1>'

which when called returns:

Content-Type: text/html

<HTML>
<HEAD><TITLE>Hello with Decorator</TITLE></HEAD>
<BODY>
<h1>Hello from CGI-Land</h1>

</BODY></HTML>

Then say_hello could be called from your HTTP server's do_GET or do_POST methods.

Paul McGuire