使用daemontools运行python脚本作为服务

时间:2015-03-31 14:19:38

标签: python service debian

对于一个项目,我有一个简单的python脚本,它提供了一个带烧瓶的http接口。剧本本身就像一个魅力。

#!flask/bin/python
from flask import Flask,request, Response
import os.path
import json
import sys
import logging
import logging.handlers
from dbMongoManager import saveToMongo
from dbSQLManager import saveToMYSQL
from FailedRequest import FailedRequest
from JSONValidation import validateJSON

app = Flask(__name__)

#create logger
logger = logging.getLogger('werkzeug')
#defines logger file and max size
handler = logging.handlers.RotatingFileHandler('request.log',maxBytes=5000000)
#define logger format
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s")
handler.setFormatter(formatter)
#add loggerhandler to applications
logger.addHandler(handler)
app.logger.addHandler(handler)

#invoked method on a POST request
@app.route('/',methods = ['POST'])
def add():
    """
    This function is mapped to the POST request of the REST interface
    """
    print ("incoming POST")
    #check if a JSON object is declared in the header

    if request.headers['Content-Type'] == 'application/json; charset=UTF-8' and request.data:
            print ("passed contentType check")
            data = json.dumps(request.json)
            #check if recieved JSON object is valid according to the scheme
            #if (validateJSON(data)):
            saveToMongo(data)
            return "JSON Message saved in MongoDB"

    raise FailedRequest

#invoked method on a POST request
@app.route('/sql',methods = ['POST'])
def addSQL():
    """
    This function is mapped to the POST request of the REST interface
    """
    print ("incoming SQL POST")
    #check if a JSON object is declared in the header

    if request.headers['Content-Type'] == 'application/json; charset=UTF-8':
        print ("passed contentType check")

        data = request.json
        #check if recieved JSON object is valid according to the scheme
        if (validateJSON(json.dumps(data))):
            saveToMYSQL(data)
            return "JSON Message saved in SQLDB"

    raise FailedRequest

if __name__ == "__main__":
    print "Start App"
    app.run(host="0.0.0.0",port=int("80"),debug=True)

由于这只是一个简单的脚本,它不是很有用,因为它不是从系统启动或崩溃开始的。接下来是在我的debian服务器上创建一个服务来监督该脚本。 我是一个非常新的debian整个服务器的东西,所以我发现.conf文件的方法有点令人困惑。作为简单的替代方案,我发现了daemontools。 我确实安装了它,然后运行。我在/ etc / services中创建了一个子文件夹,并在其中放置了一个run.sh文件,其中包含以下内容:

#!/bin/sh
echo Running service
sudo python /home/admin/RestService.py 

svscan检测到它并在其旁边创建一个监督文件夹。 虽然我没有成功启动restservice.py,但我只接受监督,这意味着我猜想肯定会出现问题。

我错过了什么或者可能是什么问题?

1 个答案:

答案 0 :(得分:1)

为什么在run.sh中需要sudo? supervise 默认用作root。

尝试在run.sh中添加日志记录。将行更改为:

python /home/admin/RestService.py 2>&1 | logger -t RestService

然后检查/var/log/user.log以获取输出。

您可能还想使用来自daemontools的多日志:http://cr.yp.to/daemontools/multilog.html

相关问题