python web服务器 apache,如何让网络服务器(例如Apache)直接调用Python?

(Important) Disclaimer: I know it's probably not a good idea, that Python is not like PHP, and that the "natural" way to do web with Python is more by using a framework like Bottle, Flask, Django (that I already use), etc. But still, just out of curiosity, I'd like to see how the following is possible.

When Apache + PHP are installed, we can access a page like http://www.example.com/index.php. Internally, Apache probably passes the request to PHP which executes code, produces a text output, which is then served by Apache.

Question: how could we do something similar in Python? i.e. by accessing http://www.example.com/index.py, Apache would call the script index.py:

print("

Hello world")

and then Apache would serve this page to the client.

NB:

Calling http://www.example.com/index.py?foo=bar could even give the params to the Python script in sys.argv

I already did it like this: http://www.example.com/index.php:

$out = shell_exec("python index.py");

echo($out);

?>

which then calls the Python script and produces the output. It works, but I'd like to do it without PHP.

Said in another way, is there something like mod_php for Python?

解决方案

I finally managed to do it thanks to the other answer:

Do:

apt-get install libapache2-mod-python

Then create or open the .htaccess file in your website folder, and add

AddHandler mod_python .py

PythonHandler mod_python.publisher

Then create a file test.py:

def index(req):

return("

Hello world")

Now accessing www.example.com/test.py works!

NB:

def index(req) is really required: using another name will make it fail.

I don't know why, but it's not possible to set AddHandler mod_python .py in a .htaccess, I only managed to do it globally for a . Does someone have an idea about how to do it directly in the .htaccess?

if mod_python is already installed but not enabled, you have to do:

a2enmod python

service apache2 restart

but this is done automatically when installing libapache2-mod-python.

This is needed in the Apache VirtualHost's Directory: AllowOverride All, Require all granted, to allow handlers to be added directly in a .htaccess file. Without it, an alternative is to add the directives AddHandler ... directly in the VirtualHost definition.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值