Hello all,
Long time reader, first time poster here. I've been a web programmer for some time now but really never got into any scripting languages, I guess you could say I was just a web designer. Either way I want to write a little web server in Python to just serve up some pages to get to know more about the language. I've decided I want to write for GET, HEAD, OPTIONS(cause it would be good to know how to put that kind of feature in) and TRACE...no POST yet because it appears to be more difficult.

I started with a tutorial that taught me:

import socket
host = ''
port = XXXX

c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

c.bind((host, port))

c.listen(1)

while 1: 
	csock, caddr = c.accept() 
	cfile = csock.makefile('rw', 0)
	line = cfile.readline().strip() 

cfile.write('HTTP/1.0 200 OK\n\n') 
cfile.write('<html><head><title>Welcome %s!</title></head><body>The Server Is Working!!!</body></html>') 
cfile.close() 
csock.close()

Then the only problem was that's not serving an actual HTML file just a variable written to the screen. So then I got to this:

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

class RequestHandler(BaseHTTPRequestHandler):
    def _writeheaders(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_HEAD(self):
        self._writeheaders()

    def do_GET(self):
        self._writeheaders()
        self.wfile.write("""
		<HTML>
		<HEAD>
		<TITLE>Test Page</TITLE>
		</HEAD>
		<BODY>Test!!!
		</BODY>
		</HTML>
		""")

serveraddr = ('', XXXX)
srvr = HTTPServer(serveraddr, RequestHandler)
 
print("Server online and active")
 
srvr.serve_forever()

But again, I can't seem to understand how to serve out the *.html files themselves.


Reader's Digest version: How do I use any of my code, or some other code you can provide, to add in the ability to serve the index.html file that's in my folder with the server.

Thanks!
-Ray-

The problem with your first code (using socket) is that the actual section doing the writing isn't doing any output as that part isn't in the while loop:

import socket
host = ''
port = 8080

c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

c.bind((host, port))

c.listen(1)

while 1: 
	csock, caddr = c.accept() 
	cfile = csock.makefile('rw', 0)
	line = cfile.readline().strip() 

	cfile.write('HTTP/1.0 200 OK\n\n') 
	cfile.write('<html><head><title>Welcome %s!</title></head><body>The Server Is Working!!!</body></html>') 
	cfile.close() 
	csock.close()

That should work :)

Now for the second one:
That should work, once you replace the Xs with an actual port...but to add page support to it you could do this:

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

sitedir = "." #could set to /var/www if your normal site is there, etc.

class RequestHandler(BaseHTTPRequestHandler):
	def _writeheaders(self):
		self.send_response(200)
		self.send_header('Content-type', 'text/html')
		self.end_headers()

	def do_HEAD(self):
		self._writeheaders()

	def do_GET(self):
		self._writeheaders()
		
		if self.path == "/":
			self.path = "index.html"
		
		try:
			f = open(sitedir + self.path)
			self.wfile.write(f.read())
			f.close()
		except IOError, e: # probably means we tried fetching a directory
			self.wfile.write("Couldn't find file")
			print e

serveraddr = ('', 8080)
srvr = HTTPServer(serveraddr, RequestHandler)
 
print("Server online and active")
 
srvr.serve_forever()

All you needed was to open self.path (the user requested path for the request) and send it back. Note that this server won't protect you from things like if someone were to request "http://localhost/../../etc/passwd"

Good luck!
- Joe

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.