Advertisement
Guest User

Untitled

a guest
Jan 24th, 2017
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. #!/usr/bin/env python
  2. """
  3. Very simple HTTP server in python.
  4. Usage::
  5. ./dummy-web-server.py [<port>]
  6. Send a GET request::
  7. curl http://localhost
  8. Send a HEAD request::
  9. curl -I http://localhost
  10. Send a POST request::
  11. curl -d "foo=bar&bin=baz" http://localhost
  12. """
  13. from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
  14. import SocketServer
  15. import sys
  16. import time
  17. import csv
  18. import urllib
  19. import psycopg2
  20.  
  21.  
  22. con = None
  23.  
  24. class S(BaseHTTPRequestHandler):
  25. def _set_headers(self):
  26. self.send_response(200)
  27. self.send_header('Content-type', 'text/html')
  28. self.end_headers()
  29.  
  30. def do_GET(self):
  31. self._set_headers()
  32. self.wfile.write("<html><body><h1>hi!</h1></body></html>")
  33.  
  34. def do_HEAD(self):
  35. self._set_headers()
  36.  
  37. def do_POST(self):
  38. # Doesn't do anything with posted data
  39. content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
  40. post_data = self.rfile.read(content_length) # <--- Gets the data itself
  41. print post_data # <-- Print post data
  42. self._set_headers()
  43. dataEncoded = str(post_data)
  44. dataString = urllib.unquote(post_data)
  45. timeString = str(time.strftime("%d %m %Y %H:%M:%S"))
  46. with open("decoded_log.csv",'a') as resultFile:
  47. wr = csv.writer(resultFile, dialect='excel')
  48. wr.writerow([dataString,timeString])
  49. with open("encoded_log.csv",'a') as resultFile:
  50. wr = csv.writer(resultFile, dialect='excel')
  51. wr.writerow([dataEncoded,timeString])
  52. con = psycopg2.connect("host=localhost dbname=data_log user=USER password=PASSWORD")
  53. print "DB Connection successful."
  54. cur = con.cursor()
  55. cur.execute("INSERT INTO log(data,date_time) VALUES (%s, %s)",(dataString,timeString))
  56. con.commit()
  57.  
  58. def run(server_class=HTTPServer, handler_class=S, port=5400):
  59. server_address = ('', port)
  60. httpd = server_class(server_address, handler_class)
  61. print 'Starting httpd...'
  62. httpd.serve_forever()
  63.  
  64. if __name__ == "__main__":
  65. from sys import argv
  66.  
  67. if len(argv) == 2:
  68. run(port=int(argv[1]))
  69. else:
  70. run()
  71.  
  72. sys.exit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement