怎样配置mod_wsgi让Apache支持Python

2018年6月5日 | 分类: 【技术】

参考:https://www.jianshu.com/p/b40a4a12fff1
参考:http://www.cnblogs.com/Erick-L/p/7063173.html
参考:http://blog.sina.com.cn/s/blog_883a98da0101k8t0.html
参考:http://www.cnblogs.com/yestreenstars/p/5949037.html

【介绍】

建立Python与Apache的链接:为Apache安装Python解释器。

【安装】

官网:http://www.modwsgi.org/
下载:https://github.com/GrahamDumpleton/mod_wsgi/releases
文档:https://github.com/GrahamDumpleton/mod_wsgi/

指定Apache和Python环境,加上”–with-apxs”和”–with-python”选项:

wget https://github.com/GrahamDumpleton/mod_wsgi/archive/4.6.4.tar.gz && tar vxzf 4.6.4.tar.gz && cd mod_wsgi-4.6.4
./configure --with-apxs=/usr/local/apache2/bin/apxs --with-python=/usr/local/bin/python3.6
make && make install

输出:

...
Libraries have been installed in:
   /usr/local/apache2/modules

If you ever happen to want to link against installed libraries
...
chmod 755 /usr/local/apache2/modules/mod_wsgi.so

【配置】

在Apache配置文件中载入mod_wsgi:

打开Apache的配置文件httpd.conf,加上载入mod_wsgi的配置,以及文件格式:

LoadModule wsgi_module modules/mod_wsgi.so
<IfModule mime_module>
	TypesConfig conf/mime.types
...
	AddType application/x-httpd-wsgi .wsgi
...
	AddHandler wsgi-script .wsgi
</IfModule>

重启Apache来启用配置。

【测试】

参考:https://stackoverflow.com/questions/34838443/typeerror-sequence-of-byte-string-values-expected-value-of-type-str-found
参考:https://stackoverflow.com/questions/8349582/500-error-with-wsgi-in-django

在Apache的DocumentRoot根目录下创建一个文件”test.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]

函数application即为WSGI应用对象,它返回的值就是该应用收到请求后的响应。

编辑 httpd-vhosts.conf :

<virtualhost *:80>
	ServerName codeabc.org
	ServerAlias www.codeabc.org
	DocumentRoot /usr/local/apache2/htdocs/codeabc.org/portal/
	WSGIScriptAlias /test /usr/local/apache2/htdocs/codeabc.org/portal/test.wsgi
	ErrorLog /usr/local/apache2/htdocs/logs/codeabc.org_error.log
	CustomLog /usr/local/apache2/htdocs/logs/codeabc.org_access.log combined
	<Directory /usr/local/apache2/htdocs/codeabc.org/portal>
		Options Indexes FollowSymLinks
		AllowOverride All
		Require all granted
	</Directory>
</VirtualHost>

WSGIScriptAlias那一行是URL路径映射。

重启Apache来启用配置。

打开浏览器,访问:http://codeabc.org/test

如果看到”Hello World!”,就说明mod_wsgi已经安装成功。