Beispiel #1
0
    def serve_client(self, client, req: Request):
        try:
            Logger.debug_info(f'Request {req}')
            if req.insufficient():
                raise Errors.MALFORMED_REQ

            a = time.perf_counter()
            res = self.handle_req(req)
            Logger.debug_info(
                f'Request handling time {time.perf_counter() - a}')
            Logger.debug_info(f'Response prepared {res}')

            Response.send_response(client, res)
            Logger.debug_info(f'Response sent')

            Logger.info(f'Source Requested',
                        extra={
                            'method': req.method,
                            'url': req.path,
                            'code': res.status,
                            'ip': client.getpeername()
                        })

            if req.headers.get('Connection') == 'keep-alive':
                client.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
            if req.headers.get('Connection') == 'close':
                self.close(client)
        except KeepAliveExpire:
            self.close(client)
        except Exception as e:
            Logger.exception(f'Client handling failed')
            send_error(client, e, self.configurator)
Beispiel #2
0
def send_error(connection, err, config):
    try:
        if err.page:
            with open(config.get("error-pages").get(err.page), 'rb') as p:
                p = p.read()
            res = [Response.build_err_res(err.status, err.reason, p)]
        else:
            res = [
                Response.build_err_res(err.status, err.reason,
                                       (err.body
                                        or err.reason).encode('utf-8'))
            ]
    except Exception as e:
        Logger.error(f'Error during err creation', e)
        res = [
            Response.build_err_res(500, b'Internal Server Error',
                                   b'Internal Server Error')
        ]
    Response.send_response(connection, *res)