{"id":1658,"date":"2015-02-07T14:19:41","date_gmt":"2015-02-07T22:19:41","guid":{"rendered":"http:\/\/joelinoff.com\/blog\/?p=1658"},"modified":"2015-05-30T15:21:13","modified_gmt":"2015-05-30T22:21:13","slug":"simple-python-web-server-to-demonstrate-getpost-handling","status":"publish","type":"post","link":"https:\/\/joelinoff.com\/blog\/?p=1658","title":{"rendered":"Simple python web server to demonstrate GET\/POST handling"},"content":{"rendered":"<p>This blog describes a simple open source (MIT licensed) web server that demonstrates how browser\/server interactions work for GET and POST requests using the python BaseHTTPServer package. It was updated to version 1.2 on 20-May-2015. This software is licensed under the term of the MIT license. Feel free to use it however you wish.<\/p>\n<p>Use it as a starting point to understand the package when creating your own custom web server for handling specific types of requests but recognize that it is not suitable for a production environment. To use it in such an environment you would, at the very least, want to add improve the error handling and add threading support. You would probably also want to add SSL\/TLS support.<br \/>\n<!--more--><\/p>\n<h2>Download<\/h2>\n<p>To use the simple web server download one of the archives and extract the files.<\/p>\n<div style=\"margin-left: 20px\">\n<table>\n<tbody>\n<tr>\n<th>Archive<\/th>\n<th>Checksum<\/th>\n<th>Description<\/th>\n<\/tr>\n<tr>\n<td><a href=\"http:\/\/projects.joelinoff.com\/webserver\/webserver-1.2.tar.bz2\">webserver.tar.bz2<\/a><\/td>\n<td align=\"right\">28050<\/td>\n<td>Bzip2 format.<\/td>\n<\/tr>\n<tr>\n<td><a href=\"http:\/\/projects.joelinoff.com\/webserver\/webserver-1.2.tar.gz\">webserver.tar.gz<\/td>\n<td align=\"right\">38095<\/td>\n<td>Gzip format.<\/td>\n<\/tr>\n<tr>\n<td><a href=\"http:\/\/projects.joelinoff.com\/webserver\/webserver-1.2.zip\">webserver.zip<\/a><\/td>\n<td align=\"right\">11861<\/td>\n<td>Zip format.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<p>The files in the archives are shown below.<\/p>\n<div style=\"margin-left: 20px\">\n<table>\n<tbody>\n<tr>\n<th>File<\/th>\n<th>Description<\/th>\n<\/tr>\n<tr>\n<td>webserver.css<\/td>\n<td>Sample CSS file referenced by webserver.html.<\/td>\n<\/tr>\n<tr>\n<td>webserver.html<\/td>\n<td>Sample HTML file.<\/td>\n<\/tr>\n<tr>\n<td>webserver.js<\/td>\n<td>Sample Javascript file referenced by webserver.html.<\/td>\n<\/tr>\n<tr>\n<td>webserver.png<\/td>\n<td>Sample PNG file referenced by webserver.html.<\/td>\n<\/tr>\n<tr>\n<td>webserver.py<\/td>\n<td>The web server program for python 2.7.<\/td>\n<\/tr>\n<tr>\n<td>webserver-start.sh<\/td>\n<td>Example script to start the web server.<\/td>\n<\/tr>\n<tr>\n<td>webserver-stop.sh<\/td>\n<td>Example script to stop the web server.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<p>The example below shows how to download and install using the zip archive.<\/p>\n<pre class=\"theme:vs2012-black font-size:14 line-height:17 lang:bash decode:true\">\r\n$ mkdir -p ~\/tmp\/webserver\r\n$ cd ~\/tmp\/webserver\r\n$ wget http:\/\/projects.joelinoff.com\/webserver\/webserver-1.2.zip  # download\r\n$ unzip webserver.zip                                             # extract\r\n$ chmod a+x webserver.py                                          # make it executable\r\n$ ls -1\r\nwebserver-start.sh\r\nwebserver-stop.sh\r\nwebserver.css\r\nwebserver.html\r\nwebserver.js\r\nwebserver.png\r\nwebserver.py*\r\n<\/pre>\n<div style=\"margin-left: 20px; margin-right: 20px; padding: 5px; background: #ffffdb;\">\n<b>NOTE:<\/b> You may have to change the first line of the source file to correctly reference your installed version of python.\n<\/div>\n<h2>Running the Server<\/h2>\n<p>After you download the server, you simply run it by typing &#8220;<code>.\/webserver.py<\/code>&#8221; or &#8220;<code>python2.7 .\/webserver.py<\/code>&#8220;. That will start the server on your local host using port 8080. If that port is already in use, then use the -p option to specify another port like this &#8220;<code>.\/webserver.py -p 9000<\/code>&#8220;. Do not try to use port 80. It will interfere with the normal operation of your system.<\/p>\n<pre class=\"theme:vs2012-black font-size:14 line-height:17 lang:bash decode:true\">\r\n$ .\/myserver.py\r\n<\/pre>\n<p>As the simple web server runs, it will print out informational messages as it is running to show you what is happening.<\/p>\n<p>This is the list of options available from the server.<\/p>\n<div style=\"margin-left: 20px\">\n<table>\n<tbody>\n<tr>\n<th>File<\/th>\n<th>Description<\/th>\n<\/tr>\n<tr>\n<td>-d <em>DIR<\/em>, &#8211;daemonize <em>DIR<\/em><\/td>\n<td>Daemonize this process, store the 3 run files (.log, .err, .pid) in DIR (default &#8220;.&#8221;). Version 1.2 or later.<\/td>\n<\/tr>\n<tr>\n<td>-h, &#8211;help<\/td>\n<td>Help message.<\/td>\n<\/tr>\n<tr>\n<td>-H <em>host<\/em>, &#8211;host <em>host<\/em><\/td>\n<td>The hostname (e.g. localhost).<\/td>\n<\/tr>\n<tr>\n<td>-l <em>LEVEL<\/em>, &#8211;level <em>LEVEL<\/em><\/td>\n<td>Logging level: noset, debug, info, warning, error, critical. Version 1.2 or later.<\/td>\n<\/tr>\n<tr>\n<td>&#8211;no-dirlist<\/td>\n<td>Disable directory listings. Version 1.2 or later.<\/td>\n<\/tr>\n<tr>\n<td>-p <em>port<\/em>, &#8211;port <em>port<\/em><\/td>\n<td>The port (e.g. 8080).<\/td>\n<\/tr>\n<tr>\n<td>-r <em>dir<\/em>, &#8211;rootdir <em>dir<\/em><\/td>\n<td>The web files root directory.<\/td>\n<\/tr>\n<tr>\n<td>-v, &#8211;verbosity<\/td>\n<td>Increase verbosity. Not used.<\/td>\n<\/tr>\n<tr>\n<td>-V, &#8211;version<\/td>\n<td>Print the version number and exit.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<h2>Accessing the Server<\/h2>\n<p>Now that the server is running you can access the webserver.html page by entering the following URL: <code>http:\/\/127.0.0.1\/webserver.html<\/code> (you can also use 0.0.0.0 if that is easier to type). If server is running properly you will see something like this:<\/p>\n<p><a href=\"http:\/\/joelinoff.com\/blog\/wp-content\/uploads\/2015\/02\/Screen-Shot-2015-02-07-at-1.36.40-PM.png\"><img loading=\"lazy\" src=\"http:\/\/joelinoff.com\/blog\/wp-content\/uploads\/2015\/02\/Screen-Shot-2015-02-07-at-1.36.40-PM.png\" alt=\"Screen Shot 2015-02-07 at 1.36.40 PM\" width=\"947\" height=\"730\" class=\"alignnone size-full wp-image-1647\" srcset=\"https:\/\/joelinoff.com\/blog\/wp-content\/uploads\/2015\/02\/Screen-Shot-2015-02-07-at-1.36.40-PM.png 947w, https:\/\/joelinoff.com\/blog\/wp-content\/uploads\/2015\/02\/Screen-Shot-2015-02-07-at-1.36.40-PM-300x231.png 300w, https:\/\/joelinoff.com\/blog\/wp-content\/uploads\/2015\/02\/Screen-Shot-2015-02-07-at-1.36.40-PM-624x481.png 624w\" sizes=\"(max-width: 947px) 100vw, 947px\" \/><\/a><\/p>\n<p>If you enter data in the &#8220;Form Using GET&#8221; fieldset, the argument values will appear in the webserver output log. If you enter data in the &#8220;Form Using POST&#8221; fieldset, the argument values will in the webserver output log and on a new page. In both case, you inspect the source code to see how the form data was captured and processed from the browser request.<\/p>\n<p>Now try entering &#8220;<code>http:\/\/127.0.0.1:8080\/info<\/code>&#8221; and you will see internal server information. This shows, in a crude way, how you can enter custom URLs.<\/p>\n<p><a href=\"http:\/\/joelinoff.com\/blog\/wp-content\/uploads\/2015\/02\/Screen-Shot-2015-02-09-at-7.06.09-AM.png\"><img loading=\"lazy\" src=\"http:\/\/joelinoff.com\/blog\/wp-content\/uploads\/2015\/02\/Screen-Shot-2015-02-09-at-7.06.09-AM.png\" alt=\"Screen Shot 2015-02-09 at 7.06.09 AM\" width=\"860\" height=\"639\" class=\"alignnone size-full wp-image-1668\" srcset=\"https:\/\/joelinoff.com\/blog\/wp-content\/uploads\/2015\/02\/Screen-Shot-2015-02-09-at-7.06.09-AM.png 860w, https:\/\/joelinoff.com\/blog\/wp-content\/uploads\/2015\/02\/Screen-Shot-2015-02-09-at-7.06.09-AM-300x223.png 300w, https:\/\/joelinoff.com\/blog\/wp-content\/uploads\/2015\/02\/Screen-Shot-2015-02-09-at-7.06.09-AM-624x464.png 624w\" sizes=\"(max-width: 860px) 100vw, 860px\" \/><\/a><\/p>\n<p>At this point you have verified that the simple web server is working. If you want to go further, you try creating your own HTML or javascript files.<\/p>\n<h2>Implementation Discussion<\/h2>\n<p>This implementation uses the BaseHTTPServer and cgi packages for creating the server and processing browser requests. It uses argparse to manage the command lines arguments. There are a number of interesting features of this example.<\/p>\n<p>The first is the use of the class factory <code>make_request_handler_class<\/code> to allow the request object to have access to the command line options, specifically the root directory for accessing files to display for GET requests. You could add any arbitrary class arguments this way. For example you add the content headers for handling different file extensions which in the current implementation are in the do_GET() handler method.<\/p>\n<p>Another interesting feature is setting the content type based on the file extension.<\/p>\n<p>Yet another interesting feature is that the POST request handler redirects to a custom page with a back button. This is simply to demonstrate that it can be done. <\/p>\n<p>The source code for webserver.py is presented in full below for interactive reference but it probably makes more sense to download it so that you can search through it in your favorite editor.<\/p>\n<pre class=\"theme:vs2012-black font-size:12 line-height:17 lang:python decode:true\">\r\n#!\/usr\/bin\/env python2.7\r\n# -*- coding: utf-8 -*-\r\n'''\r\nSimple web server that demonstrates how browser\/server interactions\r\nwork for GET and POST requests. Use it as a starting point to create a\r\ncustom web server for handling specific requests but don't try to use\r\nit for any production work.\r\n\r\nYou start by creating a simple index.html file in web directory\r\nsomewhere like you home directory: ~\/www.\r\n\r\nYou then add an HTML file: ~\/www\/index.html. It can be very\r\nsimple. Something like this will do nicely:\r\n\r\n   <!DOCTYPE html>\r\n   <html>\r\n     <head>\r\n       <meta charset=\"utf-8\">\r\n       <title>WebServer Test<\/title>\r\n     <\/head>\r\n     <body>\r\n       <p>Hello, world!<\/p>\r\n     <\/body>\r\n   <\/html>\r\n\r\nAt this point you have a basic web infrastructure with a single file\r\nso you start the server and point to the ~\/www root directory:\r\n\r\n   $ webserver.py -r ~\/www\r\n\r\nThis will start the web server listening on your localhost on port\r\n8080. You can change both the host name and the port using the --host\r\nand --port options. See the on-line help for more information (-h,\r\n--help).\r\n\r\nIf you do not specify a root directory, it will use the directory that\r\nyou started the server from.\r\n\r\nNow go to your browser and enter http:\/\/0.0.0.0:8080 on the command\r\nline and you will see your page.\r\n\r\nTry entering http:\/\/0.0.0.0:8080\/info to see some server information.\r\n\r\nYou can also use http:\/\/127.0.0.1.\r\n\r\nBy default the server allows you to see directory listings if there is\r\nno index.html or index.htm file. You can disable this by specifying\r\nthe --no-dirlist option.\r\n\r\nIf you want to see a directory listing of a directory that contains a\r\nindex.html or index.htm directory, type three trailing backslashes in\r\nthe URL like this: http:\/\/foo\/bar\/spam\/\/\/. This will not work if the\r\n--no-dirlist option is specified.\r\n\r\nThe default logging level is \"info\". You can change it using the\r\n\"--level\" option.\r\n\r\nThe example below shows how to use a number of the switches to run a\r\nserver for host foobar on port 8080 with no directory listing\r\ncapability and very little output serving files from ~\/www:\r\n\r\n  $ hostname\r\n  foobar\r\n  $ webserver --host foobar --port 8080 --level warning --no-dirlist --rootdir ~\/www\r\n\r\nTo daemonize a process, specify the -d or --daemonize option with a\r\nprocess directory. That directory will contain the log (stdout), err\r\n(stderr) and pid (process id) files for the daemon process. Here is an\r\nexample:\r\n\r\n  $ hostname\r\n  foobar\r\n  $ webserver --host foobar --port 8080 --level warning --no-dirlist --rootdir ~\/www --daemonize ~\/www\/logs\r\n  $ ls ~\/www\/logs\r\n  webserver-foobar-8080.err webserver-foobar-8080.log webserver-foobar-8080.pid\r\n'''\r\n\r\n# LICENSE\r\n#   Copyright (c) 2015 Joe Linoff\r\n#   \r\n#   Permission is hereby granted, free of charge, to any person obtaining a copy\r\n#   of this software and associated documentation files (the \"Software\"), to deal\r\n#   in the Software without restriction, including without limitation the rights\r\n#   to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n#   copies of the Software, and to permit persons to whom the Software is\r\n#   furnished to do so, subject to the following conditions:\r\n#   \r\n#   The above copyright notice and this permission notice shall be included in\r\n#   all copies or substantial portions of the Software.\r\n#   \r\n#   THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n#   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n#   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n#   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n#   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n#   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n#   THE SOFTWARE.\r\n\r\n# VERSIONS\r\n#   1.0  initial release\r\n#   1.1  replace req with self in request handler, add favicon\r\n#   1.2  added directory listings, added --no-dirlist, fixed plain text displays, logging level control, daemonize\r\nVERSION = '1.2'\r\n\r\nimport argparse\r\nimport BaseHTTPServer\r\nimport cgi\r\nimport logging\r\nimport os\r\nimport sys\r\n\r\n\r\ndef make_request_handler_class(opts):\r\n    '''\r\n    Factory to make the request handler and add arguments to it.\r\n\r\n    It exists to allow the handler to access the opts.path variable\r\n    locally.\r\n    '''\r\n    class MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\r\n        '''\r\n        Factory generated request handler class that contain\r\n        additional class variables.\r\n        '''\r\n        m_opts = opts\r\n\r\n        def do_HEAD(self):\r\n            '''\r\n            Handle a HEAD request.\r\n            '''\r\n            logging.debug('HEADER %s' % (self.path))\r\n            self.send_response(200)\r\n            self.send_header('Content-type', 'text\/html')\r\n            self.end_headers()\r\n\r\n        def info(self):\r\n            '''\r\n            Display some useful server information.\r\n\r\n            http:\/\/127.0.0.1:8080\/info\r\n            '''\r\n            self.wfile.write('<html>')\r\n            self.wfile.write('  <head>')\r\n            self.wfile.write('    <title>Server Info<\/title>')\r\n            self.wfile.write('  <\/head>')\r\n            self.wfile.write('  <body>')\r\n            self.wfile.write('    <table>')\r\n            self.wfile.write('      <tbody>')\r\n            self.wfile.write('        <tr>')\r\n            self.wfile.write('          <td>client_address<\/td>')\r\n            self.wfile.write('          <td>%r<\/td>' % (repr(self.client_address)))\r\n            self.wfile.write('        <\/tr>')\r\n            self.wfile.write('        <tr>')\r\n            self.wfile.write('          <td>command<\/td>')\r\n            self.wfile.write('          <td>%r<\/td>' % (repr(self.command)))\r\n            self.wfile.write('        <\/tr>')\r\n            self.wfile.write('        <tr>')\r\n            self.wfile.write('          <td>headers<\/td>')\r\n            self.wfile.write('          <td>%r<\/td>' % (repr(self.headers)))\r\n            self.wfile.write('        <\/tr>')\r\n            self.wfile.write('        <tr>')\r\n            self.wfile.write('          <td>path<\/td>')\r\n            self.wfile.write('          <td>%r<\/td>' % (repr(self.path)))\r\n            self.wfile.write('        <\/tr>')\r\n            self.wfile.write('        <tr>')\r\n            self.wfile.write('          <td>server_version<\/td>')\r\n            self.wfile.write('          <td>%r<\/td>' % (repr(self.server_version)))\r\n            self.wfile.write('        <\/tr>')\r\n            self.wfile.write('        <tr>')\r\n            self.wfile.write('          <td>sys_version<\/td>')\r\n            self.wfile.write('          <td>%r<\/td>' % (repr(self.sys_version)))\r\n            self.wfile.write('        <\/tr>')\r\n            self.wfile.write('      <\/tbody>')\r\n            self.wfile.write('    <\/table>')\r\n            self.wfile.write('  <\/body>')\r\n            self.wfile.write('<\/html>')\r\n\r\n        def do_GET(self):\r\n            '''\r\n            Handle a GET request.\r\n            '''\r\n            logging.debug('GET %s' % (self.path))\r\n\r\n            # Parse out the arguments.\r\n            # The arguments follow a '?' in the URL. Here is an example:\r\n            #   http:\/\/example.com?arg1=val1\r\n            args = {}\r\n            idx = self.path.find('?')\r\n            if idx >= 0:\r\n                rpath = self.path[:idx]\r\n                args = cgi.parse_qs(self.path[idx+1:])\r\n            else:\r\n                rpath = self.path\r\n\r\n            # Print out logging information about the path and args.\r\n            if 'content-type' in self.headers:\r\n                ctype, _ = cgi.parse_header(self.headers['content-type'])\r\n                logging.debug('TYPE %s' % (ctype))\r\n\r\n            logging.debug('PATH %s' % (rpath))\r\n            logging.debug('ARGS %d' % (len(args)))\r\n            if len(args):\r\n                i = 0\r\n                for key in sorted(args):\r\n                    logging.debug('ARG[%d] %s=%s' % (i, key, args[key]))\r\n                    i += 1\r\n\r\n            # Check to see whether the file is stored locally,\r\n            # if it is, display it.\r\n            # There is special handling for http:\/\/127.0.0.1\/info. That URL\r\n            # displays some internal information.\r\n            if self.path == '\/info' or self.path == '\/info\/':\r\n                self.send_response(200)  # OK\r\n                self.send_header('Content-type', 'text\/html')\r\n                self.end_headers()\r\n                self.info()\r\n            else:\r\n                # Get the file path.\r\n                path = MyRequestHandler.m_opts.rootdir + rpath\r\n                dirpath = None\r\n                logging.debug('FILE %s' % (path))\r\n\r\n                # If it is a directory look for index.html\r\n                # or process it directly if there are 3\r\n                # trailing slashed.\r\n                if rpath[-3:] == '\/\/\/':\r\n                    dirpath = path\r\n                elif os.path.exists(path) and os.path.isdir(path):\r\n                    dirpath = path  # the directory portion\r\n                    index_files = ['\/index.html', '\/index.htm', ]\r\n                    for index_file in index_files:\r\n                        tmppath = path + index_file\r\n                        if os.path.exists(tmppath):\r\n                            path = tmppath\r\n                            break\r\n\r\n                # Allow the user to type \"\/\/\/\" at the end to see the\r\n                # directory listing.\r\n                if os.path.exists(path) and os.path.isfile(path):\r\n                    # This is valid file, send it as the response\r\n                    # after determining whether it is a type that\r\n                    # the server recognizes.\r\n                    _, ext = os.path.splitext(path)\r\n                    ext = ext.lower()\r\n                    content_type = {\r\n                        '.css': 'text\/css',\r\n                        '.gif': 'image\/gif',\r\n                        '.htm': 'text\/html',\r\n                        '.html': 'text\/html',\r\n                        '.jpeg': 'image\/jpeg',\r\n                        '.jpg': 'image\/jpg',\r\n                        '.js': 'text\/javascript',\r\n                        '.png': 'image\/png',\r\n                        '.text': 'text\/plain',\r\n                        '.txt': 'text\/plain',\r\n                    }\r\n\r\n                    # If it is a known extension, set the correct\r\n                    # content type in the response.\r\n                    if ext in content_type:\r\n                        self.send_response(200)  # OK\r\n                        self.send_header('Content-type', content_type[ext])\r\n                        self.end_headers()\r\n\r\n                        with open(path) as ifp:\r\n                            self.wfile.write(ifp.read())\r\n                    else:\r\n                        # Unknown file type or a directory.\r\n                        # Treat it as plain text.\r\n                        self.send_response(200)  # OK\r\n                        self.send_header('Content-type', 'text\/plain')\r\n                        self.end_headers()\r\n\r\n                        with open(path) as ifp:\r\n                            self.wfile.write(ifp.read())\r\n                else:\r\n                    if dirpath is None or self.m_opts.no_dirlist == True:\r\n                        # Invalid file path, respond with a server access error\r\n                        self.send_response(500)  # generic server error for now\r\n                        self.send_header('Content-type', 'text\/html')\r\n                        self.end_headers()\r\n\r\n                        self.wfile.write('<html>')\r\n                        self.wfile.write('  <head>')\r\n                        self.wfile.write('    <title>Server Access Error<\/title>')\r\n                        self.wfile.write('  <\/head>')\r\n                        self.wfile.write('  <body>')\r\n                        self.wfile.write('    <p>Server access error.<\/p>')\r\n                        self.wfile.write('    <p>%r<\/p>' % (repr(self.path)))\r\n                        self.wfile.write('    <p><a href=\"%s\">Back<\/a><\/p>' % (rpath))\r\n                        self.wfile.write('  <\/body>')\r\n                        self.wfile.write('<\/html>')\r\n                    else:\r\n                        # List the directory contents. Allow simple navigation.\r\n                        logging.debug('DIR %s' % (dirpath))\r\n\r\n                        self.send_response(200)  # OK\r\n                        self.send_header('Content-type', 'text\/html')\r\n                        self.end_headers()\r\n                        \r\n                        self.wfile.write('<html>')\r\n                        self.wfile.write('  <head>')\r\n                        self.wfile.write('    <title>%s<\/title>' % (dirpath))\r\n                        self.wfile.write('  <\/head>')\r\n                        self.wfile.write('  <body>')\r\n                        self.wfile.write('    <a href=\"%s\">Home<\/a><br>' % ('\/'));\r\n\r\n                        # Make the directory path navigable.\r\n                        dirstr = ''\r\n                        href = None\r\n                        for seg in rpath.split('\/'):\r\n                            if href is None:\r\n                                href = seg\r\n                            else:\r\n                                href = href + '\/' + seg\r\n                                dirstr += '\/'\r\n                            dirstr += '<a href=\"%s\">%s<\/a>' % (href, seg)\r\n                        self.wfile.write('    <p>Directory: %s<\/p>' % (dirstr))\r\n\r\n                        # Write out the simple directory list (name and size).\r\n                        self.wfile.write('    <table border=\"0\">')\r\n                        self.wfile.write('      <tbody>')\r\n                        fnames = ['..']\r\n                        fnames.extend(sorted(os.listdir(dirpath), key=str.lower))\r\n                        for fname in fnames:\r\n                            self.wfile.write('        <tr>')\r\n                            self.wfile.write('          <td align=\"left\">')\r\n                            path = rpath + '\/' + fname\r\n                            fpath = os.path.join(dirpath, fname)\r\n                            if os.path.isdir(path):\r\n                                self.wfile.write('            <a href=\"%s\">%s\/<\/a>' % (path, fname))\r\n                            else:\r\n                                self.wfile.write('            <a href=\"%s\">%s<\/a>' % (path, fname))\r\n                            self.wfile.write('          <td>&nbsp;&nbsp;<\/td>')\r\n                            self.wfile.write('          <\/td>')\r\n                            self.wfile.write('          <td align=\"right\">%d<\/td>' % (os.path.getsize(fpath)))\r\n                            self.wfile.write('        <\/tr>')\r\n                        self.wfile.write('      <\/tbody>')\r\n                        self.wfile.write('    <\/table>')\r\n                        self.wfile.write('  <\/body>')\r\n                        self.wfile.write('<\/html>')\r\n\r\n        def do_POST(self):\r\n            '''\r\n            Handle POST requests.\r\n            '''\r\n            logging.debug('POST %s' % (self.path))\r\n\r\n            # CITATION: http:\/\/stackoverflow.com\/questions\/4233218\/python-basehttprequesthandler-post-variables\r\n            ctype, pdict = cgi.parse_header(self.headers['content-type'])\r\n            if ctype == 'multipart\/form-data':\r\n                postvars = cgi.parse_multipart(self.rfile, pdict)\r\n            elif ctype == 'application\/x-www-form-urlencoded':\r\n                length = int(self.headers['content-length'])\r\n                postvars = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1)\r\n            else:\r\n                postvars = {}\r\n\r\n            # Get the \"Back\" link.\r\n            back = self.path if self.path.find('?') < 0 else self.path[:self.path.find('?')]\r\n\r\n            # Print out logging information about the path and args.\r\n            logging.debug('TYPE %s' % (ctype))\r\n            logging.debug('PATH %s' % (self.path))\r\n            logging.debug('ARGS %d' % (len(postvars)))\r\n            if len(postvars):\r\n                i = 0\r\n                for key in sorted(postvars):\r\n                    logging.debug('ARG[%d] %s=%s' % (i, key, postvars[key]))\r\n                    i += 1\r\n\r\n            # Tell the browser everything is okay and that there is\r\n            # HTML to display.\r\n            self.send_response(200)  # OK\r\n            self.send_header('Content-type', 'text\/html')\r\n            self.end_headers()\r\n\r\n            # Display the POST variables.\r\n            self.wfile.write('<html>')\r\n            self.wfile.write('  <head>')\r\n            self.wfile.write('    <title>Server POST Response<\/title>')\r\n            self.wfile.write('  <\/head>')\r\n            self.wfile.write('  <body>')\r\n            self.wfile.write('    <p>POST variables (%d).<\/p>' % (len(postvars)))\r\n\r\n            if len(postvars):\r\n                # Write out the POST variables in 3 columns.\r\n                self.wfile.write('    <table>')\r\n                self.wfile.write('      <tbody>')\r\n                i = 0\r\n                for key in sorted(postvars):\r\n                    i += 1\r\n                    val = postvars[key]\r\n                    self.wfile.write('        <tr>')\r\n                    self.wfile.write('          <td align=\"right\">%d<\/td>' % (i))\r\n                    self.wfile.write('          <td align=\"right\">%s<\/td>' % key)\r\n                    self.wfile.write('          <td align=\"left\">%s<\/td>' % val)\r\n                    self.wfile.write('        <\/tr>')\r\n                self.wfile.write('      <\/tbody>')\r\n                self.wfile.write('    <\/table>')\r\n\r\n            self.wfile.write('    <p><a href=\"%s\">Back<\/a><\/p>' % (back))\r\n            self.wfile.write('  <\/body>')\r\n            self.wfile.write('<\/html>')\r\n\r\n    return MyRequestHandler\r\n\r\n\r\ndef err(msg):\r\n    '''\r\n    Report an error message and exit.\r\n    '''\r\n    print('ERROR: %s' % (msg))\r\n    sys.exit(1)\r\n\r\n\r\ndef getopts():\r\n    '''\r\n    Get the command line options.\r\n    '''\r\n\r\n    # Get the help from the module documentation.\r\n    this = os.path.basename(sys.argv[0])\r\n    description = ('description:%s' % '\\n  '.join(__doc__.split('\\n')))\r\n    epilog = ' '\r\n    rawd = argparse.RawDescriptionHelpFormatter\r\n    parser = argparse.ArgumentParser(formatter_class=rawd,\r\n                                     description=description,\r\n                                     epilog=epilog)\r\n\r\n    parser.add_argument('-d', '--daemonize',\r\n                        action='store',\r\n                        type=str,\r\n                        default='.',\r\n                        metavar='DIR',\r\n                        help='daemonize this process, store the 3 run files (.log, .err, .pid) in DIR (default \"%(default)s\")')\r\n\r\n    parser.add_argument('-H', '--host',\r\n                        action='store',\r\n                        type=str,\r\n                        default='localhost',\r\n                        help='hostname, default=%(default)s')\r\n\r\n    parser.add_argument('-l', '--level',\r\n                        action='store',\r\n                        type=str,\r\n                        default='info',\r\n                        choices=['notset', 'debug', 'info', 'warning', 'error', 'critical',],\r\n                        help='define the logging level, the default is %(default)s')\r\n\r\n    parser.add_argument('--no-dirlist',\r\n                        action='store_true',\r\n                        help='disable directory listings')\r\n\r\n    parser.add_argument('-p', '--port',\r\n                        action='store',\r\n                        type=int,\r\n                        default=8080,\r\n                        help='port, default=%(default)s')\r\n\r\n    parser.add_argument('-r', '--rootdir',\r\n                        action='store',\r\n                        type=str,\r\n                        default=os.path.abspath('.'),\r\n                        help='web directory root that contains the HTML\/CSS\/JS files %(default)s')\r\n\r\n    parser.add_argument('-v', '--verbose',\r\n                        action='count',\r\n                        help='level of verbosity')\r\n\r\n    parser.add_argument('-V', '--version',\r\n                        action='version',\r\n                        version='%(prog)s - v' + VERSION)\r\n\r\n    opts = parser.parse_args()\r\n    opts.rootdir = os.path.abspath(opts.rootdir)\r\n    if not os.path.isdir(opts.rootdir):\r\n        err('Root directory does not exist: ' + opts.rootdir)\r\n    if opts.port < 1 or opts.port > 65535:\r\n        err('Port is out of range [1..65535]: %d' % (opts.port))\r\n    return opts\r\n\r\n\r\ndef httpd(opts):\r\n    '''\r\n    HTTP server\r\n    '''\r\n    RequestHandlerClass = make_request_handler_class(opts)\r\n    server = BaseHTTPServer.HTTPServer((opts.host, opts.port), RequestHandlerClass)\r\n    logging.info('Server starting %s:%s (level=%s)' % (opts.host, opts.port, opts.level))\r\n    try:\r\n        server.serve_forever()\r\n    except KeyboardInterrupt:\r\n        pass\r\n    server.server_close()\r\n    logging.info('Server stopping %s:%s' % (opts.host, opts.port))\r\n\r\n\r\ndef get_logging_level(opts):\r\n    '''\r\n    Get the logging levels specified on the command line.\r\n    The level can only be set once.\r\n    '''\r\n    if opts.level == 'notset':\r\n        return logging.NOTSET\r\n    elif opts.level == 'debug':\r\n        return logging.DEBUG\r\n    elif opts.level == 'info':\r\n        return logging.INFO\r\n    elif opts.level == 'warning':\r\n        return logging.WARNING\r\n    elif opts.level == 'error':\r\n        return logging.ERROR\r\n    elif opts.level == 'critical':\r\n        return logging.CRITICAL\r\n\r\n\r\ndef daemonize(opts):\r\n    '''\r\n    Daemonize this process.\r\n\r\n    CITATION: http:\/\/stackoverflow.com\/questions\/115974\/what-would-be-the-simplest-way-to-daemonize-a-python-script-in-linux\r\n    '''\r\n    if os.path.exists(opts.daemonize) is False:\r\n        err('directory does not exist: ' + opts.daemonize)\r\n\r\n    if os.path.isdir(opts.daemonize) is False:\r\n        err('not a directory: ' + opts.daemonize)\r\n\r\n    bname = 'webserver-%s-%d' % (opts.host, opts.port)\r\n    outfile = os.path.abspath(os.path.join(opts.daemonize, bname + '.log'))\r\n    errfile = os.path.abspath(os.path.join(opts.daemonize, bname + '.err'))\r\n    pidfile = os.path.abspath(os.path.join(opts.daemonize, bname + '.pid'))\r\n\r\n    if os.path.exists(pidfile):\r\n        err('pid file exists, cannot continue: ' + pidfile)\r\n    if os.path.exists(outfile):\r\n        os.unlink(outfile)\r\n    if os.path.exists(errfile):\r\n        os.unlink(errfile)\r\n\r\n    if os.fork():\r\n        sys.exit(0)  # exit the parent\r\n\r\n    os.umask(0)\r\n    os.setsid()\r\n    if os.fork():\r\n        sys.exit(0)  # exit the parent\r\n\r\n    print('daemon pid %d' % (os.getpid()))\r\n\r\n    sys.stdout.flush()\r\n    sys.stderr.flush()\r\n\r\n    stdin = file('\/dev\/null', 'r')\r\n    stdout = file(outfile, 'a+')\r\n    stderr = file(errfile, 'a+', 0)\r\n\r\n    os.dup2(stdin.fileno(), sys.stdin.fileno())\r\n    os.dup2(stdout.fileno(), sys.stdout.fileno())\r\n    os.dup2(stderr.fileno(), sys.stderr.fileno())\r\n\r\n    with open(pidfile, 'w') as ofp:\r\n        ofp.write('%i' % (os.getpid()))\r\n\r\n\r\ndef main():\r\n    ''' main entry '''\r\n    opts = getopts()\r\n    if opts.daemonize:\r\n        daemonize(opts)\r\n    logging.basicConfig(format='%(asctime)s [%(levelname)s] %(message)s', level=get_logging_level(opts))\r\n    httpd(opts)\r\n\r\n\r\nif __name__ == '__main__':\r\n    main()  # this allows library functionality\r\n<\/pre>\n<p>Enjoy!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>This blog describes a simple open source (MIT licensed) web server that demonstrates how browser\/server interactions work for GET and POST requests using the python BaseHTTPServer package. It was updated to version 1.2 on 20-May-2015. This software is licensed under the term of the MIT license. Feel free to use it however you wish. Use &hellip; <a href=\"https:\/\/joelinoff.com\/blog\/?p=1658\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Simple python web server to demonstrate GET\/POST handling<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0},"categories":[5,7,39],"tags":[],"_links":{"self":[{"href":"https:\/\/joelinoff.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1658"}],"collection":[{"href":"https:\/\/joelinoff.com\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/joelinoff.com\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/joelinoff.com\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/joelinoff.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1658"}],"version-history":[{"count":19,"href":"https:\/\/joelinoff.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1658\/revisions"}],"predecessor-version":[{"id":1707,"href":"https:\/\/joelinoff.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1658\/revisions\/1707"}],"wp:attachment":[{"href":"https:\/\/joelinoff.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1658"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/joelinoff.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1658"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/joelinoff.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1658"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}