Apache下运行Python WEB Applications的三种方式

本文介绍了在Apache服务器上运行Python Web应用程序的三种方式:1) 使用CGI,通过修改配置文件和创建Python脚本来实现;2) 利用Mod_Python模块,配置Apache并设置PythonHandler来提高性能;3) 使用Mod_wsgi,一个高性能的Python Web服务器网关接口。每种方法都涉及到Apache配置和Python脚本的编写。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1, 传统CGI:

vim /var/www/cgi-bin/hello.py

#!/usr/bin/python
# -*- coding: utf-8 -*-

print "Content-type: text/html\n"
print "Hello World"

chmod a+x hello.py

vim /etc/httpd/conf/httpd.conf
ScriptAlias /cgi-bin/ /var/www/cgi-bin/

2, Mod_Python (http://www.modpython.org/)

wget http://archive.apache.org/dist/httpd/modpython/mod_python-3.3.1.tgz

./configure --with-apxs=/data/apache2221/bin/apxs --with-python=/usr/bin/python
make
make install

vim /etc/httpd/conf.d/python.conf
LoadModule python_module modules/mod_python.so

<Directory /var/www/mod-python>
    AddHandler mod_python .py
    # mod_python.publisher
    PythonHandler mod_python.publisher

    PythonDebug On
</Directory>

vim /var/www/mod-python/mod_python_publisher.py

#!/usr/bin/python
# -*- coding: utf-8 -*-

from mod_python import apache

def index(req):
    req.log_error('handler')
    req.content_type = 'text/html'
    req.send_http_header()
    req.write('<html><head><title>Testing mod_python</title></head><body>')
    req.write('Hello World! - mod_python.publisher')
    req.write('</body></html>')

<Directory /var/www/mod-python>
    AddHandler mod_python .py
    # custom handler
    PythonHandler mod_python_handler

    PythonDebug On
</Directory>

vim /var/www/mod-python/mod_python_handler.py 

#!/usr/bin/python
# -*- coding: utf-8 -*-

from mod_python import apache

def handler(req):
    req.log_error('handler')
    req.content_type = 'text/html'
    req.send_http_header()
    req.write('<html><head><title>Testing mod_python</title></head><body>')
    req.write('Hello World! - custom handler')
    req.write('</body></html>')
    return apache.OK

3, Mod_wsgi (http://code.google.com/p/modwsgi/)
wget http://modwsgi.googlecode.com/files/mod_wsgi-3.3.tar.gz

./configure --with-apxs=/data/apache2221/bin/apxs --with-python=/usr/bin/python
make
make install

vim /data/apache2221/conf/httpd.conf
LoadModule wsgi_module modules/mod_wsgi.so

WSGIScriptAlias /wsgi/ /var/www/wsgi/
<Directory "/var/www/wsgi">
    Order allow,deny
    Allow from all
</Directory>

vim /var/www/wsgi/hello.py

#!/usr/bin/python
# -*- coding: utf-8 -*-

def application(environ, start_response):
    status = '200 OK'
    content_type = 'text/html'

    output = ['Hello World']

    response_headers = [('Content-type', content_type)]
    start_response(status, response_headers)
    return output
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值