示例#1
0
def json_doc_to_xml(json_obj, lang='en', custom_namespace=None):
    """Converts a Open511 JSON document to XML.

    lang: the appropriate language code

    Takes a dict deserialized from JSON, returns an lxml Element.

    Accepts only the full root-level JSON object from an Open511 response."""
    if 'meta' not in json_obj:
        raise Exception(
            "This function requires a conforming Open511 JSON document with a 'meta' section."
        )
    json_obj = dict(json_obj)
    meta = json_obj.pop('meta')
    elem = get_base_open511_element(lang=lang, version=meta.pop('version'))

    pagination = json_obj.pop('pagination', None)

    json_struct_to_xml(json_obj, elem, custom_namespace=custom_namespace)

    if pagination:
        elem.append(
            json_struct_to_xml(pagination,
                               'pagination',
                               custom_namespace=custom_namespace))

    json_struct_to_xml(meta, elem)

    return elem
示例#2
0
def kml_file_to_open511_element(filename):
    """Transform a Montreal KML file, at filename, into an Element
    for the top-level <open511> element."""
    ds = DataSource(filename)
    base_element = get_base_open511_element(lang='fr')
    for layer in ds:
        for feature in layer:
            base_element.append(feature_to_open511_element(feature))
    return base_element
示例#3
0
 def validate_xml(self):
     # First, create a full XML doc to validate
     doc = get_base_open511_element()
     el = self.get_validation_xml() if hasattr(self, 'get_validation_xml') else self.xml_elem
     container = etree.Element(pluralize(el.tag))
     container.append(el)
     doc.append(container)
     doc.set('version', settings.OPEN511_DEFAULT_VERSION)
     # Then run it through schema
     validate(doc)
def main():

    logging.basicConfig()

    base = get_base_open511_element(lang="fr")

    for summary in chain(
        get_list_of_chantiers(action="EntraveMajeure"), get_list_of_chantiers(action="EntraveMineure")
    ):
        rdev = get_roadevent_from_summary(summary)
        base.append(rdev)

    print etree.tostring(base, pretty_print=True)
示例#5
0
def validate_single_item(el, version=DEFAULT_VERSION, ignore_missing_urls=False):
    doc = get_base_open511_element(version=version)

    if ignore_missing_urls:
        el = deepcopy(el)
        if not el.xpath('link[rel=self]'):
            el.append(_make_link('self', '/fake/data'))
        if not el.xpath('link[rel=jurisdiction]'):
            el.append(_make_link('jurisdiction', 'http://example.com/fake/jurisdiction'))

    container = etree.Element(pluralize(el.tag))
    container.append(el)
    doc.append(container)
    return validate(doc)
示例#6
0
 def get_xml_doc(self, request, result):
     base = get_base_open511_element(base=settings.OPEN511_BASE_URL)
     if isinstance(result.resource, (list, tuple)):
         base.extend(result.resource)
     else:
         base.append(result.resource)
     if getattr(result, 'pagination', None):
         base.append(result.pagination_to_xml())
     metadata = self.get_response_metadata(request)
     base.set('version', metadata['version'])
     # base.append(make_link('self', metadata['url']))
     # if 'up_url' in metadata:
     #     base.append(make_link('up', metadata['up_url']))
     return base
def main():

    logging.basicConfig()

    base = get_base_open511_element(lang='fr')
    events = E.events()

    for summary in chain(
            get_list_of_chantiers(action='Chantier.Majeur'),
            get_list_of_chantiers(action='Chantier.Mineur')):
        rdev = get_roadevent_from_summary(summary)
        events.append(rdev)
    base.append(events)

    print(etree.tostring(base, pretty_print=True).decode('utf8'))
示例#8
0
def geotrafic_to_xml(xml_string, db_conn):
    """
    Converts a string containing a Geo-Trafic XML document into an lxml Element
    containing an open511 document.
    """
    xml_string = xml_string.replace('<Events xmlns="GeoTrafic">', '<Events>') # simpler
    srcdoc = etree.fromstring(xml_string)
    srcevents = srcdoc.xpath('Event')
    root = get_base_open511_element(lang='fr', version='v1')
    events = etree.Element('events')
    root.append(events)
    for srcevent in srcevents:
        try:
            ev = convert_event(srcevent, db_conn)
            events.append(ev)
        except:
            logger.exception("Error processing event %s" % srcevent.findtext('event-sid'))
            continue
    return root
示例#9
0
文件: converter.py 项目: Axaub/mtl511
def geotrafic_to_xml(xml_string, db_conn):
    """
    Converts a string containing a Geo-Trafic XML document into an lxml Element
    containing an open511 document.
    """
    xml_string = xml_string.replace('<Events xmlns="GeoTrafic">',
                                    '<Events>')  # simpler
    srcdoc = etree.fromstring(xml_string)
    srcevents = srcdoc.xpath('Event')
    root = get_base_open511_element(lang='fr', version='v1')
    events = etree.Element('events')
    root.append(events)
    for srcevent in srcevents:
        try:
            ev = convert_event(srcevent, db_conn)
            events.append(ev)
        except:
            logger.exception("Error processing event %s" %
                             srcevent.findtext('event-sid'))
            continue
    return root
示例#10
0
def main():

    logging.basicConfig()

    base = get_base_open511_element(lang='fr')
    cameras = E.cameras()
    base.append(cameras)

    english_names = get_english_names()

    for camera_info in get_list_of_cameras():
        camera = E.camera(
            E.id(JURISDICTION_ID + '/' + unicode(camera_info['id'])),
            E.name(camera_info['info'])
        )
        if english_names[camera_info['id']]:
            ename = E.name(english_names[camera_info['id']])
            ename.set(XML_LANG, 'en')
            camera.append(ename)

        camera.append(
            E.geography(
                geom_to_xml_element(
                    Point(float(camera_info['lng']), float(camera_info['lat']), srid=4326)
                )
            )
        )

        try:
            camera.append(
                E.media_files(
                    E.link(rel="related", href=get_image_url(camera_info['id']), type="image/jpeg")
                )
            )
        except Exception as e:
            logger.exception("Couldn't fetch image for camera #%s" % camera_info['id'])
            continue
        cameras.append(camera)

    print etree.tostring(base, pretty_print=True)
示例#11
0
文件: o5xml.py 项目: open511/open511
def json_doc_to_xml(json_obj, lang='en', custom_namespace=None):
    """Converts a Open511 JSON document to XML.

    lang: the appropriate language code

    Takes a dict deserialized from JSON, returns an lxml Element.

    Accepts only the full root-level JSON object from an Open511 response."""
    if 'meta' not in json_obj:
        raise Exception("This function requires a conforming Open511 JSON document with a 'meta' section.")
    json_obj = dict(json_obj)
    meta = json_obj.pop('meta')
    elem = get_base_open511_element(lang=lang, version=meta.pop('version'))

    pagination = json_obj.pop('pagination', None)

    json_struct_to_xml(json_obj, elem, custom_namespace=custom_namespace)

    if pagination:
        elem.append(json_struct_to_xml(pagination, 'pagination', custom_namespace=custom_namespace))

    json_struct_to_xml(meta, elem)

    return elem