在linux apache 2.4上运行python3脚本

hew*_*ewi 3 python linux apache cgi

我到处寻找并尝试了许多建议的解决方案,但仍然没有所需的结果:从我的 lamp 服务器运行 python 文件。我似乎无法整合拼图的所有部分......使故事变得复杂的是,许多解决方案要么使用旧的 apache 版本(<2.4),这显着改变了配置文件。不再有 httpd.conf!所以这个在apache2中执行a-python-script-in-apache2没有帮助;但 python 版本 > 3 也让事情变得复杂。

眼镜:

  • linux 库班图、阿帕奇 2.4、Python 3.5
  • 阿帕奇正在运行
  • 网站文件位于 root/var/www/html/ 中,我可以 sudo 访问该文件夹。
  • 启用 apache2 cgi 模块:a2enmod cgi
  • python 3.5 路径是 usr/bin/env python3
  • python 脚本是最简单的脚本,已可执行

    #!/usr/bin/env python3
    
    print ("Content-type: text/html\n")
    print ("Hello world!")
    
    Run Code Online (Sandbox Code Playgroud)

让我们把它归结为最简单的情况:我想让apache解释spark.py脚本并吐出html:“Hello world!”

问题:

  • 脚本文件是否正确?
  • 我需要更改哪些配置文件以及需要向这些配置文件中添加哪些内容?

我知道出于安全原因,您不应该在根目录中放置 apache 运行脚本。

Dev*_*him 6

modwsgi 的 python 文档似乎符合您的要求。以下网页有一个非常简单的示例以及 python3-apache2 设置的必要配置。

http://modwsgi.readthedocs.io/en/develop/user-guides/quick-configuration-guide.html

您需要安装 mod_wsgi 才能使配置生效。请注意 apt 和 pip3 中使用的不同“_”下划线和“-”破折号字符。

$ sudo apt install apache2-dev libapache2-mod-wsgi-py3
$ sudo pip3 install mod_wsgi
Run Code Online (Sandbox Code Playgroud)

libapache2-mod-wsgi-py3 和 mod_wsgi 似乎是同一件事。但是,我的测试部署仅在安装 mod_wsgi 后才有效。可能是配置问题。以下是我在Ubuntu 16.04.2上测试过的配置详细信息。

应用程序文件/home/user/wsgi_sample/hello.wsgi:

def application(environ, start_response):
    status = '200 OK'
    output = b'Hello World!'
    response_headers = [('Content-type', 'text/plain'),
                    ('Content-Length', str(len(output)))]
    start_response(status, response_headers)
    return [output]
Run Code Online (Sandbox Code Playgroud)

Apache2配置/etc/apache2/sites-available/000-test.conf

<VirtualHost *:80>
  ServerName testmachine
  <Directory /home/user/wsgi_sample>
    Order allow,deny
    Allow from all
    Require all granted
  </Directory>
  WSGIScriptAlias /hello /home/user/wsgi_sample/hello.wsgi
</VirtualHost>
Run Code Online (Sandbox Code Playgroud)

在 apache2 中启用站点。

sudo a2ensite 000-test.conf
Run Code Online (Sandbox Code Playgroud)

打开浏览器以testmachine/hello.

wsgi也可以使用passenger部署在Apache2上。它需要更长的配置。如果需要 Passenger/python3,请提出一个新问题。