summaryrefslogtreecommitdiffstats
path: root/server.py
blob: 13e56974b22d2b289c307a3daabb314ac65635ab (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
from http.server import HTTPServer, BaseHTTPRequestHandler
import lib  



class Request():
    def __init__(self, body):
        self.body = body 


# Explanation: https://blog.anvileight.com/posts/simple-python-http-server/

class Handler(BaseHTTPRequestHandler):
    """ The class responsible for handling all the
    different requests made to our server 
    """

    def _set_headers(self):
        """ Standard header stuff that has to be done """
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()

    def do_GET(self):
        """ Just serve up our one and only html page """
        self._set_headers()
        res = lib.find_get(self.path)
        if hasattr(res, 'encode'):
            self.wfile.write(res.encode())
        else:
            self.wfile.write(res)

    
    def do_POST(self):
        """ An async ajax request. Find the function from 'posts.py' to handle this 
        particular request. 
        """
        self.send_response(200)
        self.end_headers()
        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length)
        request = Request(body)
        res = lib.find_post(self.path, request)
        self.wfile.write(res.encode())


def run (port = 8314):
    server_adress = ('', port) # Should make the port a command line argument
    server = HTTPServer(server_adress, Handler)
    print(f'Starting server on port: {port}.')
    server.serve_forever()
    
    

if __name__ == '__main__':
    run()