首页 > 编程 > Python > 正文

Python WEB应用部署的实现方法

2020-02-16 00:27:23
字体:
来源:转载
供稿:网友

本文介绍了Python WEB应用部署的实现方法,分享给大家,具体如下:

使用Apache模块mod_wsgi运行Python WSGI应用

Flask应用是基于WSGI规范的,所以它可以运行在任何一个支持WSGI协议的Web应用服务器中,最常用的就是 Apache+mod_wsgi 的方式

Apache主配置文件是/etc/httpd/conf/httpd.conf

其他配置文件存储在/etc/httpd/conf.d/目录

安装mod_wsgi

安装httpd-devel

$ yum install httpd-devel$ rpm -ql httpd-devel

安装mod__wsgi

$ yum install mod_wsgi

安装完成之后, mod_wsgi.so 会在Apache的modules目录中

httpd.conf 文件中添加以下内容

LoadModule wsgi_module modules/mod_wsgi.so

重启Apache来启用配置

$ sudo service httpd restart 

测试mod_wsgi

在Apache的DocumentRoot根目录下创建一个文件 test.wsgi

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

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

然后,再打开Apache的配置文件httpd.conf,在其最后加上URL路径映射:

WSGIScriptAlias /test /var/www/html/test.wsgi

测试 curl http://localhost/test

使用Python虚拟环境

virtualenv 是一个创建隔绝的Python环境的工具。virtualenv创建一个包含所有必要的可执行文件以及 pip 库的文件夹,用来使用Python工程所需的包。

配置app.wsgi

activate_this = '/var/www/html/py3env/bin/activate_this.py'execfile(activate_this, dict(__file__=activate_this))from flask import Flaskapplication = Flask(__name__)import syssys.path.insert(0, '/var/www/flask_test')from app import app as application

我们的虚拟环境在目录 /var/www/html 下,你可以在其 /bin 子目录中找到启用脚本 activate_this.py 。在WSGI应用的一开始执行它即可。

apache配置文件

<VirtualHost *:80> ServerName example.com WSGIScriptAlias / /var/www/html/app.wsgi <Directory /var/www/html>  Require all granted </Directory></VirtualHost>!

参考

https://www.jb51.net/article/153875.htm

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表