站在运维的角度使用django写一些简单操作的接口

事件出发点:

       前端的开发每次更新了JS或者CSS  都会要清理nginx的缓存,对于这操作站在我们运维的角度就是执行脚本的问题。但是如何让开发自己清理缓存,但又不涉及到线上服务器的操作呢?

那肯定就是写个WEB接口,让他们自己去操作,对应的类似查看日志之类的。


那我们就拿清理nginx缓存这个问题来说吧。


首先我们得有一个WEB,不管是django还是flask 都是很好的框架,而且python对运维的契合度也比较高,我选择的是django


步骤

  1. 首先,我们在nginx的服务器上有个清理缓存的脚本。

  2. django 的一个WEB框架

  3. ansible (不用也行)但是还是用的好,方便。

  4. 预留


首先贴一下django的配置,他和ansible在一台机器上,可以通过SSH访问nginx服务器

views.py

from django.shortcuts import render
from django.contrib import auth
# Create your views here.
from django.shortcuts import render_to_response
from django.contrib.auth import authenticate, login
from django.template.loader import get_template
from django.template import Context,RequestContext
#from django.template import loader, RequestContext
from django.http import HttpResponse,HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from ops.models import server,passets
#def login(request):
#    t = get_template('login.html')
#    loginhtml = t.render(Context({'username': username,'password':password}))
#    return HttpResponse(loginhtml)

import commands
def nginx(request,string):     #这里的string 就是URL那边传过来的参数
    if string == 't_nginx':
        try:
            m=commands.getoutput(''' ansible %s -m shell -a "sh /opt/script/clean_cache.sh"  ''' %string)
            return render_to_response('interface/nginx_interface.html',{'result':m})
        except Exception as e:
            return render_to_response('interface/nginx_interface.html',{'result':e})


url.py

from ops import views
url(r'^interface/(?P<string>\S+)/$',views.nginx,name='nginx'),


html 模板

cat /var/www/jastme/interface/nginx_interface.html 
{{ result }}


对django不是很熟悉的可以去看看我以前写的django的文章

 

ansible的配置

apt-get install ansible

cat /etc/ansible/hosts
[t_nginx]
172.31.9.125 ansible_ssh_user=nginx ansible_ssh_pass=123456   当然你也可以用密钥

效果图

这个接口已经正常工作,是不是很简单啊

你可能感兴趣的:(站在运维的角度使用django写一些简单操作的接口)