项目部署:flask+mod_wsgi+apache

2024-02-08 11:48
文章标签 mod 部署 项目 apache flask wsgi

本文主要是介绍项目部署: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的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/690935

相关文章

sky-take-out项目中Redis的使用示例详解

《sky-take-out项目中Redis的使用示例详解》SpringCache是Spring的缓存抽象层,通过注解简化缓存管理,支持Redis等提供者,适用于方法结果缓存、更新和删除操作,但无法实现... 目录Spring Cache主要特性核心注解1.@Cacheable2.@CachePut3.@Ca

redis-sentinel基础概念及部署流程

《redis-sentinel基础概念及部署流程》RedisSentinel是Redis的高可用解决方案,通过监控主从节点、自动故障转移、通知机制及配置提供,实现集群故障恢复与服务持续可用,核心组件包... 目录一. 引言二. 核心功能三. 核心组件四. 故障转移流程五. 服务部署六. sentinel部署

SpringBoot通过main方法启动web项目实践

《SpringBoot通过main方法启动web项目实践》SpringBoot通过SpringApplication.run()启动Web项目,自动推断应用类型,加载初始化器与监听器,配置Spring... 目录1. 启动入口:SpringApplication.run()2. SpringApplicat

Springboot项目构建时各种依赖详细介绍与依赖关系说明详解

《Springboot项目构建时各种依赖详细介绍与依赖关系说明详解》SpringBoot通过spring-boot-dependencies统一依赖版本管理,spring-boot-starter-w... 目录一、spring-boot-dependencies1.简介2. 内容概览3.核心内容结构4.

Python Flask实现定时任务的不同方法详解

《PythonFlask实现定时任务的不同方法详解》在Flask中实现定时任务,最常用的方法是使用APScheduler库,本文将提供一个完整的解决方案,有需要的小伙伴可以跟随小编一起学习一下... 目录完js整实现方案代码解释1. 依赖安装2. 核心组件3. 任务类型4. 任务管理5. 持久化存储生产环境

在ASP.NET项目中如何使用C#生成二维码

《在ASP.NET项目中如何使用C#生成二维码》二维码(QRCode)已广泛应用于网址分享,支付链接等场景,本文将以ASP.NET为示例,演示如何实现输入文本/URL,生成二维码,在线显示与下载的完整... 目录创建前端页面(Index.cshtml)后端二维码生成逻辑(Index.cshtml.cs)总结

Python用Flask封装API及调用详解

《Python用Flask封装API及调用详解》本文介绍Flask的优势(轻量、灵活、易扩展),对比GET/POST表单/JSON请求方式,涵盖错误处理、开发建议及生产环境部署注意事项... 目录一、Flask的优势一、基础设置二、GET请求方式服务端代码客户端调用三、POST表单方式服务端代码客户端调用四

Python WSGI HTTP服务器Gunicorn使用详解

《PythonWSGIHTTP服务器Gunicorn使用详解》Gunicorn是Python的WSGI服务器,用于部署Flask/Django应用,性能高且稳定,支持多Worker类型与配置,可处... 目录一、什么是 Gunicorn?二、为什么需要Gunicorn?三、安装Gunicorn四、基本使用启

Linux部署中的文件大小写问题的解决方案

《Linux部署中的文件大小写问题的解决方案》在本地开发环境(Windows/macOS)一切正常,但部署到Linux服务器后出现模块加载错误,核心原因是Linux文件系统严格区分大小写,所以本文给大... 目录问题背景解决方案配置要求问题背景在本地开发环境(Windows/MACOS)一切正常,但部署到

Spring Boot项目如何使用外部application.yml配置文件启动JAR包

《SpringBoot项目如何使用外部application.yml配置文件启动JAR包》文章介绍了SpringBoot项目通过指定外部application.yml配置文件启动JAR包的方法,包括... 目录Spring Boot项目中使用外部application.yml配置文件启动JAR包一、基本原理