Posted By

ronaklovespython on 12/03/13


Tagged

server python web


Versions (?)

Python Web Server


 / Published in: Python
 

URL: http://www.snipplr.com/view/57745/python-web-server/

Code for single threaded python web server

  1. # Import statements
  2.  
  3. from BaseHTTPServer import HTTPServer
  4. from BaseHTTPServer import BaseHTTPRequestHandler
  5. from socket import gethostname, gethostbyname
  6. import re
  7. import os
  8. import csv
  9. import time
  10.  
  11. # Config values
  12.  
  13. HTMLFILE1 = 'error.html'
  14. RESULTS_REPLACESTR = 'Results Here' # String to replace to show results
  15.  
  16. # LISTEN PORT
  17.  
  18. LISTENPORT=8800
  19.  
  20. class GetHandler(BaseHTTPRequestHandler):
  21.  
  22. menuhtml = ''
  23.  
  24. # Let's add some color
  25. def color(self, t, c):
  26. return chr(0x1b)+"["+str(c)+"m"+t+chr(0x1b)+"[0m"
  27. def bold(self, t):
  28. return self.color(t,1)
  29. def green(self, t):
  30. return self.color(t, 32)
  31. def red(self, t):
  32. return self.color(t, 31)
  33.  
  34. def display(self, find_code):
  35.  
  36. ifile = open('complete_error_codes.csv', "rb")
  37. reader = csv.reader(ifile)
  38.  
  39. rownum = 0
  40. results = ''
  41. for row in reader:
  42. if 'Class' in row:
  43. list1 = row
  44. elif find_code in row:
  45. list2 = row
  46. break
  47. # if rownum == 0:
  48. # header = row
  49. # else:
  50. # column = 0
  51. # if row[1] == str(code):
  52. # results = dict(zip(header, row))
  53. # print results
  54. # rownum += 1
  55. for key, value in zip(list1, list2):
  56. print '%s: %s' % ((self.red(key)), value)
  57. ifile.close()
  58. return results
  59.  
  60.  
  61. def getMenu(self):
  62.  
  63. fin = open(HTMLFILE1, 'r')
  64. menuhtml = fin.read()
  65. fin.close()
  66.  
  67. return menuhtml
  68.  
  69. def do_GET(self):
  70.  
  71. print 'Processing request: %s' % self.path
  72. page = self.getMenu()
  73. A = re.sub("", "", self.path)
  74. print ("%s" % A)
  75. A = A.strip("/?")
  76. nv = A.split("&")
  77. print nv
  78. code = nv[0]
  79. code = code.strip("code=")
  80. results = self.display(code)
  81. results = str(results)
  82. results = results.strip("{")
  83. results = results.strip("}")
  84. results = re.sub(",","\n", results)
  85. page = page.replace(RESULTS_REPLACESTR, '%s' % results)
  86. #return results
  87. self.send_response(200)
  88. self.end_headers()
  89. self.wfile.write(page)
  90.  
  91.  
  92. if __name__ == '__main__':
  93.  
  94. # Lets do it
  95.  
  96. # Set up a Zulu time zone
  97. os.environ['TZ'] = 'UTC+00UTC+00'
  98. time.tzset()
  99.  
  100. myip = gethostbyname(gethostname())
  101.  
  102. print 'Starting server on '+str(myip)+':'+str(LISTENPORT)+', use <Ctrl-C> o stop'
  103. server = HTTPServer(('0.0.0.0', LISTENPORT), GetHandler)
  104. server.serve_forever()

Report this snippet  

You need to login to post a comment.