Integrating a simple web server into a custom main loop in python?

loops, python

Solution

Twisted is designed to make stuff like that fairly simple

import time

from twisted.web import server, resource
from twisted.internet import reactor

class Simple(resource.Resource):
    isLeaf = True
    def render_GET(self, request):
        return "<html>%s Iterations!</html>"%n

def main():
    global n
    site = server.Site(Simple())
    reactor.listenTCP(8080, site)
    reactor.startRunning(False)
    n=0
    while True:
        n+=1
        if n%1000==0:
            print n
        time.sleep(0.001)
        reactor.iterate()

if __name__=="__main__":
    main()

Problem

I have an application in python with a custom main loop (I don't believe the details are important). I'd like to integrate a simple non-blocking web server into the application which can introspect the application objects and possibly provide an interface to manipulate them. What's the best way to do this? I'd like to avoid anything that uses threading. The ideal solution would be a server with a "stepping" function that can be called from my main loop, do its thing, then return program control until the next go-round. The higher-level the solution, the better (though something as monolithic as Django might be overkill). Ideally, a solution will look like this: ``` def main(): """My main loop.""" http_server = SomeCoolHttpServer(port=8888) while True: # Do my stuff here... # ... http_server.next() # Server gets it's turn. # Do more of my stuff here... # ... ```

Original source