Quick and Simple Python Web Server

 

If you’re ever in the need to get a quick web-server up and running, this one line python command will do wonders. Of course, launch it from the directory that your files are in.  Then you just need to go to your favorite browser and type localhost with your directory and voila!  A simple web server.

One Liner: python -m SimpleHTTPServer;

If you want to get more creative, and make it reusable simply alias it to create an easy to use test server: alias pyweb=”cd ~/webserver/; python -m SimpleHTTPServer;”  Put this command in your profile for quick and easy web server deployment for testing locally.

More Advanced Usage:

Sometimes you might need something just a little more advanced though.  I’ve found CherryPy to be a fairly straightforward Python web framework to get my test projects up and running quickly.  The code listed below will get you started serving up static html files with minimal code.  Of course, you’ll want to also include a default method to handle web scrapers and spiders, but I’ll leave that up to you.

full_page.py:

# Create a basic page to display content with cherrypy

import os.path
import cherrypy
from cherrypy.lib.static import serve_file

current_dir = os.path.dirname(os.path.abspath(__file__))

config = {'/' : {
 'tools.staticdir.on' : True,
 'tools.staticdir.dir' : current_dir+'/html/',
 'tools.staticdir.index' : 'index.html',
 }
}

class Root:
 """ Base class to handle incoming requests. """
 def index(self,name):
   return serve_file(os.path.join(current_dir, name))
 index.exposed = True

cherrypy.quickstart(Root(), '/',config=config)

Index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en">
<head>
  <title>Test Page</title>
</head>
  <body id="body">
    Welcome to your very first static web page delivered through CherryPy!
  </body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *

Are you a spammer? *