Python Web开发学习

通过Celery在网页调用后台脚本重启uwsgi和nginx服务

2018-12-15  本文已影响1人  吾星喵

通过Celery在网页调用后台脚本重启uwsgi和nginx服务

首先你得把Celery搭建好

创建重启服务shell脚本

(StarMeow) root@StarMeow-Svr:~/django-web# vim AutoUwsgi.sh


#! /bin/bash
sleep 3

echo '关闭uwsgi进程!'

killall -9 uwsgi

echo '关闭nginx进程!'

killall -9 nginx

sleep 1

echo '-----------------'

echo '正在加载uwsgi配置...'
cd /root/django-web/StarMeow
# uwsgi --ini uwsgi.ini --http-websockets
# 使用绝对路径
/root/.pyenv/versions/StarMeow/bin/uwsgi --ini /root/django-web/StarMeow/uwsgi.ini --http-websockets


sleep 2
echo '正在重启nginx服务...'
service nginx restart
service nginx reload

echo '-----------------'
sleep 2

process1=`ps aux | grep nginx | grep -v grep`;
if [ "$process1" == "" ]; then
        sleep 1;
        echo "nigix启动失败!";
else
        echo "nginx重启完成~";
fi

process2=`ps aux | grep uwsgi | grep -v grep`;
if [ "$process2" == "" ]; then
        sleep 1;
        echo "uwsgi启动失败!";
else
        echo "uwsgi重启完成~";
fi

创建tasks的任务模块

在应用下创建tasks.py文件,然后添加代码

from __future__ import absolute_import, unicode_literals
from celery import shared_task
import subprocess

from StarMeow.celery import app

from coolqbot.api import qqbot_api_data, qqbot_host_port  # 用于qqbot接口


@app.task
def reboot_uwsgi_task():
    try:
        sub = subprocess.Popen("/root/django-web/AutoUwsgi.sh", shell=True, stdout=subprocess.PIPE, cwd="/root/django-web/")
        text = sub.stdout.read().decode('utf8')
        print(text)
        qqbot_api_data(qqbot_host_port, '/send_group_msg', group_id=531809487, message=text)
    except NotADirectoryError as e:
        print(e)

视图中调用异步任务

from .tasks import reboot_uwsgi_task

def reboot_uwsgi(request):
    """重启服务器"""
    reboot_uwsgi_task.delay()  # 异步执行重启程序,防止造成服务终端,重启不成功
    return redirect(reverse('supervise:supervise_index'))

网页网上点击连接即可完成重启,注意连接的访问权限,不能每个人都能访问

重启完成后,QQ就会受到消息

image.png
上一篇下一篇

猜你喜欢

热点阅读