How to get WSGI servers to close a connection after each response?

1k views Asked by At

The API for Python's wsgiref module precludes hop-by-hop headers (as defined in RFC 2616).

I'm unclear on how to get the server to terminate a connection after a response (since there doesn't seem to be a way to add Connection: close).

This problem comes up in testing small WSGI apps and Bottle micro-services. Calls from curl get blocked by open connections from a browser. I have to click a browser refresh to terminate the connection so that the pending curl request can be answers.

Obviously, this should be a server side decision (terminate connection after a response) rather than client-side. I'm unclear how to implement this.

1

There are 1 answers

0
eatmeimadanish On

This is really predicated on your WSGI server you are hosting your framework via. The best solution with bottle is to run it through gevent.

botapp = bottle.app()
for Route in (mainappRoute,): #handle multiple files containing routes
    botapp.merge(Route)
botapp = SessionMiddleware(botapp, beakerconfig) #in case you are using beaker sessions
botapp = WhiteNoise(botapp) #in case you want whitenoise to handle static files
botapp.add_files(staticfolder, prefix='static/') #add static route to whitenoise
server = WSGIServer(("0.0.0.0", int(80)), botapp) #gevent async web server
def shutdown():
    print('Shutting down ...')
    server.stop(timeout=60)
    exit(signal.SIGTERM)
gevent.signal(signal.SIGTERM, shutdown)
gevent.signal(signal.SIGINT, shutdown) #CTRL C
server.serve_forever() #spawn the server

You can purge the whitenoise and bottle configs if they aren't necessary, I kept them there as an example, and a suggestion that you use them if this is outward facing.

This is purely asynchronous on every connection.