您的位置:首页 > 编程语言 > Python开发

To say "Hello world" in Python CGI Web Programming in 5 minutes

2012-10-09 16:38 661 查看


by Forrest Sheng Bao http://fsbao.net

I have lotta Python programs for bioinformatics research. I wanted to put them onto the web. I only developed Web apps in PHP before. And it seemed to be a big pain for porting a Python program to the web. But, I figured out in 5 minutes.

First, you need an Apache server on your Linux/Mac OS/Windows box. If you are gonna use data base, you need a database server. There are tons of blogs addressing these issues. So I won't be gossipy here. Suppose everything we mention below happens on your server-even
web browsing.

Second, configure cgi in Apache. There are many ways to run a Python program on a web/http interface. I think CGI is the easiest. Assume you are on your own server and using all default settings. On Ubuntu Linux 9.04, the default configuration file for your
default website is
/etc/apache2/sites-available/default
Open it, find the part for cgi directory, and make it like this
ScriptAlias /cgi-bin/ /var/www/cgi-bin/
<Directory "/var/www/cgi-bin">
AllowOverride None
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
Order allow,deny
Allow from all
AddHandler cgi-script .py                       # tell Apache to handle every file with .py suffix as a cgi program
AddHandler default-handler .html .htm  # tell Apache to handle HTML files in regular way
</Directory>


The line
ScriptAlias /cgi-bin/ /var/www/cgi-bin/


specifies the path of cgi codes and the actual directory of your program. So when you type http://127.0.0.1/cgi-bin, the Apache will
look into the directory
/var/www/cgi-bin/
of your localhost.

Now restart your apache. On Ubuntu Linux, by default installation and configuration, it is
sudo /etc/init.d/apache2 restart


Third, write up a Hello, World! program. Save it as hello.py and give it execution privilege for anyone.
#!/usr/bin/env python
print "Content-Type: text/html"
print
print """\
<html>
<head><title>First Python HTTP Programming </title></head>
<body>
<h2>Hello World!</h2>
</body>
</html>
"""


Now open http://127.0.0.1/cgi-bin/hello.py in your web browser and you shall see a hello world in it.

If you have any error, e.g., 500 error, please check your Apache log file. It shall tell you something. You can find errors like what you have seen from a standard Python interpreter.

Reference: http://webpython.codepoint.net/cgi_tutorial
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐