使用Apache2+WSGI发布Flask程序

在发布网站之前,注意以下事项

  • 确定是否正确安装Apache2
    sudo apt-get install apache2
  • 确定Flask程序使用Python2还是Python3环境,根据这个安装对应的libapache2-mod-wsgi
    sudo apt-get install libapache2-mod-wsgi #python2
    sudo apt-get install libapache2-mod-wsgi-py3
  • 程序目录结构
    (env) 01:09:12 harvey@harveyhub ☆ /var/www/ExampleFlask
    ♪tree -L 2 .
    .
    ├── env
    │   ├── bin
    │   └── lib
    ├── ExampleFlask
    │   ├── __init__.py
    │   └── my_flask_app.py
    └── my_flask_app.wsgi
    
  • 虚环境的使用

    虚环境下,在/var/www/``目录下无法使用sudo安装和卸载flask所需要的依赖包。解决办法是先改变目录权限,然后搭建虚环境,使用虚环境中的pip安装依赖包

my_flask_app.wsgi

#python3加载虚环境的方式
activate_this = '/var/www/ExampleFlask/env/bin/activate_this.py'
# 使用虚环境,需要在import之前加载虚环境
with open(activate_this) as file_:
    exec(file_.read(), dict(__file__=activate_this))

#python2加载虚环境的方式
#execfile(activate_this, dict(__file__=activate_this)) # 执行虚拟环境启动脚本
#指定python3版本
#! /usr/bin/python3
import logging
import sys
logging.basicConfig(stream=sys.stderr)
#不加上下面这一行,就无法加载my_flask_app模块
sys.path.insert(0, '/var/www/ExampleFlask/ExampleFlask')
from my_flask_app import app as application
application.secret_key = 'anything you wish'

/etc/apache2/sites-available/ExampleFlask.conf

<VirtualHost *:80>
     # Add machine's IP address (use ifconfig command)
     ServerName www.harveyhub.top
     ServerAlias harveyhub.top
     # Give an alias to to start your website url with
     WSGIScriptAlias /testFlask /var/www/ExampleFlask/my_flask_app.wsgi
     <Directory /var/www/ExampleFlask/ExampleFlask/>
                # set permissions as per apache2.conf file
            Options FollowSymLinks
            AllowOverride None
            Require all granted
     </Directory>
     ErrorLog ${APACHE_LOG_DIR}/error.log
     LogLevel warn
     CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

启用apache2配置文件

sudo a2ensite ExampleFlask.conf
sudo service apache2 restart

Leave a Reply

Your email address will not be published. Required fields are marked *