bottlepy / bottle

bottle.py is a fast and simple micro-framework for python web-applications.
http://bottlepy.org/
MIT License
8.37k stars 1.46k forks source link

0.13dev : shutdown of WSGIRefServer #1230

Closed josephernest closed 4 years ago

josephernest commented 4 years ago

Since 0.13dev now exposes the server object in self.srv for the WSGIRefServer, we could use it for shutdown like this, which is essentially the same than this answer on StackOverflow:

import bottle
@bottle.route('/')
def index():
    return 'hello'
@bottle.route('/stop')
def stopit():
    print('Stopping')
    server.srv.shutdown()
server = bottle.WSGIRefServer(port=80)
bottle.run(server=server)
print('Bye')

Opening http://localhost/ works, but opening http://localhost/stop does not, why?

josephernest commented 4 years ago

I solved it with a new thread:

from bottle import WSGIRefServer, run, route
from threading import Thread

@route('/')
def index():
    return 'Hello world'

@route('/stop')
def stopit():
    Thread(target=shutdown).start()

def shutdown():
    server.srv.shutdown()

server = WSGIRefServer(port=80)
run(server=server)
MartinRamm commented 3 years ago

For anyone else struggling to start the server again after shutting it down: you may need to call server_close as well to free up the port and avoid error: [Errno 98] Address already in use errors.

Extending from the example above:

def shutdown():
    server.srv.shutdown()
    server.srv.server_close()