使用mod_wsgi
在https://pypi.org/project/mod-wsgi/中,介绍了mod_wsgi和Apache的连接,具体是Connecting into Apache installation,其中针对pip install xxx的方式:
To use the Apache mod_wsgi module from where pip install placed it, run the command mod_wsgi-express module-config. This will output something like:
LoadModule wsgi_module /usr/local/lib/python2.7/site-packages/mod_wsgi/server/mod_wsgi-py27.so WSGIPythonHome /usr/local/lib
These are the directives needed to configure Apache to load the mod_wsgi module and tell mod_wsgi where the Python installation directory or virtual environment was located.
This would be placed in the Apache httpd.conf file, or if using a Linux distribution which separates out module configuration into a mods-available directory, in the wsgi.load file within the mods-available directory. In the latter case where a mods-available directory is used, the module would then be enabled by running a2enmod wsgi as root. If necessary Apache can then be restarted to verify the module is loading correctly. You can then configure Apache as necessary for your specific WSGI application.
我在运行之后,获得如下指令:
LoadFile "d:/anaconda3/python38.dll" LoadModule wsgi_module "d:/anaconda3/lib/site-packages/mod_wsgi/server/mod_wsgi.cp38-win_amd64.pyd" WSGIPythonHome "d:/anaconda3"
仅仅如此,重启apache服务时会失败。查看Apache的错误日志,看到PYTHONPATH和PYTHONHOME两个环境变量是未设置的。
我记得PYTHONPATH用于寻找python脚本文件,PYTHONHOME用于寻找解释器(可能是供某些程序使用);暂时仅创建PYTHONHOME这个环境变量,值为D:\Anaconda3,成功启动Apache。
对于来自https://modwsgi.readthedocs.io/en/master/user-guides/configuration-guidelines.html的这个标准示例文件:
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]
我将其放在D:/Apache24/cgi-bin/sales_wsgi.py中,大家都是用.wsgi作为后缀名称,但是这明显是一个py文件,所以我将其改为xxx.py(后记:事实上没有必要,我不是要造轮子,所以遵循惯例即可,2021-09-27)。
在conf文件,又添加了这个指令:
WSGIScriptAlias /sales D:/Apache24/cgi-bin/sales_wsgi.py
现在在浏览器访问192.168.22.198/sales 成功了。
示例代码仅传输"Hello World"是可以顺利执行二进制编码的,如果加上中文,再指定通常使用的utf-8编码方式,那么则需要在Apache中再添加:
AddDefaultCharset utf-8
这样服务才会用utf-8进行解码。
现在的任务是,通过 sales_wsgi.py 引用其他位置的py脚本。