当前位置: 首页>>代码示例>>Python>>正文


Python api.Record类代码示例

本文整理汇总了Python中invenio.modules.records.api.Record的典型用法代码示例。如果您正苦于以下问题:Python Record类的具体用法?Python Record怎么用?Python Record使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Record类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_json_for_ld

    def test_json_for_ld(self):
        from invenio.modules.records.api import Record
        r = Record.create({'title': 'Test'}, 'json')

        import copy
        r = Record(json=copy.copy(test_record), master_format='marc')
        r.produce('json_for_ld')
开发者ID:bruno314,项目名称:zenodo,代码行数:7,代码来源:test_jsonext.py

示例2: test_subjects_gnd

    def test_subjects_gnd(self):
        """Test contributor rules."""
        from invenio.modules.records.api import Record
        r = Record.create({'subjects': [
                {'term': 'Smith, John',
                 'identifier': 'gnd:118604740',
                 'scheme': 'gnd'},
            ]}, 'json')

        # Test that "gnd:" is not added in MARC
        print(r.produce('json_for_marc'))
        assert {'6501_a': 'Smith, John', '6501_0': '(gnd)118604740'} \
            in r.produce('json_for_marc')

        r = Record.create(
            '<record>'
            '<datafield tag="650" ind1="1" ind2=" ">'
            '<subfield code="a">Smith, John</subfield>'
            '<subfield code="0">(gnd)118604740</subfield>'
            '</datafield>'
            '</record>',
            master_format='marc'
        )

        # Test that "gnd:" is added back in JSON
        assert r['subjects'] == [{
            'identifier': 'gnd:118604740',
            'scheme': 'gnd',
            'term': 'Smith, John'}]
开发者ID:bruno314,项目名称:zenodo,代码行数:29,代码来源:test_jsonext.py

示例3: test_gnd

    def test_gnd(self):
        """Test contributor rules."""
        from invenio.modules.records.api import Record
        r = Record.create({'contributors': [
                {'name': 'Smith, John',
                 'gnd': 'gnd:118604740',
                 'type': 'DataCurator'},
            ]}, 'json')

        print r.produce('json_for_marc')
        # Test that "gnd:" is not added in MARC
        assert {'700__0': ['(gnd)118604740', None],
                '700__4': 'cur',
                '700__a': 'Smith, John'} \
            in r.produce('json_for_marc')

        r = Record.create(
            '<record>'
            '<datafield tag="700" ind1=" " ind2=" ">'
            '<subfield code="4">cur</subfield>'
            '<subfield code="a">Smith, John</subfield>'
            '<subfield code="0">(gnd)118604740</subfield>'
            '</datafield>'
            '</record>',
            master_format='marc'
        )

        # Test that "gnd:" is added back in JSON
        print r['contributors']
        assert r['contributors'] == [{
            'gnd': 'gnd:118604740',
            'name': 'Smith, John',
            'orcid': '',
            'type': 'DataCurator'
        }]
开发者ID:bruno314,项目名称:zenodo,代码行数:35,代码来源:test_jsonext.py

示例4: test_marc_export

    def test_marc_export(self):
        from invenio.modules.records.api import Record
        from invenio.legacy.bibrecord import create_record, record_xml_output

        rec = Record(json=test_record, master_format='marc')

        # Needed to properly set authors when generating MARC
        first = rec['authors'][0]
        additional = rec['authors'][1:]
        rec['_first_author'] = first
        rec['_additional_authors'] = additional

        output_marc = record_xml_output(
            create_record(rec.legacy_export_as_marc())[0]
        )
        try:
            self.assertEqual(test_marc, output_marc)
        except AssertionError:
            # Print diff in case of errors.
            import difflib
            diff = "".join(difflib.unified_diff(
                test_marc.splitlines(1),
                output_marc.splitlines(1)
            ))
            raise AssertionError(diff)

        form_json = rec.produce('json_for_form')
        for k, v in test_form_json.items():
            self.assertEqual(form_json[k], test_form_json[k])
开发者ID:SDSG-Invenio,项目名称:zenodo,代码行数:29,代码来源:test_jsonext.py

示例5: test_types

    def test_types(self):
        """Test upload_type rules."""
        from invenio.modules.records.api import Record

        for t in cfg['UPLOAD_TYPES']:
            if t['subtypes']:
                for st in t['subtypes']:
                    r = Record.create(
                        '<record><datafield tag="980" ind1=" " ind2=" ">'
                        '<subfield code="b">{1}</subfield>'
                        '<subfield code="a">{0}</subfield>'
                        '</datafield></record>'.format(t['type'], st['type']),
                        master_format='marc'
                    )
                    assert r['upload_type'] == {"type": t['type'],
                                                "subtype": st['type']}
                    assert len(r.get('collections', [])) == 0
            else:
                r = Record.create(
                    '<record><datafield tag="980" ind1=" " ind2=" ">'
                    '<subfield code="a">{0}</subfield>'
                    '</datafield></record>'.format(t['type']),
                    master_format='marc'
                )
                assert r['upload_type'] == {"type": t['type']}
                assert len(r.get('collections', [])) == 0
开发者ID:bruno314,项目名称:zenodo,代码行数:26,代码来源:test_jsonext.py

示例6: test_jsonalchemy_toint_usage

    def test_jsonalchemy_toint_usage(self):
        """Test the usage of ``to_int`` function in real life example.

        The ``test_toint`` model contains a field which contains an integer
        subfield. Whenever the record is obtained from ``MARCXML``, the
        string in mentioned subfield has to be converted to an integer.

        However, JSONAlchemy fills every absent subfield with a ``None`` value.
        If the record is not provided with the integer subfield and the
        built-in ``int`` function is used, the code will crash.

        The ``to_int`` function used inside definition of ``test_toint`` field
        prevents it. Here the unprovided subfield is ``999__a``.
        """
        xml = '<collection><record><datafield tag="999" ind1="" ind2= "">' \
              '<subfield code="b">Value</subfield></datafield></record>' \
              '</collection>'
        from invenio.modules.records.api import Record
        simple_record = Record.create(xml, master_format='marc',
                                      model="test_toint",
                                      namespace='testsuite')

        self.assertEqual(len(simple_record.__dict__['_dict']['__meta_metadata__']['__errors__']), 0)

        # Check if it works when the value is provided.
        xml = '<collection><record><datafield tag="999" ind1="" ind2= "">' \
              '<subfield code="a">9999</subfield>' \
              '<subfield code="b">Value</subfield></datafield></record>' \
              '</collection>'

        simple_record = Record.create(xml, master_format='marc',
                                      model="test_toint",
                                      namespace='testsuite')
        self.assertEqual(simple_record['with_integers'][0]['some_int'], 9999)
开发者ID:SCOAP3,项目名称:invenio,代码行数:34,代码来源:test_functions.py

示例7: formatter

    def formatter(bwo, **kwargs):
        """Nicely format the record."""
        from pprint import pformat
        from invenio.modules.records.api import Record

        data = bwo.get_data()
        if not data:
            return ''

        formatter = kwargs.get("formatter", None)
        of = kwargs.get("of", None)
        if formatter:
            # A separate formatter is supplied
            return formatter(data)

        if isinstance(data, collections.Mapping):
            # Dicts are cool on its own, but maybe its SmartJson (record)
            try:
                data = Record(data.dumps()).legacy_export_as_marc()
            except (TypeError, KeyError):
                pass

        if isinstance(data, string_types):
            # We can try formatter!
            # If already XML, format_record does not like it.
            if of and of != 'xm':
                try:
                    from invenio.modules.formatter import format_record
                    formatted_data = format_record(
                        recID=None,
                        of=of,
                        xml_record=data
                    )
                except TypeError:
                    # Wrong kind of type
                    pass
            else:
                # So, XML then
                from xml.dom.minidom import parseString

                try:
                    unpretty_data = parseString(data)
                    formatted_data = unpretty_data.toprettyxml()
                except TypeError:
                    # Probably not proper XML string then
                    return "Data cannot be parsed: %s" % (data,)
                except Exception:
                    # Just return raw string
                    pass

        if not formatted_data:
            formatted_data = data

        if isinstance(formatted_data, dict):
            formatted_data = pformat(formatted_data)
        return formatted_data
开发者ID:SCOAP3,项目名称:invenio,代码行数:56,代码来源:definitions.py

示例8: test_marc_export

    def test_marc_export(self):
        from invenio.modules.records.api import Record
        from invenio.legacy.bibrecord import create_record

        r = Record(json=test_record, master_format='marc')

        self.assertEqual(
            r.legacy_create_recstruct(),
            create_record(test_marc)[0],
        )
开发者ID:egabancho,项目名称:zenodo,代码行数:10,代码来源:test_jsonext.py

示例9: formatter

    def formatter(bwo, **kwargs):
        """Return a formatted version of the data."""
        from invenio.modules.formatter.engine import format_record

        data = bwo.get_data()
        if not data:
            return ''
        formatter = kwargs.get("formatter", None)
        format = kwargs.get("format", None)
        if formatter:
            # A seperate formatter is supplied
            return formatter(data)
        from invenio.modules.records.api import Record
        if isinstance(data, collections.Mapping):
            # Dicts are cool on its own, but maybe its SmartJson (record)
            try:
                data = Record(data.dumps()).legacy_export_as_marc()
            except (TypeError, KeyError):
                # Maybe not, submission?
                return data

        if isinstance(data, string_types):
            # Its a string type, lets try to convert
            if format:
                # We can try formatter!
                # If already XML, format_record does not like it.
                if format != 'xm':
                    try:
                        return format_record(recID=None,
                                             of=format,
                                             xml_record=data)
                    except TypeError:
                        # Wrong kind of type
                        pass
                else:
                    # So, XML then
                    from xml.dom.minidom import parseString

                    try:
                        pretty_data = parseString(data)
                        return pretty_data.toprettyxml()
                    except TypeError:
                        # Probably not proper XML string then
                        return "Data cannot be parsed: %s" % (data,)
                    except Exception:
                        # Some other parsing error
                        pass

            # Just return raw string
            return data
        if isinstance(data, set):
            return list(data)
        # Not any of the above types. How juicy!
        return data
开发者ID:GiorgosPa,项目名称:inspire-next,代码行数:54,代码来源:process_record_arxiv.py

示例10: test_json_for_ld

    def test_json_for_ld(self):
        from invenio.modules.records.api import Record

        r = Record.create({"title": "Test"}, "json")

        import copy

        r = Record(json=copy.copy(test_record), master_format="marc")

        ld = r.produce("json_for_ld")
        print(ld)
开发者ID:LibrarPotter,项目名称:zenodo,代码行数:11,代码来源:test_jsonext.py

示例11: test_json_for_form

    def test_json_for_form(self):
        from invenio.modules.records.api import Record
        r = Record.create({'title': 'Test'}, 'json')
        assert r.produce('json_for_form')['title'] == 'Test'
        assert {'245__a': 'Test'} in r.produce('json_for_marc')

        import copy
        r = Record(json=copy.copy(test_record), master_format='marc')

        form_json = r.produce('json_for_form')
        for k, v in test_form_json.items():
            self.assertEqual(form_json[k], test_form_json[k])
开发者ID:SDSG-Invenio,项目名称:zenodo,代码行数:12,代码来源:test_jsonext.py

示例12: test_marc_export

    def test_marc_export(self):
        from invenio.modules.records.api import Record
        #from invenio.legacy.bibrecord import create_record

        r = Record(json=test_record, master_format='marc')
        # self.assertEqual(
        #     r.legacy_create_recstruct(),
        #     create_record(test_marc)[0],
        # )

        form_json = r.produce('json_for_form')
        for k, v in test_form_json.items():
            self.assertEqual(form_json[k], test_form_json[k])
开发者ID:suso2,项目名称:zenodo,代码行数:13,代码来源:test_jsonext.py

示例13: test_lossless_marc_import_export

    def test_lossless_marc_import_export(self):
        from invenio.modules.records.api import Record

        r = Record.create(test_marc, master_format="marc").dumps()

        for k in test_record.keys():
            self.assertEqual(test_record[k], r[k])
开发者ID:LibrarPotter,项目名称:zenodo,代码行数:7,代码来源:test_jsonext.py

示例14: test_jsonalchemy_tooldvalue

    def test_jsonalchemy_tooldvalue(self):
        """Test behaviour of ``set_default_value``.

        In this example, the value provided to the reader in ``d`` subfield
        is in wrong format. However, the behaviour of ``JSONAlchemy`` in such
        case is to skip the value.

        Given the below value of the subfield, the module crashes in
        ``set_default_value``. The error has been caught.
        What is the reason behind the mentioned behaviour needs further
        investigation.
        """
        from invenio.modules.records.api import Record

        # Check if it works when the value is provided.
        xml = '''<collection><record><datafield tag="100" ind1=" " ind2=" ">
              <subfield code="a">Guy, Bobby</subfield>
              <subfield code="d">I like trains</subfield>
              <subfield code="g">ACTIVE</subfield>
              <subfield code="q">Bobby Guy</subfield>
              </datafield></record></collection>'''

        simple_record = Record.create(xml, master_format='marc',
                                      model="test_oldvalue",
                                      namespace='testsuite')
        self.assertEqual(simple_record['dates']['birth'], None)
开发者ID:SCOAP3,项目名称:invenio,代码行数:26,代码来源:test_oldvalue.py

示例15: update

def update(recid):
    """View for INSPIRE author update form."""
    # Store referrer in session for later redirection to original page
    session["author_update_referrer"] = request.referrer
    data = {}
    if recid:
        try:
            url = os.path.join(cfg["AUTHORS_UPDATE_BASE_URL"], "record",
                               str(recid), "export", "xm")
            xml = requests.get(url)
            data = Record.create(xml.text.encode("utf-8"), 'marc',
                                 model='author').produce("json_for_form")
            convert_for_form(data)
        except requests.exceptions.RequestException:
            pass
        data["recid"] = recid
    else:
        return redirect(url_for("inspire_authors.new"))
    form = AuthorUpdateForm(data=data)
    ctx = {
        "action": url_for('.submitupdate'),
        "name": "authorUpdateForm",
        "id": "authorUpdateForm",
    }

    return render_template('authors/forms/update_form.html', form=form, **ctx)
开发者ID:Lilykos,项目名称:inspire-next,代码行数:26,代码来源:views.py


注:本文中的invenio.modules.records.api.Record类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。