示例#1
0
def test_resolve():
    controller = resolve('now')
    assert controller is not None

    controller = resolve('echo')
    assert controller is not None

    controller = resolve('bad_action')
    assert controller is None
示例#2
0
def handle_default_request(raw_request):
    request = json.loads(raw_request.decode(ENCODING_NAME))

    action_name = request.get('action')

    if validate_request(request):
        controller = resolve(action_name)
        if controller:
            try:
                response = controller(request)
                print('response', response)

                if response.get('code') != 200:
                    logging.error(f'Request is not valid')
                else:
                    logging.info(
                        f'Function { controller.__name__ } was called')
            except Exception as err:
                logging.critical(err, exc_info=True)
                response = make_response(
                    request,
                    500,
                    'Internal server error',
                )
        else:
            logging.error(f'Action { action_name } does not exits')
            response = make_404(request)
    else:
        logging.error(f'Request is not valid')
        response = make_400(request)

    return json.dumps(response).encode(ENCODING_NAME)
示例#3
0
def handle_request(raw_request):
    request = jim.unpack(raw_request)

    action_name = request.get('action')

    if validate_request(request):
        controller = resolve(action_name)
        if controller:
            try:
                response = controller(request)
                if response.get('code') != 200:
                    logging.error('Wrong request format')
                else:
                    logging.info(
                        f'Request is valid and processed by controller')
            except Exception as err:
                logging.critical(err)
                response = make_response(request, 500, 'Internal server error')
        else:
            logging.error(f'Action {action_name} does not exits')
            response = make_404(request)
    else:
        logging.error('Request is not valid')
        response = make_400(request)

    return jim.pack(response)
示例#4
0
def main():
    try:
        sock = socket.socket()
        sock.bind((host, port))
        sock.listen(5)
        logging.info(f'Server started with {host}:{port}')
        while True:
            client, address = sock.accept()

            logging.info(f'Client detected {address}')

            b_request = client.recv(settings.BUFFERSIZE)
            request = jim.unpack(b_request)

            action_name = request.get('action')

            if validate_request(request):
                controller = resolve(action_name)
                if controller:
                    try:
                        response = controller(request)
                        if response.get('code') != 200:
                            logging.error('Wrong request format')
                        else:
                            logging.info(
                                f'Request is valid and processed by controller'
                            )
                    except Exception as err:
                        logging.critical(err)
                        response = make_response(request, 500,
                                                 'Internal server error')
                else:
                    logging.error(f'Action {action_name} does not exits')
                    response = make_404(request)
            else:
                logging.error('Request is not valid')
                response = make_400(request)

            response = jim.pack(response)
            logging.info('Send response to client')
            client.sendall(response)
    except KeyboardInterrupt:
        logging.info('Server  closed')
示例#5
0
def handle_client_request(request):
    action_name = request.get('action')
    if validate_request(request):
        controller = resolve(action_name)
        if controller:
            try:
                return controller(request)
                # if action_name == 'shutdown_server':
                #     logger.info('Shutdown server')
                #     response_string = json.dumps(response)
                #     client.send(response_string.encode('utf-8'))
                #     break

            except Exception as err:
                logger.critical(err, exc_info=True)
                return make_response(request, 500, 'Internal server error.')
        else:
            logger.error(f'Action not found: {action_name}')
            return make_404(request)
    else:
        logger.error(f'Bad request: {request}')
        return make_400(request)
示例#6
0
def write_response(client, request):
    response = None
    action_name = request.get('action')

    if validate_request(request):
        controller = resolve(action_name)
        if controller:
            try:
                response = controller(request)
            except Exception as err:
                logging.critical(err, exc_info=True)
                respoonse = make_response(request, 500,
                                          'Internal server error')
        else:
            logging.error(f'Action not found: {action_name}')
            response = make_404(request)
    else:
        logging.error(f'Bad Request: {action_name} request: {request}')
        response = make_400(request)

    response_string = json.dumps(response)
    client.send(response_string.encode('utf-8'))
示例#7
0
    def __init__(self, environ, start_response):
        path_elements = environ['PATH_INFO'].split('/')
        #Find controller based on request method and path
        controller_class, asset_path, asset_files = resolve(
            environ['REQUEST_METHOD'], path_elements)
        self.controller = controller_class()
        #Collect useful params
        self.params = {}
        if environ['REQUEST_METHOD'] == 'GET':
            self.params['body'] = parse_qs(environ['QUERY_STRING'],
                                           encoding='utf-8')
        else:
            try:
                request_body_size = int(environ.get('CONTENT_LENGTH', 0))
            except (ValueError):
                request_body_size = 0
            request_body = environ['wsgi.input'].read(
                request_body_size).decode()
            self.params['body'] = parse_qs(request_body, encoding='utf-8')
        self.params['resource_id'] = path_elements[-1]
        #Init DB
        if exists(_DB):
            self.conn = db_conn(_DB)
        else:
            self.conn = db_conn(_DB)
            cursor = self.conn.cursor()
            with open(_INIT) as init_file:
                cursor.executescript(init_file.read())
        #Collect required files
        try:
            body = list(asset_files.keys())[0]
            self.assets = {'body': get_file(sub(r"\.\/", asset_path, body))}
            for k, v in asset_files[body].items():
                self.assets[k] = get_file(sub(r"\.\/", asset_path, v))
        except IndexError:
            self.assets = {}

        self.start = start_response
示例#8
0
sock = socket.socket()
sock.bind((address, port))
sock.listen(5)

logger = logging.getLogger('server')
logger.info(f'Server start with host:{ address } and port: { port }')
try:
    while True:
        client, address = sock.accept()
        logger.info(f'Client detected {address}')
        data = client.recv(1024)
        request = json.loads(data.decode('utf-8'))

        if validate_request(request):
            action_name = request.get('action')
            controller = resolve(action_name)

            if controller:
                try:
                    response = controller(request)

                    if action_name == 'shutdown_server':
                        logger.info('Shutdown server')
                        response_string = json.dumps(response)
                        client.send(response_string.encode('utf-8'))
                        break

                except Exception as err:
                    logger.critical(err, exc_info=True)
                    response = make_response(request, 500,
                                             'Internal server error.')
示例#9
0
                # name = msg['name_client']
                logger.debug(f'Получено сообщение:\n{request}')
                requests.append(request)
            except Exception as error:
                request, event = None, None
                requests.append(request)
                response = make_400(data.decode('utf-8'))
                logger.debug(f'Ошибочка => {error}')


        if requests:
            for request in requests:
                for client in wlist:
                    if validate_request(request):
                        logger.debug(request.get('event'))
                        controller = resolve(request.get('event'))
                        if controller:
                            try:
                                response = controller(request)
                                response_string = json.dumps(response)
                                client.send(response_string.encode('utf-8'))
                                logger.debug(f'Отправка сообщения: {response_string}')
                                if event == 'start':
                                    while True:
                                        second_data = client.recv(2048)
                                        request = json.loads(second_data)
                                        logger.debug(f'Получено сообщение: {request}')
                                        if validate_request(request):
                                            controller = resolve(request.get('event'))
                                            if controller:
                                                response = controller(request)
示例#10
0
def test_resolve(routes, controller):
    resolved = resolve('echo', routes)
    assert resolved == controller
示例#11
0
def test_resolve(routes, controller):
    resolved = resolve('upper_text', routes)
    assert resolved == controller
示例#12
0
logger = logging.getLogger('app.server')

sock = socket.socket()
sock.bind(('', 8888))
sock.listen(5)

try:
    while True:
        client, address = sock.accept()
        logger.debug('Client detected {0}'.format(address))
        data = client.recv(1024)
        request = json.loads(data.decode('utf-8'))

        if validate_request(request):
            controller = resolve(request.get('action'))
            if controller:
                try:
                    response = controller(request)
                except Exception:
                    response = make_response(request, 500,
                                             'Internal server error.')
            else:
                response = make_404(request)
        else:
            response = make_400(request)

        response_string = json.dumps(response)
        client.send(response_string.encode('utf-8'))
        client.close()