Linux

关注公众号 jb51net

关闭
首页 > 网站技巧 > 服务器 > Linux > CentOS7部署Flask

CentOS7部署Flask(Apache、mod_wsgi、Python36、venv)

作者:yuan_zw

这篇文章主要介绍了CentOS7部署Flask(Apache、mod_wsgi、Python36、venv),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

一、安装Apache

# yum install -y httpd httpd-devel
# systemctl start httpd.service    # 启动
# systemctl stop httpd.service     # 关闭
# systemctl restart httpd.service   # 重启
# systemctl enable httpd.service    # 开机自启

防火墙开放80端口

# firewall-cmd --zone=public --add-port=80/tcp --permanent
# firewall-cmd --reload

开启Apache,外网已经可以通过ip访问Apache的默认页面了

二、安装Python36、pip3、virtualenv

# yum install -y epel-release
# yum install -y python36
# python36 -V
Python 3.6.6
# yum install -y python36-setuptools
# easy_install-3.6 pip
# pip3 -V
pip 18.1 from /usr/local/lib/python3.6/site-packages/pip-18.1-py3.6.egg/pip (python 3.6)
# pip3 install virtualenv

三、创建项目

创建flask项目(最简单的,一个项目文件夹、一个启动文件)

# mkdir /var/www/flask_test    # 项目文件夹
# vi /var/www/flask_test/app.py  # 启动文件

启动文件例子: 

from flask import Flask, request
 
app = Flask(__name__)
 
@app.route('/')
def hello_world():
  return 'Hello World'
 
@app.route('/hello')
def hello():
  name = request.args.get('name','')
  return 'Hello ' + name + '!'
 
if __name__ == '__main__':
  app.run()

在项目文件夹下创建虚拟环境,安装flask

# cd /var/www/flask_test
# virtualenv py3env      # 创建虚拟环境
# source py3env/bin/activate  # 进入虚拟环境
 
(py3env) # pip install flask  # 安装flask
(py3env) # deactivate     # 退出虚拟环境

四、在虚拟环境中用pip安装mod_wsgi

# yum install -y python36-devel.x86_64   # 一个依赖,不安装的话,下面pip会报错。。
# source py3env/bin/activate        # 进入虚拟环境
(py3env) # pip install mod_wsgi      # 安装mod_wsgi
(py3env) # mod_wsgi-express install-module # 执行该命令,把输出内容复制下来
LoadModule wsgi_module "/usr/lib64/httpd/modules/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so"
WSGIPythonHome "/var/www/flask_test/py3env"
 
(py3env) # deactivate           # 退出虚拟环境

修改Apache的配置

# vi /etc/httpd/conf/httpd.conf

复制上面得到的这行内容,添加到配置文件的最后

复制代码 代码如下:
LoadModule wsgi_module "/usr/lib64/httpd/modules/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so"

五、配置mod_wsgi

# vi /var/www/html/flask_test/app.wsgi

写入以下内容(根据:https://dormousehole.readthedocs.io/en/latest/deploying/mod_wsgi.html

activate_this = '/var/www/flask_test/py3env/bin/activate_this.py'
with open(activate_this) as file_:
  exec(file_.read(), dict(__file__=activate_this))
 
import sys
sys.path.insert(0, '/var/www/flask_test')
from app import app as application

配置Apache

# vi /etc/httpd/conf/httpd.conf

写入以下内容(根据:https://dormousehole.readthedocs.io/en/latest/deploying/mod_wsgi.html#id1

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

OK了,启动Apache,通过这台服务器的ip就能访问网页了

测试一些app.py里面写的两个路径

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文