项目部署:flask+mod_wsgi+apache

  • 安装apache
    root用户下安装的,安装完后,在以下目录中:
    • /usr/sbin/apache2 执行文件
    • /usr/lib/apache2 库文件
    • /etc/apache2 配置文件
    • /usr/share/man/man8/apache2.8.gz
apt-get install apache2
  • 安装mod-wsgi
    root用户下安装的
apt-get install libapache2-mod-wsgi #python2
apt-get install libapache2-mod-wsgi-py3 #python3

安装完后所在目录:
/usr/lib/apache2/modules/
在这里插入图片描述

  • 安装flask
    非root用户下安装的。
pip3 install flask --user
  • 创建flask程序
#test_hello.py
import os
from urllib.request import urlretrieve
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask, request, jsonify
import requests
import json
import time

def generate_log(log_dir):
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
    now_time = time.strftime('%Y-%m-%d-%H-%M-%S')
    formatter_base = '%(asctime)s: %(levelname)s %(message)s'
    logging.basicConfig(level=logging.DEBUG)
    formatter = logging.Formatter(formatter_base)
    Rthandler = RotatingFileHandler(filename='%s' % os.path.join(log_dir, now_time + '.log'), \
    maxBytes=50 * 1024 * 1024, backupCount=1)
    Rthandler.setLevel(logging.DEBUG)
    Rthandler.setFormatter(formatter)
    logging.getLogger('').addHandler(Rthandler)


app = Flask(__name__)
generate_log('/mnt/disk2/xxx/work/test/log/')
@app.route('/Test', methods=['GET', 'POST'])


def test():
    try:
        strs = request.values.get('strs')
    except Exception as e:
        return jsonify({'result': 'ERR', 'message' : 'hello %s faild: %s' % (strs, e)})
    return jsonify({'result': 'OK', 'message' : 'hello %s ' % strs})
if __name__ == '__main__':
    app.run(host='0.0.0.0', port='7000')
  • 创建.wsgi配置文件
    在项目test目录下创建mod_wsgi.wsgi,因为test目录在非root用户下,需要用chmod 777 mod_wsgi.wsgi命令将mod_wsgi.wsgi文件改成可读可写模式,是root用户下,apache运行后能调用该文件。
#mod_wsgi.wsgi
#!/usr/bin/python3

import sys
import os
import logging
import site

logging.basicConfig(level=logging.DEBUG, stream=sys.stderr)
site.addsitedir('/home/xxx/.local/lib/python3.5/site-packages')
sys.path.insert(0, '/mnt/disk2/xxx/work/test')

#logging.info(sys.path)

#import torch
#logging.debug(torch.__version__)

#def application(environ,start_response):
#    status='200 OK'
#    output=b'Hello wsgi!'
#    print(environ['wsgi.errors'], sys.path)
#    print (environ['wsgi.errors'], sys.prefix)
#    print (environ['wsgi.errors'], sys.executable)
#    response_headers=[('Content-type','text/plain'),
#                       ('Content-Length',str(len(output)))]
#    start_response(status,response_headers)
#    return[output]


from test_hello import app as application
  • 创建apache2配置文件
    /etc/apache2/sites-available/目录下创建flask_app.conf配置文件,在该文件中同样需要对mod_wsgi.wsgi文件、项目test目录、日志test/log目录设置可读写权限,并且还需要用命令chmod 777 xxx修改可读写权限。
#flask_app.conf
WSGIPythonHome /home/xxx/.local/lib/python3.5/site-packages
ServerName 10.27.1.20
Listen 7000
<VirtualHost *:7000>
    ServerAdmin webmaster@localhost
    WSGIDaemonProcess test python-path=/mnt/disk2/xxx/work/test:/home/xxx/.local/lib/python3.5/site-packages python-home=/home/xxx/.local/lib/python3.5/site-packages display-name=%{GROUP}

    WSGIScriptAlias / /mnt/disk2/xxx/work/test/mod_wsgi.wsgi process-group=test application-group=%{GLOBAL}
    <Directory /home/xxx/.local/lib/python3.5/site-packages/>
    Require all granted
    </Directory>
    <Directory /mnt/disk2/xxx/work/test/>
        WSGIScriptReloading On
        Require all granted
        <Files mod_wsgi.wsgi>
            Require all granted
        </Files>
    </Directory>

    <Directory /mnt/disk2/xxx/work/test/log/>
    Require all granted
    </Directory>
    LogLevel debug
    ErrorLog /mnt/disk2/xxx/work/test/log/apache_error.log
    CustomLog /mnt/disk2/xxx/work/test/log/apache_access.log combined
</VirtualHost>

  • 启动站点配置文件
    可在任意目录下启动
a2ensite flask_app.conf # 激活站点
a2dissite flask_app.conf # 屏蔽站点
  • 启动mod_wsgi
    可在任意目录下启动
a2enmod wsgi # 查看是否启动
a2dismod wsgi # 禁用
  • 启动apache服务
apache2ctl start # 启动
apache2ctl restart # 重启
apache2ctl reload # 重新加载站点
apache2ctl stop # 关闭
  • 通过端口号查看服务是否运行
fuser -v -n tcp 7000 # 查看端口服务
fuser -k 7000/tcp #关闭端口
  • 测试
    浏览器中输入http://10.27.1.20:7000/Test?strs=apache-wsgi-flask,如果返回{"message":"hello apache-wsgi-flask ","result":"OK"}则成功。

参考资料
部署方式
Linux配置Apache2的经验总结

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值