Monday, August 13, 2018

Simple HTTP Listener using Python

Here is a simple HTTP listener using Python BaseHTTPRequestHandler 
This Application will,

  • listen to port 8000 on localhost
  • respond to REST POST request 

from BaseHTTPServer import BaseHTTPRequestHandler
import urlparse, json
import shutil
import os

class GetHandler(BaseHTTPRequestHandler):

	def do_POST(self):

		content_len = int(self.headers.getheader('content-length'))
		req_token = self.headers.get('Authorization')
		post_body = self.rfile.read(content_len)
		data = json.loads(post_body)
		user_id = data['id']
		user_name = data['name']
		
		print ("Token "+str(req_token))
		print ("User Id "+str(user_id))
		print ("User Name "+str(user_name))
		 
		#Do something here
		
		self.send_response(200)
		return

if __name__ == '__main__':
	from BaseHTTPServer import HTTPServer
	server = HTTPServer(('localhost', 8000), GetHandler)
	print 'Starting server at http://localhost:8009'
	server.serve_forever()

    
 
Save the content as simple_http_server.py

Start Application : python simple_http_server.py

Sample Request:

curl -v -X POST -H 'Authorization: Bearer gcfdgckuyebku7t56FHGVBKJHKJTY6' -d '{"id":"1234","name":"Hasitha"}' http://localhost:8000

Sample Response:

* Rebuilt URL to: http://localhost:8000/
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 8000 (#0)
> POST / HTTP/1.1
> Host: localhost:8000
> User-Agent: curl/7.47.0
> Accept: */*
> Authorization: Bearer gcfdgckuyebku7t56FHGVBKJHKJTY6
> Content-Length: 30
> Content-Type: application/x-www-form-urlencoded

* upload completely sent off: 30 out of 30 bytes
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Server: BaseHTTP/0.3 Python/2.7.12
< Date: Mon, 13 Aug 2018 15:21:06 GMT

* Closing connection 0

Application Logs:

Starting server at http://localhost:8000
Token Bearer gcfdgckuyebku7t56FHGVBKJHKJTY6
User Id 1234
User Name Hasitha

127.0.0.1 - - [13/Aug/2018 15:21:06] "POST / HTTP/1.1" 200 -







File Sharing using NFS in GKE Cluster

 File Sharing using NFS in GKE Cluster There was a requirement to create common file sharing location which should be accessible by specific...