My Python threading problem, trying to update webserver module

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

My Python threading problem, trying to update webserver module

tristanexmachina
I have been wracking my brain over what should be a simple project
but I'm trying to learn this whole threading business so I figured
what better way then to update the NakedMUD webserver module in
python and as a spawned thread rather than a constantly updating
poller. Here is the broken code I came up with:

[code]
'''
 webserver.py                                                    
5/5/2008

 A python interpretation of the webserver module allowing various
sorts of
 information to be accessed from a web browser.
   -Hannibal

 Thanks to Geoff Hollis ([hidden email]) for the original C code
and
 Jon Berg ([hidden email]) for his python tutorial on the
subject.
'''

# Python Webserver imports
import string, cgi, time, threading
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

# NakedMud imports
import mud, mudsys, char, hooks, account, socket, inform, event
from colour_HTML import process_HTML_colour

module_name = 'NakedMud Python Webserver v1.0'

###############################################
# Define the webserver port here
web_port = 3098
###############################################

'''------------------------------------------------------
Extremely simple webserver and handler.
------------------------------------------------------'''
class NakedHTTPServer(HTTPServer):
    def server_bind(self):
        HTTPServer.server_bind(self)
        self.socket.settimeout(3)
        self.running = True

    def get_request(self):
        while self.running:
            try:
                sock, addr = self.socket.accept()
                sock.settimeout(None)
                return (sock, addr)
            except socket.timeout:
                pass

class NakedHandler(BaseHTTPRequestHandler):
    def do_GET(self):
         # Collect what information we are looking for
         # Information is sent to the server as part of the path
         # Each argument is separated by a slash
         # The first argument is the function to be called
         keywords = self.path.lower().split("/")
         # Build your list of webserver requests here:
         if keywords[1] == "who":
             buffer = inform.build_who()
         elif keywords[1] == "motd":
             buffer = mud.get_motd()
         # other 'elifs' go here
         else:
             buffer = "Unknown request."

         buffer = buffer.replace('\r','')
         buffer = buffer.replace('\n','<br>')
         buffer = buffer.replace(' ','&nbsp')

         # Send information
         self.send_response(200)
         self.send_header(module_name,'text/html')
         self.end_headers()
         self.wfile.write("<html><body bgcolor=\"black\"
text=\"silver\">")
         self.wfile.write("<font face=\"courier\">")
         self.wfile.write(process_HTML_colour(buffer))
         self.wfile.write("</font></body></html>")
         return

class nakedThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.HTTPD = NakedHTTPServer(('', web_port), NakedHandler)
        self.running = True

    def stop(self):
        self.running = False

    def run(self):
        self.running = True
        while self.running:
            self.HTTPD.handle_request()

'''------------------------------------------------------
Hooks, initializations, finalizations and other necessary
objects that make this module function.
------------------------------------------------------'''
nakedserver = nakedThread()

def init_webserver_hook(info):
    nakedserver.start()

def finalize_webserver_hook(info):
    nakedserver.stop()

hooks.add("initialize", init_webserver_hook)
hooks.add("shutdown", finalize_webserver_hook)

def __unload__():
    hooks.remove("initialize", init_webserver_hook)
    hooks.remove("shutdown", finalize_webserver_hook)
[/code]
Well the brick wall I hit is this (and it may boil down to a
fundamental misunderstanding on my part):

I know the webserver part works, when I run the handle_request() as
part of a loop within the main python code like this:
[code]
def init_webserver_hook(info):
        nakedserver.running = True
        while nakedserver.running:
            nakedserver.HTTPD.handle_request()
[/code]
everything works fine- except that the game is stuck in the webserver
loop and doesn't update itself. However, when I try to spawn a thread
using the top code the game works fine but the webserver does not
respond to requests. It was my hope that starting a separate
webserver thread would allow the game to continue as normal while
also running the webserver loop, but this doesn't seem to be the case
and I don't understand why.

As a side note, when I throw the handle_request() inside an
event_update() as part of the init_webserver_hook it stalls the game
until the first request is handled by the webserver, then the
webserver dies (times out requests) and the game continues as normal.
This is probably a stupid thing to do but I was curious and to me
this is an unexpected result, any explanations?

I am looking for some help understanding why this concept doesnt
work. Is it fundamentally a bad idea or is it just my execution that
is lacking. Any help at all would be hot. Thanks


------------------------------------

Yahoo! Groups Links

<*> To visit your group on the web, go to:
    http://groups.yahoo.com/group/nakedmud/

<*> Your email settings:
    Individual Email | Traditional

<*> To change settings online go to:
    http://groups.yahoo.com/group/nakedmud/join
    (Yahoo! ID required)

<*> To change settings via email:
    mailto:[hidden email]
    mailto:[hidden email]

<*> To unsubscribe from this group, send an email to:
    [hidden email]

<*> Your use of Yahoo! Groups is subject to:
    http://docs.yahoo.com/info/terms/

Reply | Threaded
Open this post in threaded view
|

Re: My Python threading problem, trying to update webserver module

Stephen Squires
Did you ever get this code working?  I'd be interested in it if so.

--- In [hidden email], "tristanexmachina"
<tristanexmachina@...> wrote:

>
> I have been wracking my brain over what should be a simple project
> but I'm trying to learn this whole threading business so I figured
> what better way then to update the NakedMUD webserver module in
> python and as a spawned thread rather than a constantly updating
> poller. Here is the broken code I came up with:
>
> [code]
> '''
>  webserver.py                                                    
> 5/5/2008
>
>  A python interpretation of the webserver module allowing various
> sorts of
>  information to be accessed from a web browser.
>    -Hannibal
>
>  Thanks to Geoff Hollis (hollis@...) for the original C code
> and
>  Jon Berg (jon.berg@...) for his python tutorial on the
> subject.
> '''
>
> # Python Webserver imports
> import string, cgi, time, threading
> from os import curdir, sep
> from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
>
> # NakedMud imports
> import mud, mudsys, char, hooks, account, socket, inform, event
> from colour_HTML import process_HTML_colour
>
> module_name = 'NakedMud Python Webserver v1.0'
>
> ###############################################
> # Define the webserver port here
> web_port = 3098
> ###############################################
>
> '''------------------------------------------------------
> Extremely simple webserver and handler.
> ------------------------------------------------------'''
> class NakedHTTPServer(HTTPServer):
>     def server_bind(self):
>         HTTPServer.server_bind(self)
> self.socket.settimeout(3)
> self.running = True
>
>     def get_request(self):
>         while self.running:
>    try:
>                 sock, addr = self.socket.accept()
> sock.settimeout(None)
> return (sock, addr)
>    except socket.timeout:
> pass
>
> class NakedHandler(BaseHTTPRequestHandler):
>     def do_GET(self):
>          # Collect what information we are looking for
>          # Information is sent to the server as part of the path
>          # Each argument is separated by a slash
>          # The first argument is the function to be called
>          keywords = self.path.lower().split("/")
>          # Build your list of webserver requests here:
>          if keywords[1] == "who":
>              buffer = inform.build_who()
>          elif keywords[1] == "motd":
>              buffer = mud.get_motd()
>          # other 'elifs' go here
>          else:
>              buffer = "Unknown request."
>
>          buffer = buffer.replace('\r','')
>          buffer = buffer.replace('\n','<br>')
>          buffer = buffer.replace(' ','&nbsp')
>
>          # Send information
>          self.send_response(200)
>          self.send_header(module_name,'text/html')
>          self.end_headers()
>          self.wfile.write("<html><body bgcolor=\"black\"
> text=\"silver\">")
>          self.wfile.write("<font face=\"courier\">")
>          self.wfile.write(process_HTML_colour(buffer))
>          self.wfile.write("</font></body></html>")
>          return
>
> class nakedThread(threading.Thread):
>     def __init__(self):
> threading.Thread.__init__(self)
> self.HTTPD = NakedHTTPServer(('', web_port), NakedHandler)
> self.running = True
>
>     def stop(self):
>         self.running = False
>
>     def run(self):
> self.running = True
> while self.running:
>    self.HTTPD.handle_request()
>
> '''------------------------------------------------------
> Hooks, initializations, finalizations and other necessary
> objects that make this module function.
> ------------------------------------------------------'''
> nakedserver = nakedThread()
>
> def init_webserver_hook(info):
>     nakedserver.start()
>
> def finalize_webserver_hook(info):
>     nakedserver.stop()
>
> hooks.add("initialize", init_webserver_hook)
> hooks.add("shutdown", finalize_webserver_hook)
>
> def __unload__():
>     hooks.remove("initialize", init_webserver_hook)
>     hooks.remove("shutdown", finalize_webserver_hook)
> [/code]
> Well the brick wall I hit is this (and it may boil down to a
> fundamental misunderstanding on my part):
>
> I know the webserver part works, when I run the handle_request() as
> part of a loop within the main python code like this:
> [code]
> def init_webserver_hook(info):
> nakedserver.running = True
> while nakedserver.running:
>    nakedserver.HTTPD.handle_request()
> [/code]
> everything works fine- except that the game is stuck in the webserver
> loop and doesn't update itself. However, when I try to spawn a thread
> using the top code the game works fine but the webserver does not
> respond to requests. It was my hope that starting a separate
> webserver thread would allow the game to continue as normal while
> also running the webserver loop, but this doesn't seem to be the case
> and I don't understand why.
>
> As a side note, when I throw the handle_request() inside an
> event_update() as part of the init_webserver_hook it stalls the game
> until the first request is handled by the webserver, then the
> webserver dies (times out requests) and the game continues as normal.
> This is probably a stupid thing to do but I was curious and to me
> this is an unexpected result, any explanations?
>
> I am looking for some help understanding why this concept doesnt
> work. Is it fundamentally a bad idea or is it just my execution that
> is lacking. Any help at all would be hot. Thanks
>


Reply | Threaded
Open this post in threaded view
|

Re: My Python threading problem, trying to update webserver module

tristanexmachina
No I never got it working, it still doesnt make sense to me why the
threading was not working but I have moved on to storing everything in
MySQL so I don't need a webserver anymore so I gave up on the project.

--- In [hidden email], "stevesquires42"
<stephen.squires@...> wrote:
>
> Did you ever get this code working?  I'd be interested in it if so.
>
> --- In [hidden email], "tristanexmachina"
> <tristanexmachina@> wrote: