Tuukka Turto
Tuukka Turto

Reputation: 145

How to run web.py server inside of another application

I have a little desktop game written in Python and would like to be able to access internal of it while the game is running. I was thinking of doing this by having a web.py running on a separate thread and serving pages. So when I access http://localhost:8080/map it would display map of the current level for debugging purposes.

I got web.py installed and running, but I don't really know where to go from here. I tried starting web.application in a separate thread, but for some reason I can not share data between threads (I think).

Below is simple example, that I was using testing this idea. I thought that http://localhost:8080/ would return different number every time, but it keeps showing the same one (5). If I print common_value inside of the while loop, it is being incremented, but it starts from 5.

What am I missing here and is the approach anywhere close to sensible? I really would like to avoid using database if possible.

import web
import thread

urls = (
    '/(.*)', 'hello'
)

app = web.application(urls, globals())

common_value = 5

class hello:        
    def GET(self):  
        return str(common_value)

if __name__ == "__main__":
    thread.start_new_thread(app.run, ())    
    while 1:
        common_value = common_value + 1

Upvotes: 2

Views: 1840

Answers (2)

Cletrix
Cletrix

Reputation: 402

I found erros with arguments, but change : def GET(self):

with:

def GET(self, *args):

and works now.

Upvotes: 1

Tuukka Turto
Tuukka Turto

Reputation: 145

After searching around a bit, I found a solution that works:

If common_value is defined at a separate module and imported from there, the above code works. So in essence (excuse the naming):

thingy.py

common_value = 0

server.py

import web
import thread
import thingy

import sys; sys.path.insert(0, ".")

urls = (
    '/(.*)', 'hello'
)

app = web.application(urls, globals())

thingy.common_value = 5

class hello:        
    def GET(self):               
        return str(thingy.common_value)

if __name__ == "__main__":
    thread.start_new_thread(app.run, ())    
    while 1:
        thingy.common_value = thingy.common_value + 1

Upvotes: 1

Related Questions