在Linux Apache 2.4上运行Python3脚本

3
我已经寻找了很多地方并尝试了许多建议的解决方案,仍然没有达到所需的结果:从我的lamp服务器运行一个python文件。我似乎无法整合所有的部分... 让情况复杂化的是,许多解决方案要么使用旧的apache版本(<2.4),这显着改变了配置文件。没有httpd.conf文件了!因此,这个执行python脚本在apache2中不能帮助; 但是,python版本>3也使问题更加复杂。 规格:
  • linux Kubuntu, apache 2.4, python 3.5
  • apache is running
  • website files are in root/var/www/html/, I have sudo access to this folder.
  • apache2 cgi module enabled: a2enmod cgi
  • the python 3.5 path is usr/bin/env python3
  • the python script, simplest of scripts, has been made executable

    #!/usr/bin/env python3
    
    print ("Content-type: text/html\n")
    print ("Hello world!")
    
让我们简化一下问题:我想让apache解释spark.py脚本并输出HTML:“Hello world!”
问题:
- 这个脚本文件是正确的吗? - 我需要更改哪些配置文件以及需要在这些配置文件中添加什么内容?
出于安全考虑,我知道你不应该让apache在根目录下运行脚本。

看看 mod_wsgi,它比普通的 CGI 好多了。主要的 Ubuntu 存档中有一个 libapache2-mod-wsgi-py3 包,我相信 Kubuntu 也有一个可用的包。 - MattDMo
我正在研究wsgi模块,但似乎更难实现。也许你有一个非常基本简单的例子吗? - hewi
我已经在谷歌上搜索了很久,相信我,这就是为什么我回复有所延迟 :) 别忘了 YouTube,也非常有帮助,但是没有一个例子真正地从头到尾解释清楚,WSGI脚本位于哪里,Apache服务器设置是什么,你的实际应用程序位于哪里?谷歌“基本Python WSGI示例”会显示155,000个结果,我刚刚检查了一下,我实际上访问了大约60个链接,但仍然无法工作 :( 无论如何,感谢您的帮助,我将发布一个新问题... - hewi
2个回答

6
Python文档中的modwsgi似乎符合您的要求。下面的网页有一个非常简单的例子以及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

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]

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>

启用 Apache2 中的站点。

sudo a2ensite 000-test.conf

打开您的浏览器,输入“testmachine/hello”。
使用Passenger也可以在Apache2上部署WSGI。但是,它需要稍微更长的配置时间。如果需要使用passenger/python3,请提出一个新问题。

欢迎来到Stack Overflow。如果目标网站无法访问或永久关闭,请引用重要链接的最相关部分。 - Fabian Horlacher

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接