пятница, 11 января 2013 г.

Quick recipe how to launch simple daemonized web service using python

Writing linux daemon in C or C++  could be done easily. It is a native daemon creating approach for unix. What can we do if we need to use a python script like a daemon? There are several solutions how to daemonize your python code. In this post I just want to mention a simple and convenient pattern which I usually use. It is based on the linux deamon template written by Sander Marechal (2.X 3.X). This is a pretty good code, I integrated it into several prototypes and they work perfectly. It contains simple to use Daemon class which python daemon developer should inherit.


In my opinion, this is a good way to run simple web-service in daemon mode. Sure, instead of running your script as a daemon you can use .bashrc or launch it in terminal. But what about auto restart after reboot? Or just without logging in? What about auto restart on termination? 

It is easy to write client code which inherits Daemon class. Here is an example how to run simple xml-rpc service in daemon mode (example from SVM classifier remote service prototype):

class ServerClass():
    def __init__(self):
        self.ai_agent = cls.SVMClassifier() def classify_data(self, data):
        category = self.ai_agent.datacategory(data)
        return category
    def get_categories(self):
        return self.ai_agent.categories

class ClassifierDaemon(Daemon):
    def run(self):
        while True:
            try:
                server = SimpleXMLRPCServer(("", 8001))
                server.register_instance(ServerClass())
                server.register_introspection_functions()
                server.serve_forever()
            except Exception as e:
                pass

"pass" instruction and catching block should be replaced by properly written Exceptions Handler.

now you can type

classifier_daemon.py stop
classifier_daemon.py start
classifier_daemon.py restart

It works )

Recently I started to use Python 3.3 I  like it, but this code is still written for 2.7. The reason is that I prefer to run such web services using pypy instead of CPython (in order to make them faster). Pypy is going to be compatible with CPython 3.X. Once this officialy done, I'll switch to 3.3 or higher.

Комментариев нет:

Отправить комментарий