Integrating HTTPServer and GUI

Joonas Paalasmaa joonas at olen.to
Fri Aug 31 07:38:52 EDT 2001


I have made a httpserver that prints all its logs into Tkinter Text
window.
The only problem is that when the GUI reads data from the server
with os.read, the GUI is blocked.
Any suggestions how to solve this?
Is there any other ways to implement realtime communication between
threads than
os.pipe and using globals.

- Joonas

#!/usr/bin/python

import threading, time, sys, BaseHTTPServer, os
from Tkinter import *

PORT = 80

log_lines = 20

requests = 0


pipein, pipeout = os.pipe()


class HTTPWrapper(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_GET(self):
        global requests
        requests += 1
        self.send_response(200)
        self.send_header("Content-type","text/html")
        self.end_headers()
        self.wfile.write("it works!")
    def log_message(self, format, *args):
        os.write(pipeout, "%s - - [%s] %s\n" %
                     (self.address_string(),
                      self.log_date_time_string(),
                      format%args))


class SimpleWidget(Frame):
    def add_line(self, line):
        if self.number_of_lines >= log_lines:
            self.text.delete("1.0", "2.0")
        self.text.insert(END, line+"\n")
        self.number_of_lines += 1
        self.infolabel.set(str(requests)+" requests since startup")
    def get_server_info(self):
        self.update()
        self.new_char = os.read(pipein, 1) #this blocks the GUI
        if self.new_char == "\n":
            self.add_line(self.linebuffer)
            self.linebuffer = ""
        else:
            self.linebuffer += self.new_char
        self.get_server_info()
    def __init__(self):
        self.number_of_lines = 0
        self.linebuffer = ""
        Frame.__init__(self)
        self.pack()
        self.infolabel = StringVar()
        Label(self, textvariable=self.infolabel).pack(side=TOP)
        self.infolabel.set("foo")
        Button(self,text="Shut down server", command=self.quit).pack()
        self.text = Text(self)
        self.text.pack()
        self.get_server_info()


httpd = BaseHTTPServer.HTTPServer(("", PORT), HTTPWrapper)
threading.Thread( target=httpd.serve_forever ).start()

SimpleWidget().mainloop()



More information about the Python-list mailing list