Python Quick and Minimal setup HTTP-Server

Distraction! I've got to do with my `file-server`. Previously i deploy cloud servers with no docker.
Therefore the sshfs , a remote filesystem over SSH, works best! But then i found out that
it does not work as-is in docker service.

Ok, lets not crunch too much and deal with it a.s.a.p, since i have to resume back my 
coding-journals regarding my bitcoint-programming (cryptocurreny). So i decided to
use python (https.server) a minimal http server that would work great, and it is :D.

The intuition is to utilized the os.listdir() and os.path.isfile(), so

real_path = os.getenv('PREFIX_PATH') + '/' + post_data
ls = os.listdir(real_path)
files = []
for filenm in ls:
      if os.path.isfile(real_path + '/' + filenm) == True:
           print("File is ", filenm)
           files.append(l)
      else:
           pass
pass

Oke now we have the files reader handler, we stitch all of them in http.server
 
from http.server import BaseHTTPRequestHandler, HTTPServer
from dotenv import load_dotenv
import os
import logging
import json

load_dotenv('./.env')

'''
TODO sanitize the incoming data make sure does not traverse
'''

class S(BaseHTTPRequestHandler):

    def _set_response(self, **kwargs):

        self.send_response(200)

        if 'output_type' in kwargs and kwargs['output_type'] == 'json':
            self.send_header('Content-type', 'application/json')
        elif 'output_type' in kwargs and kwargs['output_type'] == 'text':
            self.send_header('Content-type', 'text/plain')
        else:
            self.send_header('Content-type', 'text/html')

        self.end_headers()
        pass

    def do_POST(self):
        content_length = int(self.headers['Content-length'])
        post_data = self.rfile.read(content_length).decode('utf-8')
        logging.info("POST Req, \nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n"
                %(
                    str(self.path), 
                    str(self.headers), 
                    post_data
                )
            )

        real_path = os.getenv('PREFIX_PATH') + '/' + post_data
        ls = os.listdir(real_path)
        files = []
        for l in ls:
            if os.path.isfile(real_path + '/' + l) == True:
                print("File is ", l)
                files.append(l)
            else:
                pass
        pass

        self._set_response()
        self.wfile.write(json.dumps(files).encode('utf-8'))

def run(server_class=HTTPServer, handler_class=S, port=8080):
    logging.basicConfig(level=logging.INFO,
        filename='file_server.log',
        format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
        datefmt='%H:%M:%S.%f'
    )
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    logging.info('Starting httpd...\n')
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    logging.info('Stopping httpd...\n')

if __name__ == '__main__':

    from sys import argv

    if len(argv) == 2:
        run(port=int(argv[1]))
    else:
        run()
The result at PHP endpoint would need to be parsed with json_decode().

Comments

Popular posts from this blog

Arduino RFID, RC522, VUSB HID as Keyboard

Codeigniter Oracle Transaction BUG

Error: cannot find symbol import android.support.v4.app.ActivityCompat