本文主要是介绍项目部署: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 timedef 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/python3import sys
import os
import logging
import sitelogging.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@localhostWSGIDaemonProcess 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 OnRequire all granted<Files mod_wsgi.wsgi>Require all granted</Files></Directory><Directory /mnt/disk2/xxx/work/test/log/>Require all granted</Directory>LogLevel debugErrorLog /mnt/disk2/xxx/work/test/log/apache_error.logCustomLog /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的经验总结
这篇关于项目部署:flask+mod_wsgi+apache的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!