python 写接口供外部调用

.py:

import requests
import urllib2
import commands
import subprocess



def check():
    status, msg = commands.getstatusoutput("ps -ef | grep build_lp.sh | grep -Fv grep")
    if msg.find('build_lp.sh') > -1:
        print("build_lp.sh still running wait 1 second...")
        return True
    return False


def offer_build(cmd, path, mode):
    if "/build_prod" == cmd:
        while check():
            time.sleep(1)
        realcmd = 'source ~/.bash_profile && source ~/.bashrc && cd %s && mkdir -p logs && mkdir -p data && bash bin/build_lp.sh %s >> ./logs/build_lp.log' % (path, mode)
        return commands.getstatusoutput(realcmd)
    elif "/build_prod_async" == cmd:   
         while check():
            return "1", "please wait for a while"
        realcmd = 'source ~/.bash_profile && source ~/.bashrc && cd %s && mkdir -p logs && mkdir -p data && bash bin/build_lp.sh %s >> ./logs/build_lp.log' % (path, mode)
        subprocess.Popen(realcmd,shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        return 0, "done"
    else:
        print("method not found: support (/build_prod & /build_prod_async)")
        return commands.getstatusoutput('free')


def app(environ, start_response):
    status, data = commands.getstatusoutput("ps -ef | grep start.sh | grep -Fv grep | awk '{print $10}'")
    if data != "prod":
        path = "/data1/menghui.lv/git/jupiteroffer/output" #debug 
        mode = "debug"
    else:
        path = "/data/jupiteroffer/output"                 #prod
        mode = "prod"
    timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
    rst = offer_build(environ['PATH_INFO'], path, mode)
    ret = {}    
    ret['status'] = 'ok' if rst[0] == 0 else 'error'
    ret['msg'] = rst[1]
    with open('control.log', 'a') as fo:
        fo.write("%s\t%s\t%s\n" %(timestamp, environ['PATH_INFO'], json.dumps(ret)))
    data = json.dumps(ret)
    start_response("200 OK", [
        ("Content-Type", "text/plain"),
        ("Content-Length", str(len(data)))
    ])
    return iter([data])
    print "hello"

# end   

 

.sh:

#!/usr/bin/env bash

if [ $#  == 0 ]; then
    echo "bash start.sh debug or bash start.sh prod"
else
    echo "$1"
    mkdir -p logs
    sleep 1
    if [[ "prod" = $1 ]]; then
        port=8386
    else
        port=8200
    fi
    nohup gunicorn -k gevent --log-syslog  --max-requests=300 -w 5 -b 0.0.0.0:$port jupitercontrol:app >> ./logs/build.log 2>&1 &
    #gunicorn -k gevent --log-syslog  --max-requests=300 -w 5 -b 0.0.0.0:$port jupitercontrol:app                        
fi
# end

 

posted @ 2019-01-21 14:08  lvmenghui001  阅读(3111)  评论(0编辑  收藏  举报