Example #1
0
def _handle_export_request(request, items, callback=None):
    """Helper function to handle the export request. This function
    provides the required logic to show the export configuration dialog
    and returning the exported items. It is called when exporting a
    single item or when exporting multiple items in a bundle."""
    clazz = request.context.__model__
    renderer = ExportDialogRenderer(request, clazz)
    form = renderer.form
    if (request.method == 'POST'
       and is_confirmed(request)
       and form.validate(request.params)):
        # Setup exporter
        ef = form.data.get('format')
        if ef == "json":
            exporter = JSONExporter(clazz)
        elif ef == "csv":
            exporter = CSVExporter(clazz)
        elif ef == "xlsx":
            exporter = XLSXExporter(clazz)
        export = exporter.perform(items)
        # Build response
        resp = request.response
        resp.content_type = str('application/%s' % ef)
        resp.content_disposition = 'attachment; filename=export.%s' % ef
        resp.body = export
        return resp
    else:
        # FIXME: Get the ActionItem here and provide this in the Dialog to get
        # the translation working (torsten) <2013-07-10 09:32>
        rvalue = {}
        rvalue['dialog'] = renderer.render(items)
        return rvalue
Example #2
0
def handle_db_savedata_command(args):
    path = []
    path.append(args.config)
    session = get_session(os.path.join(*path))
    modul = get_modul(args.modul, session)
    data = session.query(modul).order_by(modul.id).all()

    if args.filter:
        # Build Baselist which is used for filtering.
        filter_stack = []
        listing = BaseList(modul, db=None, items=data)
        for f in args.filter.split(";"):
            filter_item = f.split(",")
            filter_item[2] = bool(filter_item[2])
            filter_stack.append(tuple(filter_item))
        try:
            listing.filter(filter_stack)
        except KeyError:
            print "Error while filtering."
            sys.exit(1)

        data = listing.items

    if args.export_config:
        with open(args.export_config, "r") as export_configfile:
            export_config = ExportConfiguration(json.load(export_configfile))
    else:
        export_config = ExportConfiguration(json.loads("[]"))

    if args.format == "json":
        exporter = JSONExporter(modul, serialized=False, config=export_config)
    else:
        exporter = CSVExporter(modul, serialized=False, config=export_config)
    print exporter.perform(data)
Example #3
0
def _handle_export_request(request, items, callback=None):
    """Helper function to handle the export request. This function
    provides the required logic to show the export configuration dialog
    and returning the exported items. It is called when exporting a
    single item or when exporting multiple items in a bundle."""
    clazz = request.context.__model__
    renderer = ExportDialogRenderer(request, clazz)
    form = renderer.form
    if (request.method == 'POST' and request.ringo.params.confirmed
            and form.validate(request.params)):
        # Setup exporter
        ef = form.data.get('format')
        if ef == "json":
            exporter = JSONExporter(clazz)
        elif ef == "csv":
            exporter = CSVExporter(clazz)
        elif ef == "xlsx":
            exporter = XLSXExporter(clazz)
        export = exporter.perform(items)
        # Build response
        resp = request.response
        resp.content_type = str('application/%s' % ef)
        resp.content_disposition = 'attachment; filename=export.%s' % ef
        resp.body = export
        return resp
    else:
        # FIXME: Get the ActionItem here and provide this in the Dialog to get
        # the translation working (torsten) <2013-07-10 09:32>
        rvalue = {}
        rvalue['dialog'] = renderer.render(items)
        return rvalue
Example #4
0
 def test_json_imexport(self):
     from ringo.lib.imexport import JSONExporter, JSONImporter
     item = self._load_item()
     exporter = JSONExporter(item.__class__)
     result = exporter.perform([item])
     imported = JSONImporter(item.__class__).perform(result)
     self.assertEqual(len(imported), 1)
     self.assertEqual(imported[0][1], "UPDATE")
Example #5
0
 def test_json(self):
     from ringo.lib.imexport import JSONExporter
     item = self._load_item()
     exporter = JSONExporter(item.__class__)
     result = exporter.perform([item])
     self.assertEqual(
         len(result),
         len('[{"str_repr": "%s|name", "description": "", "name": "modules", "label": "Modul", "default_gid": "", "id": "1", "label_plural": "Modules", "display": "admin-menu", "clazzpath": "ringo.model.modul.ModulItem", "uuid": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}]'
             ))
Example #6
0
 def __json__(self, request):
     rvalue = {}
     rvalue['success'] = self._success
     if isinstance(self._data, BaseItem):
         exporter = JSONExporter(self._data.__class__)
         self._data = exporter.perform([self._data])
     elif isinstance(self._data, BaseList):
         exporter = JSONExporter(self._data.__class__)
         self._data = exporter.perform(self._data.items)
     rvalue['data'] = self._data
     rvalue['params'] = self._params
     return rvalue
Example #7
0
def handle_db_savedata_command(args):
    path = []
    path.append(args.config)
    session = get_session(os.path.join(*path))
    modul_clazzpath = session.query(ModulItem).filter(ModulItem.name == args.modul).all()[0].clazzpath
    modul = dynamic_import(modul_clazzpath)
    if args.format == "json":
        exporter = JSONExporter(modul, serialized=False,
                                relations=args.include_relations)
    else:
        exporter = CSVExporter(modul, serialized=False,
                               relations=args.include_relations)
    print exporter.perform(session.query(modul)
                          .order_by(modul.id)
                          .all())
Example #8
0
 def __json__(self, request):
     rvalue = {}
     rvalue['success'] = self._success
     if isinstance(self._data, BaseItem):
         exporter = JSONExporter(self._data.__class__)
         self._data = exporter.perform([self._data])
     elif isinstance(self._data, BaseList):
         exporter = JSONExporter(self._data.__class__)
         self._data = exporter.perform(self._data.items)
     elif isinstance(self._data, list):
         if len(self._data) > 1 and isinstance(self._data[0], BaseItem):
             exporter = JSONExporter(self._data[0].__class__)
             self._data = exporter.perform(self._data)
     rvalue['data'] = self._data
     rvalue['params'] = self._params
     return rvalue
Example #9
0
def nested_import_items(nested_import_item):
    from ringo.lib.sql import DBSession
    from ringo.lib.imexport import JSONExporter
    from ringo.model.user import Usergroup, Role

    import_items = [nested_import_item, copy.deepcopy(nested_import_item)]
    import_items[1]["login"] = "******"

    # update-import relations of second item
    import_items[1]["usergroup"] = json.loads(
        JSONExporter(Usergroup, serialized=False).perform(
            DBSession.query(Usergroup).filter(
                Usergroup.name == 'users').one()))
    import_items[1]["roles"] = json.loads(
        JSONExporter(Role,
                     serialized=False).perform(DBSession.query(Role).all()))

    # Identifiable related object can appear multiple times
    import_items[0]["roles"][0]["uuid"] = str(uuid.uuid4())
    import_items[1]["roles"].append(import_items[0]["roles"][0])

    return import_items
Example #10
0
def test_item_export(expected_item):
    from ringo.model.base import BaseFactory
    from ringo.model.user import User
    from ringo.lib.imexport import JSONExporter

    user = BaseFactory(User).load(1)
    export = json.loads(JSONExporter(User, serialized=False).perform(user))

    assert sorted(export.keys()) == sorted(expected_item.keys())

    for key in [
            key for key in expected_item.keys()
            if key not in ["uuid", "last_login", "password"]
    ]:
        assert export[key] == expected_item[key]
Example #11
0
 def test_json(self):
     from ringo.lib.imexport import JSONExporter
     item = self._load_item()
     exporter = JSONExporter(item.__class__)
     result = exporter.perform([item])
     self.assertEqual(len(result), len('[{"str_repr": "%s|name", "description": "", "name": "modules", "label": "Modul", "default_gid": "", "id": "1", "label_plural": "Modules", "display": "admin-menu", "clazzpath": "ringo.model.modul.ModulItem", "uuid": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}]'))