waiting for request using BaseRequestHandler

B

Ben

Hi all,

I'd like to know if there is a way to find out the requested filename
using BaseRequestHandler's handle() method... My code looks like this:

def makeList():
mylist=[]
l=''
if os.path.exists("listfile"):
mf=get_file("listfile")
mylist=mf[0].split(' ')
for c in mylist:
l += '<a href=http://localhost:8755/%s>'%c+c+'</a><br>'
else:
#.................
#.................
#.................

header = "HTTP/1.0 200 OK\n"
header += "Content-Type: text/html\n"
header += "Content-Length: %d\n\n"%len(l)
return header+l

class ListHandler(SocketServer.BaseRequestHandler):

def handle(self):
request = self.request.recv(1024)
self.request.send(makeList())

myServer = SocketServer.TCPServer(('',8755), ListHandler)
myServer.serve_forever()

In the above code, if I make a request from a browser such as
"http://localhost:8755", it gives me an html page generated by
makeList() method. So the browser displays links like this(for
example):
Peter
-----
Jack
----
Ken
---
Jane
----

Here, Peter's link is "http://localhost:8755/Peter". I'd like to know
while the server is waiting for a request, how do I make it determine
the path (eg, "http://localhost:8755/Peter"). Initially it takes any
http reqeust and calls makeList() method... What i want to do is I
want makeList() to be called only when the request is
"http://localhost:8755/". For "http://localhost:8755/Peter", I want to
call another method... How do i fix my webserver to handle this?

Thanks
Ben
 
B

bromden

please read the docstring of the class BaseHTTPRequestHandler

normally you should subclass BaseHTTPRequestHandler and override
methods do_GET(), do_POST() and so on, which are handling specific
HTTP commands,
the info about a request being processed is stored in the class
members described in the docstring, specifically the path is
in (guess) "path",
moreover, you shouldn't assemble response header yourself,
use the methods send_response(), send_error() instead,

so what you should do is something like

class ListHandler(BaseHTTPServer.BaseHTTPRequestHandler):

def do_GET(self):
if (self.path) == '/Peter':
data = self.makeList()
self.send_response(200)
self.send_header('Content-Length', str(len(data)))
self.end_headers()
self.wfile.write(data)
....
else:
....
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top