コード例 #1
0
ファイル: request.py プロジェクト: mmasata/miniweb
    async def parse_header(self, data):
        """
        Accept HTTP request header in raw and parse them and store to attribute.
        :param data: Incoming header row.
        :return: Boolean if we can continue read headers.
        """

        try:
            if not self.has_path:
                self.method, full_path, proto = data.split()
                log.info("Incoming HTTP request {m} {p}.".format(m=self.method, p=full_path))

                await self.__find_query_params(full_path)
                self.has_path = True
            else:
                header, value = data.split(": ")
                self.headers[header] = value.replace("\r\n", "")
                log.debug("Header\n {k}: {v}".format(k=header, v=self.headers[header]))

                if "Content-Length" == header:
                    self.headers["Content-Type"] = self.headers["Content-Type"].split(";")[0]
                    self.content_len = int(value)
                    self.content_read = self.content_len > 0
                    return False

            return True
        except HeaderException:
            log.error("Error during read of request headers!")
コード例 #2
0
    def __parse_data(self, data):
        log.info("Parsing FormData.")
        rows = data.split("\r\n")
        read_values = False
        current_value = ""
        current_is_file = False
        filename = None
        current_key = None
        for row in rows:
            if not (row[0:2] == "--"):
                if not read_values:
                    if row != "":
                        param_header = row.split(";")
                        current_is_file = len(param_header) == 3
                        filename = param_header[2] if current_is_file else None
                        current_key = param_header[1].split('"')[1]
                        read_values = True
                else:
                    current_value += row
            elif current_key is not None:
                if current_is_file:
                    current_value = self.__create_file(filename, current_value)

                log.debug("Set form data attribute with key: {k}.".format(
                    k=current_key))
                setattr(self, current_key, current_value)
                read_values = False
                current_key = None
                current_value = ""
                filename = None
コード例 #3
0
ファイル: route.py プロジェクト: mmasata/miniweb
    def __init__(self, path, methods, fc):
        log.info("Register route for method/s: {m} and path: {p}.".format(
            m=methods, p=path))

        self.path = path
        self.regex, self.param_keys = self.__compile_regex(path)
        self.methods = methods
        self.fc = fc
コード例 #4
0
ファイル: route.py プロジェクト: mmasata/miniweb
    def __init__(self, root, path, controller=None):
        self.file_path = path if controller is None else controller.path + path
        self.root = root

        log.info("Creating static route.")

        def _inner(req, res):
            if validate(controller, req, res):
                res.status(Status.OK).type(self.mime).entity(self.file).build()

        super().__init__(path, ["GET"], _inner)
コード例 #5
0
ファイル: route.py プロジェクト: mmasata/miniweb
    def is_match(self, path):
        try:
            destination_file = path.replace(self.file_path, self.root, 1)

            log.info("Looking for static file.")
            log.debug("File destination path should be {df}.".format(
                df=destination_file))

            self.file = open(destination_file)
            self.mime = get_mime_by_suffix(destination_file)
            return True
        except:
            log.debug("Match with static route was not found.")
            return False
コード例 #6
0
def validate_consumes(mime, req, res):
    """
    Validate incoming Content-Type.
    :param mime: Mime type which route can accept.
    :param req: HTTP request wrapped inside of Request class.
    :param res:  Response class which will define HTTP response.
    :return: Boolean of success/fail.
    """

    log.info("Validate consumes.")
    if (mime is None) or (req.headers["Content-Type"] in mime):
        log.debug("Consumes middleware was suceed.")
        return True
    else:
        log.warning("Consumes middleware failed!")
        res.type("text/html").entity(consume_error(
            req.headers["Content-Type"])).status(400).build()
        return False
コード例 #7
0
def get_content(data, t):
    """
    Parse incoming Content-Type to object.
    :param data: Raw Content-Data from HTTP request.
    :param t: Content-Type of HTTP request Content-Data.
    :return: Data parsed to object.
    """

    result = data
    if t == "application/json":
        log.info("Parsing JSON string to object.")
        result = ujson.loads(data)
    elif t == "multipart/form-data":
        result = FormData(data)
    else:
        log.warning(
            "Unknown content type! Content will be accessable in raw format.")
    return result
コード例 #8
0
def validate(controller, req, res):
    """
    Validate incoming HTTP request - run middleware function.
    :param controller: Group router to group and define path. (optional parameter)
    :param req: HTTP request wrapped inside of Request class.
    :param res: Response class which will define HTTP response.
    :return: Boolean of success/fail.
    """

    log.info("Validate middlewares.")
    if not check_filters_group(global_filter, req, res):
        return False

    if controller is not None:
        if not check_filters_group(controller.filters, req, res):
            return False

    log.debug("Middleware function was suceed.")
    return True
コード例 #9
0
ファイル: server.py プロジェクト: mmasata/miniweb
    def init(self):
        """
        Method for server in asyncio event loop.
        :return: None
        """
        self.keep_run = True
        self.delay = 0

        gc.collect()
        server_task = None

        try:
            server_task = asyncio.start_server(self.__handle, self.config.host,
                                               self.config.port)
        except:
            raise ConfigParamsException("Host or port is missing!")

        log.info("Server is running on {h} with port: {p}.".format(
            h=self.config.host, p=self.config.port))

        self.e_loop = asyncio.get_event_loop()
        self.e_loop.create_task(server_task)
        self.e_loop.run_forever()
コード例 #10
0
ファイル: server.py プロジェクト: mmasata/miniweb
 async def __stop(self):
     log.debug(
         "Miniweb server will be stopped in {t}ms.".format(t=self.delay))
     await asyncio.sleep_ms(self.delay)
     self.e_loop.stop()
     log.info("Miniweb has been stopped.")