Advertisement
aproxtime

HTTP Server

May 23rd, 2019
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.32 KB | None | 0 0
  1. from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
  2. import SocketServer
  3. import json
  4.  
  5. class S(BaseHTTPRequestHandler):
  6.     def _set_headers(self, tipe=""):
  7.         self.send_response(200)
  8.         self.send_header('Content-type', tipe)
  9.         self.end_headers()
  10.  
  11.     def do_GET(self):
  12.         req = str(self.path)
  13.         dataOut = ""
  14.        
  15.         if (req=="/tes"):
  16.             dataOut = "Fungsi Tes"
  17.             self._set_headers('text/html')
  18.         elif (req=="/get"):
  19.             dataOut = "Fungsi Get"
  20.             self._set_headers('text/html')
  21.         elif (req=="/json"):
  22.             dataOut = json.dumps({"data":"isi"})
  23.             self._set_headers('application/json')
  24.        
  25.         self.wfile.write(dataOut)
  26.  
  27.     def do_HEAD(self):
  28.         self._set_headers()
  29.        
  30.     def do_POST(self):
  31.         # Doesn't do anything with posted data
  32.         self._set_headers()
  33.         self.wfile.write("<html><body><h1>POST!</h1></body></html>")
  34.        
  35. def run(server_class=HTTPServer, handler_class=S, port=8080):
  36.     server_address = ('', port)
  37.     httpd = server_class(server_address, handler_class)
  38.     print 'Starting httpd...'
  39.     httpd.serve_forever()
  40.  
  41. if __name__ == "__main__":
  42.     from sys import argv
  43.  
  44.     if len(argv) == 2:
  45.         run(port=int(argv[1]))
  46.     else:
  47.         run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement