SuperFamousGuy
SuperFamousGuy

Reputation: 69

How do I keep a python HTTP Server up forever?

I wrote a simple HTTP server in python to manage a database hosted on a server via a web UI. It is perfectly functional and works as intended. However it has one huge problem, it won't stay put. It will work for an hour or so, but if left unused for long periods of time when returning to use it I have to re-initialize it every time. Right now the method I use to make it serve is:

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 would run a command like sudo python webserver.py & to detach it, but as I mentioned previously after a while it quits. Any advice is appreciated cause as it stands I don't see why it shuts down.

Upvotes: 9

Views: 11884

Answers (5)

Alec Munro
Alec Munro

Reputation: 223

Well, first step is to figure out why it's crashing. There's two likely possibilities:

  • The serve_forever call is throwing an exception.
  • The python process is crashing/being terminated.

In the former case, you can make it live forever by wrapping it in a loop, with a try-except. Probably a good idea to log the error details.

The latter case is a bit trickier, because it could be caused by a variety of things. Does it happen if you run the script in the foreground? If not, maybe there's some kind of maintenance service running that is terminating your script?

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

Upvotes: 1

Paul Rubel
Paul Rubel

Reputation: 27222

Here's one piece of advice in a story about driving. You certainly want to drive safely (figure out why your program is failing and fix it). In the (rare?) case of a crash, some monitoring infrastructure, like monit, can be helpful to restart crashed processes. You probably wouldn't want to use it to paper over a crash just like you wouldn't want to deploy your air bag every time you stopped the car.

Upvotes: 4

André Caron
André Caron

Reputation: 45224

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

Unfortunately, I know of no "portable" solution to writing daemon / service processes (in Python, or otherwise).

Upvotes: 4

SimonEP
SimonEP

Reputation: 11

As an alternative to screen there is NoHup which will ensure the process carries on running after your logged out.

Its worth checking the logs to see why its killed/quitting as well as it may not be related to the operating system but an internal fault.

Upvotes: 1

Alex Smith
Alex Smith

Reputation: 1535

Have you tried running it from inside a screen session?

$ screen -L sudo python webserver.py

Upvotes: 1

Related Questions