简体   繁体   中英

run a python script as service with daemontools

For a project I have a simple python script that offers a http interface with flask. The script itself works like a charm.

#!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)

As this is just a simple script, it's not very usable, as it doesn't start on are system boot or on a crash. So the next is to create a service on my debian server that supervises that script. I'm very new to debian an the whole server thing, so I find the approach over the .conf files a bit confusing. As simple alternativ I've found daemontools. I did install it, and it runs. I created a subfolder in /etc/services and placed a run.sh file in it with the following content:

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

svscan detects it and creates a supervise folder next to it. Although instead of starting the restservice.py successfully, I only get a supervise , which means that there must be something wrong I guess.

Am I missing something or what could possibly be the probleme here?

Why do you require sudo in run.sh? supervise works as a root by default.

Try to add logging in your run.sh. Change the line to be:

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

Then check /var/log/user.log for output.

You may also want to use multilog from daemontools: http://cr.yp.to/daemontools/multilog.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM