
[英]How to call a function to reload another function (on “orientationchange()” e.g.)?
[英]How to let the webserver (e.g. Apache) call Python directly?
(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 ) 等。但是,出于好奇,我还是想看看以下是如何可能的。
安装 Apache + PHP 后,我们可以访问像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
:
print("<html><body>Hello world</body></html>")
然后 Apache 会将此页面提供给客户端。
注意:
调用http://www.example.com/index.py?foo=bar
甚至可以将参数提供给sys.argv
中的 Python 脚本
我已经这样做了: http://www.example.com/index.php
:
<?php $out = shell_exec("python index.py"); echo($out); ?>
然后调用 Python 脚本并生成 output。 它有效,但我想在没有 PHP 的情况下这样做。
换句话说,Python 有类似mod_php
的东西吗?
python 有一个类似的 mod ,但它没有被广泛使用,而且似乎几年没有更新。
注意:一种常见的处理方式是使用 apache/nginx 作为 web 服务器,使用 uwsgi 作为应用程序服务器,web 服务器重定向到应用程序服务器以获取非静态内容 url。
由于另一个答案,我终于设法做到了:
做:
apt-get install libapache2-mod-python
然后在您的网站文件夹中创建或打开.htaccess
文件,并添加
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
工作!
注意:
def index(req)
确实是必需的:使用另一个名称会使其失败。
我不知道为什么,但是不可能在.htaccess
中设置AddHandler mod_python.py
,我只设法在全局范围内为<VirtualHost>
进行设置。 有人知道如何直接在.htaccess
中进行操作吗?
如果mod_python
已安装但未启用,则必须执行以下操作:
a2enmod python service apache2 restart
但这是在安装libapache2-mod-python
时自动完成的。
这在 Apache VirtualHost
的Directory
中是必需的: AllowOverride All
, Require all granted
allgranted ,以允许将处理程序直接添加到.htaccess
文件中。 如果没有它,另一种方法是直接在VirtualHost
定义中添加指令AddHandler...
还有一个模块 apache 可以服务器 python 除了mod_python
是mod_wsgi
你可能已经尝试过,如果不是,可以像下面这样完成。
如果尚未安装,请先安装
sudo apt-get install libapache2-mod-wsgi -y
创建虚拟主机
<VirtualHost *:8081>
#ServerName www.example.com
#ServerAlias example.com
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html/wsgi
<Directory /var/www/html/wsgi>
<IfVersion < 2.4>
Order allow,deny
Allow from all
</IfVersion>
<IfVersion >= 2.4>
Require all granted
</IfVersion>
</Directory>
WSGIScriptAlias /myapp /var/www/html/wsgi/index.py #path to file
<Directory /var/www/html/wsgi>
<IfVersion < 2.4>
Order allow,deny
Allow from all
</IfVersion>
<IfVersion >= 2.4>
Require all granted
</IfVersion>
</Directory>
</VirtualHost>
创建 index.py
def application(environ, start_response):
status = '200 OK'
output = b'<h2>Hello World!</h2>'
response_headers = [('Content-type', 'text/html'),
('Content-Length', str(len(output)))]
start_response(status, response_headers)
return [output]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.