任何 Web 程序如果要正式上线,都需要使用 Web Server, 也就是 Web 服务器。通常 Python 模块和库自带的 Web 运行程序都只是用于开发和测试。而 Python 产品的正式运行环境可以选择 Apache 和Nginx 作为 Web Server。
Apache 和 Nginx 默认只能处理静态文件,如果让它们处理 Python 脚本呢?官方给出的答案就是 WSGI。
WSGi是一种通用API协议,用于在底层Web服务器和Python Web应用之间进行映射。
示例运行环境介绍:
Ubuntu 18.04.1 LTS
Python 2.7.15rc1
Apache 2.4.29
在 Ubuntu 系统安装 apache 的 wsgi 模块。
sudo apt install libapache2-mod-wsgi-py3
重启 Apache
sudo apachectl restart
或者
sudo service apache2 restart
创建一个简单的 WSGI 程序,保存到/www/wsgi/myapp.wsgi:
nano /www/wsgi/myapp.wsgi
myapp.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]
需要注意的是:mod_wsgi 需要入口程序被命名为application, 除非你通过额外的mod_wsgi 配置来指定它使用其他名字。
加载myapp.wsgi, 修改/etc/apache2/sites-enabled/000-default.conf
sudo nano 000-default.conf
添加内容:
WSGIScriptAlias /myapp /www/wsgi/myapp.wsgi
<Directory /www/wsgi>
Require all granted
</Directory>
真实案例:
![](https://img.haomeiwen.com/i4071558/84c9d525af865f62.png)
重启apache ,查看效果:
sudo service apache2 restart
打开浏览器:http://192.168.23.39/myapp
![](https://img.haomeiwen.com/i4071558/6dd41ba054d8c9e5.png)
成功!
网友评论