Pranay Vishwanath
Pranay Vishwanath

Reputation: 21

Python equivalent of a Perl function-based cgi style

I was taught to use Perl cgi (CGI(':standard')) like so:

#!/usr/local/bin/perl
use CGI qw/:standard/;           # load standard CGI routines
print header,                    # create the HTTP header
      start_html('hello world'), # start the HTML
      h1('hello world'),         # level 1 header
      end_html;                  # end the HTML

When moving over to Python, I find I have to do this:

#!/usr/bin/python
print "Content-type:text/html\r\n\r\n"
print '<html>'
print '<head>'
print '<title>Hello Word</title>'
print '</head>'
print '<body>'
print '<h1>Hello Word!</h1>'
print '</body>'
print '</html>'

Is a function-based approach to cgi possible with Python as it is in Perl? What major challenges would you anticipate in trying to create such a package (should one not exist)?

Upvotes: 1

Views: 688

Answers (1)

jfs
jfs

Reputation: 414325

Here's a CGI script written in a "function-based" style using bottle Python web framework:

#!/usr/bin/env python
from bottle import route, run, template

@route('/hello/<name>')
def index(name):
    return template('<b>Hello {{name}}</b>!', name=name)

run(server='cgi') # transform the application into a valid CGI script

To install bottle module, run the usual pip install bottle or just download a single bottle.py file.

To try it, make the script executable:

$ chmod +x cgi-bin/cgi-script

Start [development] CGI server in the current directory:

$ python3 -mhttp.server --cgi --bind localhost

Open the page:

$ python -mwebbrowser http://localhost:8000/cgi-bin/cgi-script/hello/World

Unless you must use CGI, consider other deployment options.

Upvotes: 1

Related Questions