Welcome, guest | Sign In | My Account | Store | Cart

This is the simplest way I have found of sending information from a python program to a browser

Python, 22 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/env python
import socket, threading, time

def handle(s):
  print s
  print repr(s.recv(4096))
  html = "<html><body>"
  html += time.asctime()
  html += "</body></html>"
  
  s.send(html)
  s.close()
  
s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('', 8888));
s.listen(1);
while 1:
  t,_ = s.accept();
  threading.Thread(target = handle, args = (t,)).start()

#After running this, open a browser and go to http://localhost:8888/

3 comments

Kent Johnson 11 years, 3 months ago  # | flag

You should include a status line followed by a blank line to make a well-formed HTTP response, e.g.

html = "HTTP/1.0 200 OK\r\n\r\n<html><body>" 
etc.

The simplest way to serve files to a browser is just the command line

python -m SimpleHTTPServer 8888

which will serve the files in the current directory.

James Mills 11 years, 3 months ago  # | flag

Nice work on writing a complete program.

I do however feel the need to point out the various Web Application Frameworks available in Python as well as the standard wsgiref module (which is probably the simplest, most straight-forward and correct way to build a web application).

Your implementation is crude and incomplete and will not work in general.

Kaushik Ghose (author) 11 years, 3 months ago  # | flag

Hi James and Kent,

Yes, there are very nice frameworks for doing things like what rails does in Ruby.

I am, however, not aiming for a general http server.

What I am after is a simple way to have a browser based interface for interacting with a python program. I found the webapplication frameworks to be too heavy for this.

wsgiref I recently discovered and that seems to be the ticket as it comes standard.

Thanks!