如何让网络服务器(例如Apache)直接调用Python? [英] How to let the webserver (e.g. Apache) call Python directly?
问题描述
(重要)免责声明:我知道这可能不是一个好主意,Python不像PHP,并且使用Python进行网络连接的自然"方式更多是通过使用Bottle,Flask, Django(我已经使用过的)等.但是,出于好奇,我还是想看看如何实现以下目标.
安装Apache + PHP后,我们可以访问http://www.example.com/index.php
之类的页面.在内部,Apache可能会将请求传递给PHP,该PHP执行代码,生成文本输出,然后由Apache提供服务.
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.
问题:我们如何在Python中做类似的事情?,即通过访问http://www.example.com/index.py
,Apache将调用脚本index.py
:
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("<html><body>Hello world</body></html>")
然后Apache将把该页面提供给客户端.
and then Apache would serve this page to the client.
NB:
-
调用
http://www.example.com/index.py?foo=bar
甚至可以为sys.argv
我已经这样做了:http://www.example.com/index.php
:
<?php
$out = shell_exec("python index.py");
echo($out);
?>
然后调用Python脚本并产生输出.它可以工作,但是我想不用PHP.
which then calls the Python script and produces the output. It works, but I'd like to do it without PHP.
用另一种方式表示,是否有类似 mod_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
然后在您的网站文件夹中创建或打开.htaccess
文件,然后添加
Then create or open the .htaccess
file in your website folder, and add
AddHandler mod_python .py
PythonHandler mod_python.publisher
然后创建一个文件test.py
:
def index(req):
return("<html><body>Hello world</body></html>")
现在可以访问www.example.com/test.py
了!
NB:
NB:
-
def index(req)
确实是必需的:使用其他名称将使其失败.
def index(req)
is really required: using another name will make it fail.
我不知道为什么,但是不可能在.htaccess
中设置AddHandler mod_python .py
,我只为<VirtualHost>
全局进行了设置.有人对如何直接在.htaccess
上进行操作有想法吗?
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 <VirtualHost>
. Does someone have an idea about how to do it directly in the .htaccess
?
如果已经安装但未启用mod_python
,则必须执行以下操作:
if mod_python
is already installed but not enabled, you have to do:
a2enmod python
service apache2 restart
,但这是在安装libapache2-mod-python
时自动完成的.
but this is done automatically when installing libapache2-mod-python
.
这在Apache VirtualHost
的Directory
:AllowOverride All
,Require all granted
中是必需的,以允许将处理程序直接添加到.htaccess
文件中.没有它,另一种选择是直接在VirtualHost
定义中添加指令AddHandler ...
.
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.
这篇关于如何让网络服务器(例如Apache)直接调用Python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!