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


Python resolver.Resolver类代码示例

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


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

示例1: create_or_update_record

def create_or_update_record(data, pid_type, id_key, minter):
    """Register a funder or grant."""
    resolver = Resolver(
        pid_type=pid_type, object_type='rec', getter=Record.get_record)

    try:
        pid, record = resolver.resolve(data[id_key])
        data_c = deepcopy(data)
        del data_c['remote_modified']
        record_c = deepcopy(data)
        del record_c['remote_modified']
        # All grants on OpenAIRE are modified periodically even if nothing
        # has changed. We need to check for actual differences in the metadata
        if data_c != record_c:
            record.update(data)
            record.commit()
            record_id = record.id
            db.session.commit()
            RecordIndexer().index_by_id(str(record_id))
    except PIDDoesNotExistError:
        record = Record.create(data)
        record_id = record.id
        minter(record.id, data)
        db.session.commit()
        RecordIndexer().index_by_id(str(record_id))
开发者ID:tiborsimko,项目名称:invenio-openaire,代码行数:25,代码来源:tasks.py

示例2: run

    def run(self, event):
        """Process the circulation event.

        This method builds the frame, fetching the item and calling *_run*
        in a nested transaction.
        """
        resolver = Resolver(pid_type='crcitm', object_type='rec',
                            getter=Item.get_record)
        _, item = resolver.resolve(event.payload['item_id'])

        self.circulation_event_schema.context['item'] = item

        data, errors = self.circulation_event_schema.load(event.payload)
        if errors:
            event.response_code = 400
            event.response = {'message': errors}
            return

        if data.get('dry_run'):
            event.response_code = 204
            return

        with db.session.begin_nested():
            data, _ = self.circulation_event_schema.dump(data)
            self._run(item, data)
            item.commit()
            RecordIndexer().index(item)
开发者ID:tiborsimko,项目名称:invenio-circulation,代码行数:27,代码来源:receivers.py

示例3: test_deposit_load_task

def test_deposit_load_task(dummy_location, deposit_dump, deposit_user,
                           deposit_record_pid):
    """Test the deposit loading task."""

    # Create a user and a record with PID corresponding with test deposit data
    assert RecordMetadata.query.count() == 1
    for dep in deposit_dump:
        load_deposit.delay(dep)
    assert RecordMetadata.query.count() == 2
    res = Resolver(pid_type='depid', object_type='rec',
                   getter=Record.get_record)
    dep_pid, dep_rec = res.resolve('1')
    assert '_deposit' in dep_rec
    assert '_files' in dep_rec
    sip = SIP.query.one()
    assert sip.user_id == deposit_user.id
    rsip = RecordSIP.query.one()
    assert rsip.pid_id == deposit_record_pid.id
    assert rsip.sip_id == sip.id

    # Test RecordsFiles API
    res = Resolver(pid_type='depid', object_type='rec',
                   getter=RecordFiles.get_record)
    dep_pid, dep_recbucket = res.resolve('1')
    files = list(dep_recbucket.files)
    assert files[0]['key'] == 'bazbar.pdf'
    assert files[0]['size'] == 12345
    assert files[0]['checksum'] == "00000000000000000000000000000000"
    assert files[0]['bucket']
    assert SIPFile.query.count() == 1
开发者ID:egabancho,项目名称:invenio-migrator,代码行数:30,代码来源:test_deposit_load.py

示例4: recid

def recid(pid_value=None):
    resolver = Resolver(
        pid_type='recid',
        object_type='rec',
        getter=Record.get_record)

    try:
        pid, record = resolver.resolve(pid_value)
    except:
        abort(404)

    is_public = ActionUsers.query.filter(
        ActionUsers.action == 'records-read',
        ActionUsers.user_id.is_(None)).first()

    permission_read_record = read_permission_factory(record)

    if is_public or permission_read_record.can():
        return record_view(pid_value,
                           resolver,
                           ['records/detail-'+record.get("collections", [""])[0]+'.html', 'records/detail.html'],
                           None,
                           default_view_method
                           )

    abort(403)
开发者ID:lukasheinrich,项目名称:analysis-preservation.cern.ch,代码行数:26,代码来源:views.py

示例5: test_deposit_load_task

def test_deposit_load_task(dummy_location, deposit_dump, deposit_user, deposit_record_pid):
    """Test the deposit loading task."""

    # Create a user and a record with PID corresponding with test deposit data
    assert RecordMetadata.query.count() == 1
    for dep in deposit_dump:
        load_deposit(dep)
    assert RecordMetadata.query.count() == 2
    res = Resolver(pid_type="depid", object_type="rec", getter=Record.get_record)
    dep_pid, dep_rec = res.resolve("1")
    assert "_deposit" in dep_rec
    assert "_files" in dep_rec
    sip = SIP.query.one()
    assert sip.user_id == deposit_user.id
    rsip = RecordSIP.query.one()
    assert rsip.pid_id == deposit_record_pid.id
    assert rsip.sip_id == sip.id

    # Test RecordsFiles API
    res = Resolver(pid_type="depid", object_type="rec", getter=RecordFiles.get_record)
    dep_pid, dep_recbucket = res.resolve("1")
    files = list(dep_recbucket.files)
    assert files[0]["key"] == "bazbar.pdf"
    assert files[0]["size"] == 12345
    assert files[0]["checksum"] == "md5:00000000000000000000000000000000"
    assert files[0]["bucket"]
    assert SIPFile.query.count() == 1
开发者ID:tiborsimko,项目名称:invenio-migrator,代码行数:27,代码来源:test_deposit_load.py

示例6: record_permissions

def record_permissions(pid_value=None):
    resolver = Resolver(
        pid_type='recid',
        object_type='rec',
        getter=Record.get_record)

    pid, record = resolver.resolve(pid_value)

    permissions = get_record_permissions(record.id)

    result = dict()
    result['permissions'] = []

    collab_egroups = current_app.config.get('CAP_COLLAB_EGROUPS')

    if record.get('experiment', None):
        result['collab_egroup'] = six.next(
            six.itervalues(collab_egroups.get(record['experiment']))
            )[0]

    for p in permissions:
        if isinstance(p, ActionUsers) and p.user:
            result['permissions'].append(
                {"action": p.action, "user": {"email": p.user.email}}
            )
        elif isinstance(p, ActionRoles) and p.role:
            result['permissions'].append(
                {"action": p.action, "user": {"email": p.role.name}}
            )

    resp = jsonify(**result)
    resp.status_code = 200
    return resp
开发者ID:lukasheinrich,项目名称:analysis-preservation.cern.ch,代码行数:33,代码来源:views.py

示例7: prepare_authors_data_for_pushing_to_orcid

def prepare_authors_data_for_pushing_to_orcid(json):
    """ Extracts the authors with valid orcid credentials from the list of authors
    of a given record in json format.
    """
    resolver = Resolver(pid_type='literature',
                        object_type='rec', getter=lambda x: x)
    record_id = resolver.resolve(json.get('control_number'))[
        0].object_uuid
    authors = get_orcid_valid_authors(json)
    token = None
    author_orcid = ''
    authors_with_orcid_credentials = []
    for author in authors:
        try:
            token, author_orcid = get_authors_credentials(author['_source'])
        except AttributeError:
            continue
        try:
            authors_with_orcid_credentials.append((InspireOrcidRecords.query.filter_by(
                orcid=author_orcid, record_id=record_id).first().put_code, token, author_orcid, record_id))
        except AttributeError:
            authors_with_orcid_credentials.append(
                ([], token, author_orcid, record_id))
            continue
    return authors_with_orcid_credentials
开发者ID:kaplun,项目名称:inspire-next,代码行数:25,代码来源:tasks.py

示例8: prepare_authors_data_for_pushing_to_orcid

def prepare_authors_data_for_pushing_to_orcid(data):
    """Extract the authors with valid ORCID credentials.

    It uses the list of authors from a given record in JSON format.
    """
    pid_type = current_app.config['ORCID_RECORDS_PID_TYPE']
    resolver = Resolver(pid_type=pid_type,
                        object_type='rec', getter=lambda x: x)
    fetcher_name = current_app.config['ORCID_RECORDS_PID_FETCHER']
    pid = current_pidstore.fetchers[fetcher_name](None, data)
    record_identifier = pid.pid_value
    record_id = resolver.resolve(record_identifier)[0].object_uuid
    authors = get_orcid_valid_authors(data)
    token = None
    author_orcid = ''
    authors_with_orcid_credentials = []
    for author in authors:
        try:
            token, author_orcid = get_authors_credentials(author)
        except AttributeError:
            continue
        try:
            authors_with_orcid_credentials.append((
                ORCIDRecords.query.filter_by(
                    orcid=author_orcid, record_id=record_id
                ).first().put_code,
                token, author_orcid, record_id
            ))
        except AttributeError:
            authors_with_orcid_credentials.append(
                ([], token, author_orcid, record_id))
            continue
    return authors_with_orcid_credentials
开发者ID:tiborsimko,项目名称:invenio-orcid,代码行数:33,代码来源:tasks.py

示例9: get_record_by_pid

 def get_record_by_pid(cls, pid, with_deleted=False):
     """Get ils record by pid value."""
     resolver = Resolver(
         pid_type=CIRCULATION_LOAN_PID_TYPE,
         object_type="rec",
         getter=cls.get_record,
     )
     persistent_identifier, record = resolver.resolve(str(pid))
     return record
开发者ID:inveniosoftware,项目名称:invenio-circulation,代码行数:9,代码来源:api.py

示例10: curate

def curate(community):
    """Index page with uploader and list of existing depositions.

    :param community_id: ID of the community to curate.
    """
    if request.method == 'POST':
        action = request.json.get('action')
        recid = request.json.get('recid')

        # 'recid' is mandatory
        if not recid:
            return jsonify({'status': 'danger', 'msg': _('Unknown record')})
        if action not in ['accept', 'reject', 'remove']:
            return jsonify({'status': 'danger', 'msg': _('Unknown action')})

        # Resolve recid to a Record
        resolver = Resolver(
            pid_type='recid', object_type='rec', getter=Record.get_record)
        pid, record = resolver.resolve(recid)

        action_name = ""
        status = "success"
        # Perform actions
        try:
            if action == "accept":
                community.accept_record(record)
                action_name = "added to"
            elif action == "reject":
                community.reject_record(record)
                action_name = "rejected from"
                status = "info"
            elif action == "remove":
                community.remove_record(record)
                action_name = "removed from"
                status = "info"
        except CommunitiesError:
            return jsonify({
                'status': 'danger',
                'msg': _('record not in the curation list,'
                         ' please refresh the page.')})

        record.commit()
        db.session.commit()
        RecordIndexer().index_by_id(record.id)
        title = ""
        if "title_statement" in record \
            and "title" in record["title_statement"]:
            title = record["title_statement"]["title"]
        message = _('The record '
            '"{}" has been {} the community.').format(title, action_name)
        return jsonify({'status': status, 'msg': message})

    ctx = {'community': community}
    return render_template(
        current_app.config['COMMUNITIES_CURATE_TEMPLATE'],
        **ctx
    )
开发者ID:tind,项目名称:invenio-communities,代码行数:57,代码来源:ui.py

示例11: fetch_published

    def fetch_published(self):
        """Return a tuple with PID and published record."""
        pid_type = self['_deposit']['pid']['type']
        pid_value = self['_deposit']['pid']['value']

        resolver = Resolver(
            pid_type=pid_type, object_type='rec',
            getter=partial(Record.get_record, with_deleted=True)
        )
        return resolver.resolve(pid_value)
开发者ID:nharraud,项目名称:invenio-deposit,代码行数:10,代码来源:api.py

示例12: get_record_by_id

def get_record_by_id(recid):
    try:
        resolver = Resolver(pid_type='recid', object_type='rec', getter=Record.get_record)
        pid, record = resolver.resolve(recid)
        return record
    except NoResultFound:
        current_app.logger.exception('No record found for recid {}'.format(recid))
        return None
    except PIDDoesNotExistError:
        current_app.logger.exception('The PID {0} does not exist'.format(recid))
        return None
开发者ID:HEPData,项目名称:hepdata3,代码行数:11,代码来源:common.py

示例13: fundertree2json

    def fundertree2json(self, tree, oai_id):
        """Convert OpenAIRE's funder XML to JSON."""
        try:
            tree = self.get_subtree(tree, 'fundingtree')[0]
        except IndexError:  # pragma: nocover
            pass

        funder_node = self.get_subtree(tree, 'funder')
        subfunder_node = self.get_subtree(tree, '//funding_level_0')

        funder_id = self.get_text_node(funder_node[0], './id') \
            if funder_node else None
        subfunder_id = self.get_text_node(subfunder_node[0], './id') \
            if subfunder_node else None
        funder_name = self.get_text_node(funder_node[0], './shortname') \
            if funder_node else ""
        subfunder_name = self.get_text_node(subfunder_node[0], './name') \
            if subfunder_node else ""

        # Try to resolve the subfunder first, on failure try to resolve the
        # main funder, on failure raise an error.
        funder_doi_url = None
        if subfunder_id:
            funder_doi_url = self.funder_resolver.resolve_by_id(subfunder_id)
        if not funder_doi_url:
            if funder_id:
                funder_doi_url = self.funder_resolver.resolve_by_id(funder_id)
        if not funder_doi_url:
            funder_doi_url = self.funder_resolver.resolve_by_oai_id(oai_id)
        if not funder_doi_url:
            raise FunderNotFoundError(oai_id, funder_id, subfunder_id)

        funder_doi = FundRefDOIResolver.strip_doi_host(funder_doi_url)
        if not funder_name:
            # Grab name from FundRef record.
            resolver = Resolver(
                pid_type='frdoi', object_type='rec', getter=Record.get_record)
            try:
                dummy_pid, funder_rec = resolver.resolve(funder_doi)
                funder_name = funder_rec['acronyms'][0]
            except PersistentIdentifierError:
                raise OAIRELoadingError(
                    "Please ensure that funders have been loaded prior to"
                    "loading grants. Could not resolve funder {0}".format(
                        funder_doi))

        return dict(
            doi=funder_doi,
            url=funder_doi_url,
            name=funder_name,
            program=subfunder_name,
        )
开发者ID:krzysztof,项目名称:invenio-openaire,代码行数:52,代码来源:loaders.py

示例14: test_permission

def test_permission(app):
    """Test permission control to records."""
    app.config.update(
        WTF_CSRF_ENABLED=False,
        SECRET_KEY='CHANGEME',
        SECURITY_PASSWORD_SALT='CHANGEME',
        # conftest switches off permission checking, so re-enable it for this
        # app.
        RECORDS_UI_DEFAULT_PERMISSION_FACTORY='helpers:'
                                              'only_authenticated_users',
    )
    Menu(app)
    InvenioRecordsUI(app)
    accounts = InvenioAccounts(app)
    app.register_blueprint(accounts_blueprint)
    InvenioAccess(app)
    setup_record_fixture(app)

    # Create admin
    with app.app_context():
        accounts.datastore.create_user(
            email='[email protected]',
            password=encrypt_password('123456'),
            active=True,
        )

        # Get record 1
        r = Resolver(pid_type='recid', object_type='rec',
                     getter=Record.get_record)
        dummy_pid, record = r.resolve('1')

        db.session.commit()

    with app.test_request_context():
        login_url = url_for('security.login')
        record_url = url_for('invenio_records_ui.recid', pid_value='1')

    # Access record 1 as admin
    with app.test_client() as client:
        res = client.get(record_url)
        assert res.status_code == 302
        res = client.post(login_url, data={
            'email': '[email protected]', 'password': '123456'})
        assert res.status_code == 302
        res = client.get(record_url)
        res.status_code == 200

    # Access record 1 as anonymous
    with app.test_client() as client:
        res = client.get(record_url)
        res.status_code == 403
开发者ID:hachreak,项目名称:invenio-records-ui,代码行数:51,代码来源:test_invenio_records_ui.py

示例15: create_or_update_record

def create_or_update_record(data, pid_type, id_key, minter):
    """Register a funder or grant."""
    resolver = Resolver(
        pid_type=pid_type, object_type='rec', getter=Record.get_record)

    try:
        pid, record = resolver.resolve(data[id_key])
        if data['remote_modified'] != record['remote_modified']:
            record.update(data)
            record.commit()
            db.session.commit()
    except PIDDoesNotExistError:
        record = Record.create(data)
        minter(record.id, data)
        db.session.commit()
开发者ID:SamiHiltunen,项目名称:invenio-openaire,代码行数:15,代码来源:tasks.py


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