示例#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 home_route(req):
     res = HTTPResponse()
     res.code = 303
     res.phrase = "See Other"
     res.add_header("Location", "/index.html")
     return res
     pass
示例#4
0
 def cookie(req):
     res = HTTPResponse()
     res.code = 200
     res.phrase = "OK"
     res.add_header('Set-Cookie', 'us=2')
     res.add_header('Set-Cookie', 'u1=2sdf')
     return res
     pass
示例#5
0
 def create_room(req):
     # create room and redirect user to it
     res = HTTPResponse()
     res.code = 303
     res.phrase = "See Other"
     res.add_header(
         "Location",
         f"/room/index.html?room={ws.create_room()}&name={req['url_params']['name'][0]}"
     )
     return res
     pass
示例#6
0
 def join_room(req):
     # redirect user to room
     res = HTTPResponse()
     res.code = 303
     res.phrase = "See Other"
     res.add_header(
         "Location",
         f"/room/index.html?room={req['url_params']['id'][0]}&name={req['url_params']['name'][0]}"
     )
     return res
     pass
示例#7
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
示例#8
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)