How to keep python http server forever?

I wrote a simple HTTP server in python to manage a database hosted on a server through a web interface. It works great and works as intended. However, he has one huge problem, it will not remain. It will work for an hour or so, but if you remain unused for extended periods of time when you return to using it, I must reinitialize it every time. Currently, the method I use to feed it is as follows:

def main(): global db db = DB("localhost") server = HTTPServer(('', 8080), MyHandler) print 'started httpserver...' server.serve_forever() if __name__ == '__main__': main() 

I run this in the background on a linux server, so I run a command like sudo python webserver.py and turn it off, but as I mentioned earlier, after a while it shuts down. Any advice is welcome because it is standing, I do not understand why it is closing.

+6
source share
5 answers

Well, the first step is to find out why it is crashing. Two possibilities are possible:

  • The serve_forever call throws an exception.
  • The python process crashes / terminates.

In the first case, you can make it live forever by wrapping it in a loop using try-except. It is probably a good idea to write error data.

The latter case is a bit more complicated, because it can be caused by many things. Will this happen if you run the script in the foreground? If not, maybe there is some kind of maintenance work that completes your script?

Not a complete answer, but perhaps enough to help you diagnose the problem.

+1
source

You can write a UNIX daemon in Python using python-daemon or a Windows service using pywin32 .

Unfortunately, I donโ€™t know a โ€œportableโ€ solution for writing daemon / service processes (in Python or otherwise).

+3
source

Here is one tip in a driving story. You certainly want to drive safely (find out why your program is not working and fix it). In the case of a (rare?) Accident, some monitoring infrastructure, such as monit , can be useful for restarting broken processes. You probably won't want to use it for paper work in the event of a crash, as if you didn't want to deploy your airbag every time you stopped the car.

+2
source

Have you tried to start it from a screen session?

 $ screen -L sudo python webserver.py 
+1
source

As an alternative to the screen, there is NoHup , which ensures that the process will start after logging out.

It is worth checking the logs to find out why he was killed / fired, and also can not be associated with the operating system, but an internal error.

0
source

Source: https://habr.com/ru/post/896997/


All Articles