Exemple #1
0
def manage_message(impact, json, client_id):
    messages_db = dict((msg.channel_id, msg) for msg in impact.messages)
    messages_json = dict()
    if 'messages' in json:
        messages_json = dict((msg["channel"]["id"], msg) for msg in json['messages'])
        manage_channels_required(messages_json, client_id)
        for message_json in json['messages']:
            if message_json["channel"]["id"] in messages_db:
                msg = messages_db[message_json["channel"]["id"]]
                mapper.fill_from_json(msg, message_json, mapper.message_mapping)
                clean_message(msg,  msg.channel.content_type)
                manage_message_meta(msg, message_json)
            else:
                message = models.Message()
                message.impact_id = impact.id
                mapper.fill_from_json(message, message_json, mapper.message_mapping)
                channel = models.Channel.get(message.channel_id, client_id)
                clean_message(message, channel.content_type)
                impact.insert_message(message)
                manage_message_meta(message, message_json)
                messages_db[message.channel_id] = message

    difference = set(messages_db) - set(messages_json)
    for diff in difference:
        impact.delete_message(messages_db[diff])
Exemple #2
0
def fill_and_get_pt_object(navitia, all_objects, json, add_to_db=True):
    """
    :param all_objects: dictionary of objects to be added in this session
    :param json: Flux which contains json information of pt_object
    :param add_to_db: ptobject insert into database
    :return: a pt_object and modify all_objects param
    """

    if json["id"] in all_objects:
        return all_objects[json["id"]]

    pt_object = models.PTobject.get_pt_object_by_uri(json["id"])

    if pt_object:
        all_objects[json["id"]] = pt_object
        return pt_object

    if not navitia.get_pt_object(json['id'], json['type']):
        raise exceptions.ObjectUnknown()

    pt_object = models.PTobject()
    mapper.fill_from_json(pt_object, json, mapper.object_mapping)
    if add_to_db:
        db.session.add(pt_object)
    all_objects[json["id"]] = pt_object
    return pt_object
Exemple #3
0
def create_application_period_pattern_from_json(json):
    pattern = models.Pattern()
    mapper.fill_from_json(pattern, json, mapper.pattern_mapping)
    pattern.time_slots = create_pattern_time_slots_from_json(
        json['time_slots'])

    return pattern
Exemple #4
0
def manage_time_slot(pattern, json):
    if 'time_slots' in json:
        for json_time_slot in json['time_slots']:
            time_slot = models.TimeSlot(pattern.id)
            mapper.fill_from_json(time_slot, json_time_slot,
                                  mapper.time_slot_mapping)
            pattern.insert_time_slot(time_slot)
Exemple #5
0
def fill_and_get_pt_object(navitia, all_objects, json, add_to_db=True):
    """
    :param all_objects: dictionary of objects to be added in this session
    :param json: Flux which contains json information of pt_object
    :param add_to_db: ptobject insert into database
    :return: a pt_object and modify all_objects param
    """

    if json["id"] in all_objects:
        return all_objects[json["id"]]

    pt_object = models.PTobject.get_pt_object_by_uri(json["id"])

    if pt_object:
        all_objects[json["id"]] = pt_object
        return pt_object

    if not navitia.get_pt_object(json['id'], json['type']):
        raise exceptions.ObjectUnknown()

    pt_object = models.PTobject()
    mapper.fill_from_json(pt_object, json, mapper.object_mapping)
    if add_to_db:
        db.session.add(pt_object)
    all_objects[json["id"]] = pt_object
    return pt_object
Exemple #6
0
def create_severity_wordings_from_json(json):
    wordings = []
    for wording_json in json:
        wording = models.Wording()
        mapper.fill_from_json(wording, wording_json, mapper.meta_mapping)
        wordings.append(wording)
    return wordings
Exemple #7
0
def create_metas_from_json(json):
    metas = []
    for meta_json in json:
        meta = models.Meta()
        mapper.fill_from_json(meta, meta_json, mapper.meta_mapping)
        metas.append(meta)

    return metas
Exemple #8
0
def manage_patterns(impact, json):
    impact.delete_patterns()
    if 'application_period_patterns' in json:
        for json_pattern in json['application_period_patterns']:
            pattern = models.Pattern(impact.id)
            mapper.fill_from_json(pattern, json_pattern, mapper.pattern_mapping)
            impact.insert_pattern(pattern)
            manage_time_slot(pattern, json_pattern)
Exemple #9
0
def manage_patterns(impact, json):
    impact.delete_patterns()
    if 'application_period_patterns' in json:
        for json_pattern in json['application_period_patterns']:
            pattern = models.Pattern(impact.id)
            mapper.fill_from_json(pattern, json_pattern, mapper.pattern_mapping)
            impact.insert_pattern(pattern)
            manage_time_slot(pattern, json_pattern)
Exemple #10
0
def test_fill_from_json_with_missing_json():
    obj = Obj()
    obj.foo = 1
    fields = {'foo': None}
    json = {'bar': 3}

    mapper.fill_from_json(obj, json, fields)
    eq_(obj.foo, None)
Exemple #11
0
def test_fill_from_json_with_formater():
    obj = Obj()
    obj.date = None
    fields = {'date': mapper.Datetime('date')}
    json = {'date': '2014-05-22T12:15:23'}

    mapper.fill_from_json(obj, json, fields)
    eq_(obj.date, datetime(2014, 5, 22, 12, 15, 23))
Exemple #12
0
def create_pattern_time_slots_from_json(json):
    time_slots = []
    for time_slot_json in json:
        time_slot = models.TimeSlot()
        mapper.fill_from_json(time_slot, time_slot_json,
                              mapper.time_slot_mapping)
        time_slots.append(time_slot)

    return time_slots
Exemple #13
0
def create_severity_from_json(json):
    severity = models.Severity()
    mapper.fill_from_json(severity, json, mapper.severity_mapping)
    severity.id = json['id']
    severity.wording = json['wording']
    severity.created_at = get_datetime_from_json_attr(json, 'created_at')
    severity.updated_at = get_datetime_from_json_attr(json, 'updated_at')
    severity.wordings = create_severity_wordings_from_json(json['wordings'])
    return severity
Exemple #14
0
def create_channel_from_json(json):
    channel = models.Channel()
    channel.id = json['id']
    mapper.fill_from_json(channel, json, mapper.channel_mapping)
    channel.created_at = get_datetime_from_json_attr(json, 'created_at')
    channel.updated_at = get_datetime_from_json_attr(json, 'updated_at')
    channel.channel_types = create_channel_types_from_json(json)

    return channel
Exemple #15
0
def test_fill_from_json():
    obj = Obj()
    obj.foo = None
    obj.baz = None
    json = {'foo': 'bar', 'baz': 2}
    fields = {'foo': None, 'baz': None}

    mapper.fill_from_json(obj, json, fields)
    eq_(obj.foo, 'bar')
    eq_(obj.baz, 2)
Exemple #16
0
def test_fill_from_json_with_nested():
    obj = Obj()
    obj.foo = None
    obj.bar = None
    json = {'foo': 'bar', 'baz': {'bar': 2}}
    fields = {'foo': None, 'baz': {'bar': None}}

    mapper.fill_from_json(obj, json, fields)
    eq_(obj.foo, 'bar')
    eq_(obj.bar, 2)
Exemple #17
0
def create_pt_object_from_json(json):
    pt_object = models.PTobject()
    mapper.fill_from_json(pt_object, json, mapper.object_mapping)

    if 'line_section' in json:
        pt_object.line_section = create_line_section_from_json(
            json['line_section'])
    elif 'name' in json:
        pt_object.name = json['name']

    return pt_object
Exemple #18
0
class Channel(flask_restful.Resource):
    @validate_client()
    @validate_id()
    def get(self, client, id=None):
        if id:
            response = {'channel': models.Channel.get(id, client.id)}
            return marshal(response, one_channel_fields)
        else:
            response = {'channels': models.Channel.all(client.id), 'meta': {}}
            return marshal(response, channels_fields)

    @validate_client(True)
    def post(self, client):
        json = request.get_json(silent=True)
        logging.getLogger(__name__).debug('Post channel: %s', json)
        try:
            validate(json, channel_input_format)
        except ValidationError, e:
            logging.debug(str(e))
            # TODO: generate good error messages
            return marshal({'error': {
                'message': utils.parse_error(e)
            }}, error_fields), 400

        channel = models.Channel()
        mapper.fill_from_json(channel, json, mapper.channel_mapping)
        channel.client = client
        try:
            db_helper.manage_channel_types(channel, json["types"])
        except exceptions.InvalidJson, e:
            return marshal({'error': {
                'message': utils.parse_error(e)
            }}, error_fields), 400
Exemple #19
0
def manage_message_meta(message, json):
    meta_db = dict((meta.key, meta) for meta in message.meta)
    metas_json = dict()
    if 'meta' in json:
        metas_json = dict((meta['key'], meta) for meta in json['meta'])
        for meta_json in json['meta']:
            if meta_json['key'] not in meta_db:
                meta = models.Meta()
                mapper.fill_from_json(meta, meta_json, mapper.meta_mapping)
                message.insert_meta(meta)
                meta_db[meta.key] = meta
            else:
                meta = meta_db[meta_json['key']]
                mapper.fill_from_json(meta, meta_json, mapper.meta_mapping)
    difference = set(meta_db) - set(metas_json)
    for diff in difference:
        message.delete_meta(meta_db[diff])
Exemple #20
0
def manage_message_db(impact, json, messages_json, messages_db, client_id):
    for message_json in json['messages']:
        if message_json["channel"]["id"] in messages_db:
            msg = messages_db[message_json["channel"]["id"]]
            mapper.fill_from_json(msg, message_json, mapper.message_mapping)
            clean_message(msg, msg.channel.content_type)
            manage_message_meta(msg, message_json)
        else:
            message = models.Message()
            message.impact_id = impact.id
            mapper.fill_from_json(message, message_json,
                                  mapper.message_mapping)
            channel = models.Channel.get(message.channel_id, client_id)
            clean_message(message, channel.content_type)
            impact.insert_message(message)
            manage_message_meta(message, message_json)
            messages_db[message.channel_id] = message
Exemple #21
0
def manage_message(impact, json):
    messages_db = dict((msg.channel_id, msg) for msg in impact.messages)
    messages_json = dict()
    if 'messages' in json:
        messages_json = dict((msg["channel"]["id"], msg) for msg in json['messages'])
        for message_json in json['messages']:
            if message_json["channel"]["id"] in messages_db:
                msg = messages_db[message_json["channel"]["id"]]
                mapper.fill_from_json(msg, message_json, mapper.message_mapping)
            else:
                message = models.Message()
                message.impact_id = impact.id
                mapper.fill_from_json(message, message_json, mapper.message_mapping)
                impact.insert_message(message)
                messages_db[message.channel_id] = message

    difference = set(messages_db) - set(messages_json)
    for diff in difference:
        impact.delete_message(messages_db[diff])
Exemple #22
0
class Property(flask_restful.Resource):
    def __init__(self):
        self.parsers = {'get': reqparse.RequestParser()}
        self.parsers['get'].add_argument('key').add_argument('type')

    @validate_client()
    @validate_id()
    def get(self, client, id=None):
        args = self.parsers['get'].parse_args()
        key = args['key']
        type = args['type']

        if id:
            property = models.Property.get(client.id, id)

            if property is None:
                return marshal(
                    {'error': {
                        'message': 'Property {} not found'.format(id)
                    }}, error_fields), 404

            return marshal({'property': property}, one_property_fields)
        else:
            response = {
                'properties': models.Property.all(client.id, key, type)
            }
            return marshal(response, properties_fields)

    @validate_client(True)
    def post(self, client):
        json = request.get_json(silent=True)
        logging.getLogger(__name__).debug('POST property: %s', json)

        try:
            validate(json, property_input_format)
        except ValidationError, e:
            return marshal({'error': {
                'message': utils.parse_error(e)
            }}, error_fields), 400

        property = models.Property()
        mapper.fill_from_json(property, json, mapper.property_mapping)
        property.client = client
        db.session.add(property)

        try:
            db.session.commit()
            db.session.refresh(property)
        except IntegrityError, e:
            return marshal({'error': {
                'message': utils.parse_error(e)
            }}, error_fields), 409
Exemple #23
0
def manage_message(impact, json):
    messages_db = dict((msg.channel_id, msg) for msg in impact.messages)
    messages_json = dict()
    if 'messages' in json:
        messages_json = dict(
            (msg["channel"]["id"], msg) for msg in json['messages'])
        for message_json in json['messages']:
            if message_json["channel"]["id"] in messages_db:
                msg = messages_db[message_json["channel"]["id"]]
                mapper.fill_from_json(msg, message_json,
                                      mapper.message_mapping)
            else:
                message = models.Message()
                message.impact_id = impact.id
                mapper.fill_from_json(message, message_json,
                                      mapper.message_mapping)
                impact.insert_message(message)
                messages_db[message.channel_id] = message

    difference = set(messages_db) - set(messages_json)
    for diff in difference:
        impact.delete_message(messages_db[diff])
Exemple #24
0
class Category(flask_restful.Resource):
    @validate_client()
    @validate_id()
    def get(self, client, id=None):
        if id:
            response = {'category': models.Category.get(id, client.id)}
            return marshal(response, one_category_fields)
        else:
            response = {
                'categories': models.Category.all(client.id),
                'meta': {}
            }
            return marshal(response, categories_fields)

    @validate_client(True)
    def post(self, client):
        json = request.get_json(silent=True)
        logging.getLogger(__name__).debug('Post category: %s', json)
        try:
            validate(json, category_input_format)
        except ValidationError, e:
            logging.debug(str(e))
            # TODO: generate good error messages
            return marshal({'error': {
                'message': utils.parse_error(e)
            }}, error_fields), 400

        # if an archived category exists with same name use the same instead of creating a new one.
        archived_category = models.Category.get_archived_by_name(
            json['name'], client.id)
        if archived_category:
            category = archived_category
            category.is_visible = True
        else:
            category = models.Category()
            mapper.fill_from_json(category, json, mapper.category_mapping)
            category.client = client
            db.session.add(category)

        try:
            db.session.commit()
            db.session.refresh(category)
        except IntegrityError, e:
            logging.debug(str(e))
            return marshal({'error': {
                'message': utils.parse_error(e)
            }}, error_fields), 400
Exemple #25
0
class Cause(flask_restful.Resource):
    def __init__(self):
        self.parsers = {}
        self.parsers["get"] = reqparse.RequestParser()
        parser_get = self.parsers["get"]
        parser_get.add_argument("category", type=utils.get_uuid)

    @validate_client()
    @validate_id()
    def get(self, client, id=None):
        args = self.parsers['get'].parse_args()
        category_id = args['category']
        if id:
            response = {'cause': models.Cause.get(id, client.id, category_id)}
            return marshal(response, one_cause_fields)
        else:
            response = {
                'causes': models.Cause.all(client.id, category_id),
                'meta': {}
            }
            return marshal(response, causes_fields)

    @validate_client(True)
    def post(self, client):
        json = request.get_json(silent=True)
        logging.getLogger(__name__).debug('Post cause: %s', json)
        try:
            validate(json, cause_input_format)
        except ValidationError, e:
            logging.debug(str(e))
            # TODO: generate good error messages
            return marshal({'error': {
                'message': utils.parse_error(e)
            }}, error_fields), 400

        cause = models.Cause()
        mapper.fill_from_json(cause, json, mapper.cause_mapping)
        cause.client = client
        try:
            db_helper.manage_wordings(cause, json["wordings"])
        except exceptions.InvalidJson, e:
            return marshal({'error': {
                'message': utils.parse_error(e)
            }}, error_fields), 400
Exemple #26
0
class Tag(flask_restful.Resource):
    @validate_client()
    @validate_id()
    def get(self, client, id=None):
        if id:
            response = {'tag': models.Tag.get(id, client.id)}
            return marshal(response, one_tag_fields)
        else:
            response = {'tags': models.Tag.all(client.id), 'meta': {}}
            return marshal(response, tags_fields)

    @validate_client(True)
    def post(self, client):
        json = request.get_json(silent=True)
        logging.getLogger(__name__).debug('Post tag: %s', json)
        try:
            validate(json, tag_input_format)
        except ValidationError, e:
            logging.debug(str(e))
            # TODO: generate good error messages
            return marshal({'error': {
                'message': utils.parse_error(e)
            }}, error_fields), 400

        # if an archived tag exists with same name use the same instead of creating a new one.
        archived_tag = models.Tag.get_archived_by_name(json['name'], client.id)
        if archived_tag:
            tag = archived_tag
            tag.client = client
            tag.is_visible = True
        else:
            tag = models.Tag()
            mapper.fill_from_json(tag, json, mapper.tag_mapping)
            tag.client = client
            db.session.add(tag)

        try:
            db.session.commit()
        except IntegrityError, e:
            logging.debug(str(e))
            return marshal({'error': {
                'message': utils.parse_error(e)
            }}, error_fields), 400
Exemple #27
0
def test_fill_from_json_with_optional_field():
    obj = Obj()
    obj.value = 'test'
    fields = {'value': mapper.OptionalField(attribute='value')}
    empty_json = {}
    json = {'value': 'real value'}

    mapper.fill_from_json(obj, empty_json, fields)
    eq_(obj.value, 'test')

    mapper.fill_from_json(obj, json, fields)
    eq_(obj.value, 'real value')

    mapper.fill_from_json(obj, empty_json, fields)
    eq_(obj.value, 'real value')
Exemple #28
0
class Severity(flask_restful.Resource):
    @validate_client()
    @validate_id()
    def get(self, client, id=None):
        if id:
            return marshal({'severity': models.Severity.get(id, client.id)},
                           one_severity_fields)
        else:
            response = {
                'severities': models.Severity.all(client.id),
                'meta': {}
            }
            return marshal(response, severities_fields)

    @validate_client(True)
    def post(self, client):
        json = request.get_json(silent=True)
        logging.getLogger(__name__).debug('Post severity: %s', json)
        try:
            validate(json, severity_input_format)
        except ValidationError, e:
            logging.debug(str(e))
            # TODO: generate good error messages
            return marshal({'error': {
                'message': utils.parse_error(e)
            }}, error_fields), 400

        severity = models.Severity()
        mapper.fill_from_json(severity, json, mapper.severity_mapping)
        severity.client = client
        try:
            db_helper.manage_wordings(severity, json["wordings"])
        except exceptions.InvalidJson, e:
            return marshal({'error': {
                'message': utils.parse_error(e)
            }}, error_fields), 400
Exemple #29
0
def manage_time_slot(pattern, json):
    if 'time_slots' in json:
        for json_time_slot in json['time_slots']:
            time_slot = models.TimeSlot(pattern.id)
            mapper.fill_from_json(time_slot, json_time_slot, mapper.time_slot_mapping)
            pattern.insert_time_slot(time_slot)
Exemple #30
0
def fill_and_add_line_section(navitia, impact_id, all_objects, pt_object_json):
    """
    :param impact_id: impact_id to construct uri of line_section object
    :param all_objects: dictionary of objects to be added in this session
    :param pt_object_json: Flux which contains json information of pt_object
    :return: pt_object and modify all_objects param
    """
    ptobject = models.PTobject()
    mapper.fill_from_json(ptobject, pt_object_json, mapper.object_mapping)

    #Here we treat all the objects in line_section like line, start_point, end_point
    line_section_json = pt_object_json['line_section']

    ptobject.uri = ":".join((line_section_json['line']['id'], ptobject.id))

    line_section = models.LineSection(ptobject.id)

    try:
        line_object = fill_and_get_pt_object(navitia, all_objects, line_section_json['line'])
    except exceptions.ObjectUnknown:
        raise exceptions.ObjectUnknown('{} {} doesn\'t exist'.format(line_section_json['line']['type'], line_section_json['line']['id']))

    line_section.line = line_object

    try:
        start_object = fill_and_get_pt_object(navitia, all_objects, line_section_json['start_point'])
    except exceptions.ObjectUnknown:
        raise exceptions.ObjectUnknown('{} {} doesn\'t exist'.format(line_section_json['line']['type'], line_section_json['line']['id']))
    line_section.start_point = start_object

    try:
        end_object = fill_and_get_pt_object(navitia, all_objects, line_section_json['end_point'])
    except exceptions.ObjectUnknown:
        raise exceptions.ObjectUnknown('{} {} doesn\'t exist'.format(line_section_json['line']['type'], line_section_json['line']['id']))
    line_section.end_point = end_object

    #Here we manage routes in line_section
    #"routes":[{"id":"route:MTD:9", "type": "route"}, {"id":"route:MTD:Nav23", "type": "route"}]
    if 'routes' in line_section_json:
        for route in line_section_json["routes"]:
            try:
                route_object = fill_and_get_pt_object(navitia, all_objects, route, True)
                line_section.routes.append(route_object)
            except exceptions.ObjectUnknown:
                raise exceptions.ObjectUnknown('{} {} doesn\'t exist'.format(route['type'], route['id']))

    #Here we manage via in line_section
    #"via":[{"id":"stop_area:MTD:9", "type": "stop_area"}, {"id":"stop_area:MTD:Nav23", "type": "stop_area"}]
    if 'via' in line_section_json:
        for via in line_section_json["via"]:
            try:
                via_object = fill_and_get_pt_object(navitia, all_objects, via, True)
                line_section.via.append(via_object)
            except exceptions.ObjectUnknown:
                raise exceptions.ObjectUnknown('{} {} doesn\'t exist'.format(via['type'], via['id']))

    #Fill sens from json
    if 'sens' in line_section_json:
        line_section.sens = line_section_json["sens"]

    #Fill wordings from json
    #"meta":[{"key":"direction", "value": "1234"}, {"key":"direction", "value": "5678"}]
    if 'metas' in line_section_json:
        try:
            manage_wordings(line_section, line_section_json['metas'])
        except exceptions.InvalidJson:
            raise

    ptobject.insert_line_section(line_section)
    return ptobject
Exemple #31
0
def generate_pt_object_from_json(json):
    pt_object = models.PTobject()
    mapper.fill_from_json(pt_object, json, mapper.object_mapping)
    pt_object.name = json['name']

    return pt_object
Exemple #32
0
class Disruptions(flask_restful.Resource):
    def __init__(self):
        self.navitia = None
        self.parsers = {}
        self.parsers["get"] = reqparse.RequestParser()
        parser_get = self.parsers["get"]

        parser_get.add_argument("start_page", type=int, default=1)
        parser_get.add_argument("items_per_page", type=int, default=20)
        parser_get.add_argument("publication_status[]",
                                type=option_value(publication_status_values),
                                action="append",
                                default=publication_status_values)
        parser_get.add_argument("tag[]", type=utils.get_uuid, action="append")
        parser_get.add_argument("current_time", type=utils.get_datetime)
        parser_get.add_argument("uri", type=str)
        parser_get.add_argument("status[]",
                                type=option_value(disruption_status_values),
                                action="append",
                                default=disruption_status_values)

    @validate_navitia()
    @validate_contributor()
    @manage_navitia_error()
    @validate_id()
    def get(self, contributor, navitia, id=None):
        self.navitia = navitia
        if id:
            return marshal(
                {'disruption': models.Disruption.get(id, contributor.id)},
                one_disruption_fields)
        else:
            args = self.parsers['get'].parse_args()
            page_index = args['start_page']
            if page_index == 0:
                abort(400, message="page_index argument value is not valid")
            items_per_page = args['items_per_page']
            if items_per_page == 0:
                abort(400,
                      message="items_per_page argument value is not valid")
            publication_status = args['publication_status[]']
            tags = args['tag[]']
            uri = args['uri']
            statuses = args['status[]']

            g.current_time = args['current_time']
            result = models.Disruption.all_with_filter(
                page_index=page_index,
                items_per_page=items_per_page,
                contributor_id=contributor.id,
                publication_status=publication_status,
                tags=tags,
                uri=uri,
                statuses=statuses)
            response = {
                'disruptions': result.items,
                'meta': make_pager(result, 'disruption')
            }
            return marshal(response, disruptions_fields)

    @validate_navitia()
    @validate_client(True)
    @manage_navitia_error()
    def post(self, client, navitia):
        self.navitia = navitia
        json = request.get_json(silent=True)
        logging.getLogger(__name__).debug('POST disruption: %s', json)
        try:
            validate(json, disruptions_input_format)
        except ValidationError, e:
            logging.debug(str(e))
            # TODO: generate good error messages
            return marshal({'error': {
                'message': utils.parse_error(e)
            }}, error_fields), 400
        disruption = models.Disruption()
        mapper.fill_from_json(disruption, json, mapper.disruption_mapping)

        # Use contributor_code present in the json to get contributor_id
        if 'contributor' in json:
            disruption.contributor = models.Contributor.get_or_create(
                json['contributor'])
        disruption.client = client

        # Add localization present in Json
        try:
            db_helper.manage_pt_object_without_line_section(
                self.navitia, disruption.localizations, 'localization', json)
        except exceptions.ObjectUnknown, e:
            return marshal({'error': {
                'message': '{}'.format(e.message)
            }}, error_fields), 404
Exemple #33
0
    def put(self, client, id):

        severity = models.Severity.get(id, client.id)
        json = request.get_json(silent=True)
        logging.getLogger(__name__).debug('PUT severity: %s', json)

        try:
            validate(json, severity_input_format)
        except ValidationError, e:
            logging.debug(str(e))
            # TODO: generate good error messages
            return marshal({'error': {
                'message': utils.parse_error(e)
            }}, error_fields), 400

        mapper.fill_from_json(severity, json, mapper.severity_mapping)
        try:
            db_helper.manage_wordings(severity, json["wordings"])
        except exceptions.InvalidJson, e:
            return marshal({'error': {
                'message': utils.parse_error(e)
            }}, error_fields), 400
        db.session.commit()
        return marshal({'severity': severity}, one_severity_fields), 200

    @validate_client()
    @validate_id(True)
    def delete(self, client, id):

        severity = models.Severity.get(id, client.id)
        severity.is_visible = False
Exemple #34
0
    @validate_id(True)
    def put(self, client, id):

        severity = models.Severity.get(id, client.id)
        json = request.get_json(silent=True)
        logging.getLogger(__name__).debug('PUT severity: %s', json)

        try:
            validate(json, severity_input_format)
        except ValidationError, e:
            logging.debug(str(e))
            # TODO: generate good error messages
            return marshal({'error': {'message': utils.parse_error(e)}},
                           error_fields), 400

        mapper.fill_from_json(severity, json, mapper.severity_mapping)
        try:
            db_helper.manage_wordings(severity, json["wordings"])
        except exceptions.InvalidJson, e:
            return marshal({'error': {'message': utils.parse_error(e)}},
                           error_fields), 400
        db.session.commit()
        db.session.refresh(severity)
        return marshal({'severity': severity}, one_severity_fields), 200

    @validate_client()
    @validate_id(True)
    def delete(self, client, id):

        severity = models.Severity.get(id, client.id)
        severity.is_visible = False
Exemple #35
0
class Disruptions(flask_restful.Resource):
    def __init__(self):
        self.navitia = None
        self.parsers = {}
        self.parsers["get"] = reqparse.RequestParser()
        parser_get = self.parsers["get"]

        parser_get.add_argument("start_page", type=int, default=1)
        parser_get.add_argument("items_per_page", type=int, default=20)
        parser_get.add_argument("publication_status[]",
                                type=option_value(publication_status_values),
                                action="append",
                                default=publication_status_values)
        parser_get.add_argument("ends_after_date", type=utils.get_datetime),
        parser_get.add_argument("ends_before_date", type=utils.get_datetime),
        parser_get.add_argument("tag[]", type=utils.get_uuid, action="append")
        parser_get.add_argument("current_time", type=utils.get_datetime)
        parser_get.add_argument("uri", type=str)
        parser_get.add_argument("line_section",
                                type=types.boolean,
                                default=False)
        parser_get.add_argument("status[]",
                                type=option_value(disruption_status_values),
                                action="append",
                                default=disruption_status_values)
        parser_get.add_argument("depth", type=int, default=1)

    @validate_navitia()
    @validate_contributor()
    @manage_navitia_error()
    @validate_id()
    def get(self, contributor, navitia, id=None):
        self.navitia = navitia
        args = self.parsers['get'].parse_args()
        depth = args['depth']
        g.display_impacts = depth > 1

        if id:
            return self._get_disruption_by_id(id, contributor.id)
        else:
            return self._get_disruptions(contributor.id, args)

    def _get_disruption_by_id(self, id, contributor_id):
        return marshal(
            {'disruption': models.Disruption.get(id, contributor_id)},
            one_disruption_fields)

    def _get_disruptions(self, contributor_id, args):

        self._validate_arguments_for_disruption_list(args)
        g.current_time = args['current_time']
        page_index = args['start_page']
        items_per_page = args['items_per_page']
        publication_status = args['publication_status[]']
        ends_after_date = args['ends_after_date']
        ends_before_date = args['ends_before_date']
        tags = args['tag[]']
        uri = args['uri']
        line_section = args['line_section']
        statuses = args['status[]']

        result = models.Disruption.all_with_filter(
            page_index=page_index,
            items_per_page=items_per_page,
            contributor_id=contributor_id,
            publication_status=publication_status,
            ends_after_date=ends_after_date,
            ends_before_date=ends_before_date,
            tags=tags,
            uri=uri,
            line_section=line_section,
            statuses=statuses)

        response = {
            'disruptions': result.items,
            'meta': make_pager(result, 'disruption')
        }
        '''
        The purpose is to remove any database-loaded state from all current objects so that the next access of
        any attribute, or any query execution, will retrieve new state, freshening those objects which are still
        referenced outside of the session with the most recent available state.
        '''
        for o in result.items:
            models.db.session.expunge(o)
        return marshal(response, disruptions_fields)

    def _validate_arguments_for_disruption_list(self, args):
        if args['start_page'] == 0:
            abort(400, message="page_index argument value is not valid")

        if args['items_per_page'] == 0:
            abort(400, message="items_per_page argument value is not valid")

    def get_post_error_response_and_log(self, exception, status_code):
        return self.get_error_response_and_log('POST', exception, status_code)

    def get_put_error_response_and_log(self, exception, status_code):
        return self.get_error_response_and_log('PUT', exception, status_code)

    def get_error_response_and_log(self, method, exception, status_code):
        response_content = marshal(
            {'error': {
                'message': '{}'.format(exception.message)
            }}, error_fields)
        logging.getLogger(__name__).debug(
            "\nError REQUEST %s disruption: [X-Customer-Id:%s;X-Coverage:%s;X-Contributors:%s;Authorization:%s] with payload \n%s"
            + "\ngot RESPONSE with status %d:\n%s", method,
            request.headers.get('X-Customer-Id'),
            request.headers.get('X-Coverage'),
            request.headers.get('X-Contributors'),
            request.headers.get('Authorization'),
            json.dumps(request.get_json(silent=True)), status_code,
            json.dumps(response_content))
        return response_content

    @validate_navitia()
    @validate_client(True)
    @manage_navitia_error()
    def post(self, client, navitia):
        self.navitia = navitia
        json = request.get_json(silent=True)

        try:
            validate(json, disruptions_input_format)
        except ValidationError, e:
            response = self.get_post_error_response_and_log(e, 400)
            return response, 400
        disruption = models.Disruption()
        mapper.fill_from_json(disruption, json, mapper.disruption_mapping)

        # Use contributor_code present in the json to get contributor_id
        if 'contributor' in json:
            disruption.contributor = models.Contributor.get_or_create(
                json['contributor'])
        disruption.client = client

        # Add localization present in Json
        try:
            db_helper.manage_pt_object_without_line_section(
                self.navitia, disruption.localizations, 'localization', json)
        except exceptions.ObjectUnknown, e:
            response = self.get_post_error_response_and_log(e, 404)
            return response, 404
Exemple #36
0
def fill_and_add_line_section(navitia, impact_id, all_objects, pt_object_json):
    """
    :param impact_id: impact_id to construct uri of line_section object
    :param all_objects: dictionary of objects to be added in this session
    :param pt_object_json: Flux which contains json information of pt_object
    :return: pt_object and modify all_objects param
    """
    ptobject = models.PTobject()
    mapper.fill_from_json(ptobject, pt_object_json, mapper.object_mapping)

    #Here we treat all the objects in line_section like line, start_point, end_point
    line_section_json = pt_object_json['line_section']

    ptobject.uri = ":".join((line_section_json['line']['id'], ptobject.id))

    line_section = models.LineSection(ptobject.id)

    try:
        line_object = fill_and_get_pt_object(navitia, all_objects,
                                             line_section_json['line'])
    except exceptions.ObjectUnknown:
        raise exceptions.ObjectUnknown('{} {} doesn\'t exist'.format(
            line_section_json['line']['type'],
            line_section_json['line']['id']))

    line_section.line = line_object

    try:
        start_object = fill_and_get_pt_object(navitia, all_objects,
                                              line_section_json['start_point'])
    except exceptions.ObjectUnknown:
        raise exceptions.ObjectUnknown('{} {} doesn\'t exist'.format(
            line_section_json['line']['type'],
            line_section_json['line']['id']))
    line_section.start_point = start_object

    try:
        end_object = fill_and_get_pt_object(navitia, all_objects,
                                            line_section_json['end_point'])
    except exceptions.ObjectUnknown:
        raise exceptions.ObjectUnknown('{} {} doesn\'t exist'.format(
            line_section_json['line']['type'],
            line_section_json['line']['id']))
    line_section.end_point = end_object

    #Here we manage routes in line_section
    #"routes":[{"id":"route:MTD:9", "type": "route"}, {"id":"route:MTD:Nav23", "type": "route"}]
    if 'routes' in line_section_json:
        for route in line_section_json["routes"]:
            try:
                route_object = fill_and_get_pt_object(navitia, all_objects,
                                                      route, True)
                line_section.routes.append(route_object)
            except exceptions.ObjectUnknown:
                raise exceptions.ObjectUnknown('{} {} doesn\'t exist'.format(
                    route['type'], route['id']))

    #Here we manage via in line_section
    #"via":[{"id":"stop_area:MTD:9", "type": "stop_area"}, {"id":"stop_area:MTD:Nav23", "type": "stop_area"}]
    if 'via' in line_section_json:
        for via in line_section_json["via"]:
            try:
                via_object = fill_and_get_pt_object(navitia, all_objects, via,
                                                    True)
                line_section.via.append(via_object)
            except exceptions.ObjectUnknown:
                raise exceptions.ObjectUnknown('{} {} doesn\'t exist'.format(
                    via['type'], via['id']))

    #Fill sens from json
    if 'sens' in line_section_json:
        line_section.sens = line_section_json["sens"]

    #Fill wordings from json
    #"meta":[{"key":"direction", "value": "1234"}, {"key":"direction", "value": "5678"}]
    if 'metas' in line_section_json:
        try:
            metas = {}
            metas['wordings'] = line_section_json['metas']
            manage_wordings(line_section, metas)
        except exceptions.InvalidJson:
            raise

    ptobject.insert_line_section(line_section)
    return ptobject