예제 #1
0
 def __default_route(req):
     res = HTTPResponse()
     res.code = 404
     res.phrase = "not found"
     res.add_header('Content-Type', 'text/html')
     res.set_body("<h1>404 not found</h1> unknown url: " + req["raw"].url)
     return res
예제 #2
0
 def __default_server_error(req, err):
     res = HTTPResponse()
     res.code = 500
     res.phrase = "Internal Server Error"
     res.add_header('Content-Type', 'text/html')
     res.set_body(f"<h1>server error:</h1> <p>{err}</p>")
     return res
예제 #3
0
    def web_socket_location(req):
        res = HTTPResponse()
        res.code = 200
        res.phrase = "OK"
        res.add_header("Content-Type", "application/json")

        # create json object
        obj = {
            "ip": socket.gethostbyname(socket.gethostname()),
            "port": WS_PORT
        }
        res.set_body(json.dumps(obj))
        return res
예제 #4
0
 def __route_req(self, req):
     # build string of request method + url (without url params)
     key = req["raw"].method + " " + req["raw"].url.split('?')[0]
     if key in self.__routes.keys():
         # if value of key in the routes map is string or byte
         # return response with the value in the body
         if isinstance(self.__routes[key], bytes) or \
                 isinstance(self.__routes[key], str):
             res = HTTPResponse()
             res.code = 200
             res.phrase = 'ok'
             res.set_body(self.__routes[key])
             return res
         # if it isnt string nor bytes then in must be a function.
         else:
             return self.__routes[key](req)
     # if key isnt found send 404
     elif self.route404 is None:
         return self.__default_route(req)
     else:
         return self.route404(req)