本文整理汇总了Python中invenio_records.Record.get_record方法的典型用法代码示例。如果您正苦于以下问题:Python Record.get_record方法的具体用法?Python Record.get_record怎么用?Python Record.get_record使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类invenio_records.Record
的用法示例。
在下文中一共展示了Record.get_record方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_record_update_mutable
# 需要导入模块: from invenio_records import Record [as 别名]
# 或者: from invenio_records.Record import get_record [as 别名]
def test_record_update_mutable(app, db):
"""Test updating mutables in a record."""
recid = uuid.UUID("262d2748-ba41-456f-a844-4d043a419a6f")
# Create a new record with two mutables, a list and a dict
rec = Record.create({"title": "Title", "list": ["foo"], "dict": {"moo": "boo"}}, id_=recid)
# Make sure mutables are there before and after commit
assert rec == {"title": "Title", "list": ["foo"], "dict": {"moo": "boo"}}
db.session.commit()
db.session.expunge_all()
rec = Record.get_record(recid)
assert rec == {"title": "Title", "list": ["foo"], "dict": {"moo": "boo"}}
# Set the mutables under key
rec["list"] = ["bar"]
rec["dict"] = {"eggs": "bacon"}
rec.commit()
# Make sure it commits to DB
assert rec == {"title": "Title", "list": ["bar"], "dict": {"eggs": "bacon"}}
db.session.commit()
db.session.expunge_all()
rec = Record.get_record(recid)
assert rec == {"title": "Title", "list": ["bar"], "dict": {"eggs": "bacon"}}
# Update the mutables under key
rec["list"].append("spam")
rec["dict"]["ham"] = "chicken"
rec.commit()
# Make sure it commits to DB
assert rec == {"title": "Title", "list": ["bar", "spam"], "dict": {"eggs": "bacon", "ham": "chicken"}}
db.session.commit()
db.session.expunge_all()
rec = Record.get_record(recid)
assert rec == {"title": "Title", "list": ["bar", "spam"], "dict": {"eggs": "bacon", "ham": "chicken"}}
示例2: test_valid_delete
# 需要导入模块: from invenio_records import Record [as 别名]
# 或者: from invenio_records.Record import get_record [as 别名]
def test_valid_delete(app):
"""Test VALID record delete request (DELETE .../records/<record_id>)."""
with app.app_context():
# create the record using the internal API
pid, record = create_record(test_data)
with app.test_client() as client:
headers = [('Accept', 'application/json')]
res = client.delete(url_for('invenio_records_rest.recid_item',
pid_value=pid.pid_value),
headers=headers)
assert res.status_code == 204
# check database state
with pytest.raises(NoResultFound):
Record.get_record(record.id)
assert pid.is_deleted()
# check that DELETE with non JSON accepted format will work
# as it returns nothing
pid, record = create_record(test_data)
headers = [('Accept', 'video/mp4')]
res = client.delete(url_for('invenio_records_rest.recid_item',
pid_value=pid.pid_value),
headers=headers)
assert res.status_code == 204
示例3: test_db
# 需要导入模块: from invenio_records import Record [as 别名]
# 或者: from invenio_records.Record import get_record [as 别名]
def test_db():
"""Test database backend."""
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get(
'SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'
)
FlaskCLI(app)
InvenioDB(app)
InvenioRecords(app)
with app.app_context():
create_database(db.engine.url)
db.create_all()
assert len(db.metadata.tables) == 3
data = {'title': 'Test'}
from invenio_records.models import RecordMetadata as RM
# Create a record
with app.app_context():
assert RM.query.count() == 0
record_uuid = Record.create(data).id
db.session.commit()
assert RM.query.count() == 1
db.session.commit()
# Retrieve created record
with app.app_context():
record = Record.get_record(record_uuid)
assert record.dumps() == data
with pytest.raises(NoResultFound):
Record.get_record(uuid.uuid4())
record['field'] = True
record = record.patch([
{'op': 'add', 'path': '/hello', 'value': ['world']}
])
assert record['hello'] == ['world']
record.commit()
db.session.commit()
with app.app_context():
record2 = Record.get_record(record_uuid)
assert record2.model.version_id == 2
assert record2['field']
assert record2['hello'] == ['world']
db.session.commit()
# Cannot commit record without model (i.e. Record.create_record)
with app.app_context():
record3 = Record({'title': 'Not possible'})
with pytest.raises(RecordNotCommitableError):
record3.commit()
with app.app_context():
db.drop_all()
drop_database(db.engine.url)
示例4: test_change_record_community
# 需要导入模块: from invenio_records import Record [as 别名]
# 或者: from invenio_records.Record import get_record [as 别名]
def test_change_record_community(app, test_records):
"""Test updating the community field fails."""
with app.app_context():
record = Record.get_record(test_records[0].record_id)
del record['community']
with pytest.raises(AlteredRecordError):
record.commit()
with app.app_context():
record = Record.get_record(test_records[0].record_id)
record['community'] = str(uuid.uuid4())
with pytest.raises(AlteredRecordError):
record.commit()
示例5: test_record_patch_immutable_fields
# 需要导入模块: from invenio_records import Record [as 别名]
# 或者: from invenio_records.Record import get_record [as 别名]
def test_record_patch_immutable_fields(app, test_records, test_users,
login_user):
"""Test invalid modification of record draft with HTTP PATCH."""
with app.app_context():
record = Record.get_record(test_records[0].record_id)
with app.test_client() as client:
user = test_users['admin']
login_user(user, client)
headers = [('Content-Type', 'application/json-patch+json'),
('Accept', 'application/json')]
for path in IMMUTABLE_PATHS:
for command in [
{"op": "replace", "path": path, "value": ""},
{"op": "remove", "path": path},
{"op": "add", "path": path, "value": ""},
{"op": "copy", "from": "/title", "path": path, "value": ""},
{"op": "move", "from": "/title", "path": path, "value": ""},
]:
draft_patch_res = client.patch(
url_for('b2share_records_rest.b2rec_item',
pid_value=test_records[0].pid),
data=json.dumps([command]),
headers=headers)
assert draft_patch_res.status_code == 400
data = json.loads(draft_patch_res.get_data(as_text=True))
assert data['errors'][0]['message'] == \
'The field "{}" is immutable.'.format(path)
示例6: test_valid_put
# 需要导入模块: from invenio_records import Record [as 别名]
# 或者: from invenio_records.Record import get_record [as 别名]
def test_valid_put(app):
"""Test VALID record patch request (PATCH .../records/<record_id>)."""
with app.app_context():
InvenioRecordsREST(app)
# create the record using the internal API
internal_record = Record.create(test_data)
with app.test_client() as client:
headers = [('Content-Type', 'application/json'),
('Accept', 'application/json')]
res = client.put(url_for(blueprint.name + '.' +
RecordResource.view_name,
record_id=internal_record.model.id),
data=json.dumps(test_data_patched),
headers=headers)
assert res.status_code == 200
# check that the returned record matches the given data
response_data = json.loads(res.get_data(as_text=True))
assert response_data['data'] == test_data_patched
# check that an internal record returned id and that it contains
# the same data
assert 'id' in response_data.keys()
internal_record = Record.get_record(response_data['id'])
assert internal_record == response_data['data']
# check that the returned self link returns the same data
subtest_self_link(response_data, res.headers, client)
示例7: test_change_record_schema_fails
# 需要导入模块: from invenio_records import Record [as 别名]
# 或者: from invenio_records.Record import get_record [as 别名]
def test_change_record_schema_fails(app, test_records):
"""Test updating the $schema field fails."""
with app.app_context():
record = Record.get_record(test_records[0].record_id)
del record['$schema']
with pytest.raises(AlteredRecordError):
record.commit()
示例8: record_upsert
# 需要导入模块: from invenio_records import Record [as 别名]
# 或者: from invenio_records.Record import get_record [as 别名]
def record_upsert(json):
"""Insert or update a record."""
control_number = json.get('control_number', json.get('recid'))
if control_number:
control_number = int(control_number)
pid_type = InspireRecordIdProvider.schema_to_pid_type(json['$schema'])
try:
pid = PersistentIdentifier.get(pid_type, control_number)
record = Record.get_record(pid.object_uuid)
record.update(json)
record.commit()
except PIDDoesNotExistError:
record = Record.create(json, id_=None)
# Create persistent identifier.
inspire_recid_minter(str(record.id), json)
if json.get('deleted'):
new_recid = get_recid_from_ref(json.get('new_record'))
if new_recid:
merged_record = get_db_record(pid_type, new_recid)
merge_pidstores_of_two_merged_records(merged_record.id, record.id)
else:
soft_delete_pidstore_for_record(record.id)
return record
示例9: _get_record_from_workflow
# 需要导入模块: from invenio_records import Record [as 别名]
# 或者: from invenio_records.Record import get_record [as 别名]
def _get_record_from_workflow(workflow):
assert len(workflow.objects) == 1
workflow_object = workflow.objects[0]
recid = workflow_object.data['control_number']
pid = PersistentIdentifier.get('recid', recid)
return Record.get_record(pid.object_uuid)
示例10: update_authors_recid
# 需要导入模块: from invenio_records import Record [as 别名]
# 或者: from invenio_records.Record import get_record [as 别名]
def update_authors_recid(record_id, uuid, profile_recid):
"""Update author profile for a given signature.
The method receives UUIDs representing record and signature
respectively together with an author profile recid.
The new recid will be placed in the signature with the given
UUID.
:param record_id:
A string representing UUID of a given record.
Example:
record_id = "a5afb151-8f75-4e91-8dc1-05e7e8e8c0b8"
:param uuid:
A string representing UUID of a given signature.
Example:
uuid = "c2f432bd-2f52-4c16-ac66-096f168c762f"
:param profile_recid:
A string representing author profile recid, that
updated signature should point to.
Example:
profile_recid = "1"
"""
try:
record = Record.get_record(record_id)
update_flag = False
for author in record['authors']:
if author['uuid'] == uuid:
author['recid'] = str(profile_recid)
update_flag = True
if update_flag:
# Disconnect the signal on insert of a new record.
before_record_index.disconnect(append_updated_record_to_queue)
# Update the record in the database.
record.commit()
db.session.commit()
# Update the record in Elasticsearch.
indexer = RecordIndexer()
indexer.index_by_id(record.id)
except StaleDataError as exc:
raise update_authors_recid.retry(exc=exc)
finally:
# Reconnect the disconnected signal.
before_record_index.connect(append_updated_record_to_queue)
# Report.
logger.info("Updated signature %s with profile %s",
uuid, profile_recid)
示例11: get_primary_arxiv_category
# 需要导入模块: from invenio_records import Record [as 别名]
# 或者: from invenio_records.Record import get_record [as 别名]
def get_primary_arxiv_category(self):
try:
pid = PersistentIdentifier.get('recid', self.control_number)
record = Record.get_record(pid.object_uuid)
return get_arxiv_primary_category(record)
except PIDDoesNotExistError:
# records imported from Inspire won't be found
pass
return None
示例12: get_document_previewer
# 需要导入模块: from invenio_records import Record [as 别名]
# 或者: from invenio_records.Record import get_record [as 别名]
def get_document_previewer(record_id, filename):
"""Look for a record and return the file."""
record = Record.get_record(record_id)
len_documents = len(Document(record, '/files/').record['files'])
for i_document in range(len_documents):
document = Document(record, '/files/{0}/uri'.format(i_document))
document_previewer = DocumentPreviewer(record_id, document)
if not filename or document_previewer.get_filename() == filename:
return document_previewer
示例13: test_delete
# 需要导入模块: from invenio_records import Record [as 别名]
# 或者: from invenio_records.Record import get_record [as 别名]
def test_delete(app):
"""Test delete a record."""
with app.app_context():
# Create a record, revise it and delete it.
record = Record.create({'title': 'test 1'})
db.session.commit()
record['title'] = 'test 2'
record.commit()
db.session.commit()
record.delete()
db.session.commit()
# Deleted records a not retrievable by default
pytest.raises(NoResultFound, Record.get_record, record.id)
# Deleted records can be retrieved if you explicit request it
record = Record.get_record(record.id, with_deleted=True)
# Deleted records are empty
assert record == {}
assert record.model.json is None
# Deleted records *cannot* be modified
record['title'] = 'deleted'
assert pytest.raises(MissingModelError, record.commit)
# Deleted records *can* be reverted
record = record.revert(-2)
assert record['title'] == 'test 2'
db.session.commit()
# The "undeleted" record can now be retrieve again
record = Record.get_record(record.id)
assert record['title'] == 'test 2'
# Force deleted record cannot be retrieved again
record.delete(force=True)
db.session.commit()
pytest.raises(
NoResultFound, Record.get_record, record.id,
with_deleted=True)
示例14: check_compliance
# 需要导入模块: from invenio_records import Record [as 别名]
# 或者: from invenio_records.Record import get_record [as 别名]
def check_compliance(obj, *args):
if 'control_number' not in obj.data:
raise ValueError("Object should have a 'control_number' key in 'data' dict to be consistent with article upload.")
recid = obj.data['control_number']
pid = PersistentIdentifier.get('recid', recid)
record = Record.get_record(pid.object_uuid)
checks = {}
# Add temporary data to evalutaion
extra_data = {'extracted_text': __extract_article_text(record)}
all_checks_accepted = True
for name, func in COMPLIANCE_TASKS:
check_accepted, details, debug = func(record, extra_data)
all_checks_accepted = all_checks_accepted and check_accepted
checks[name] = {
'check': check_accepted,
'details': details,
'debug': debug
}
c = Compliance.get_or_create(pid.object_uuid)
results = {
'checks': checks,
'accepted': all_checks_accepted,
'data': {
'doi': get_first_doi(record),
'publisher': get_abbreviated_publisher(record),
'journal': get_abbreviated_journal(record),
'arxiv': get_first_arxiv(record)
}
}
c.add_results(results)
c.id_record = pid.object_uuid
db.session.add(c)
db.session.commit()
# send notification about failed checks
if not all_checks_accepted:
msg = TemplatedMessage(
template_html='scoap3_compliance/admin/failed_email.html',
subject='SCOAP3 - Compliance check',
sender=current_app.config.get('MAIL_DEFAULT_SENDER'),
recipients=current_app.config.get('COMPLIANCE_EMAILS'),
ctx={'results': results}
)
current_app.extensions['mail'].send(msg)
示例15: test_delete
# 需要导入模块: from invenio_records import Record [as 别名]
# 或者: from invenio_records.Record import get_record [as 别名]
def test_delete(app, db):
"""Test delete a record."""
# Create a record, revise it and delete it.
record = Record.create({"title": "test 1"})
db.session.commit()
record["title"] = "test 2"
record.commit()
db.session.commit()
record.delete()
db.session.commit()
# Deleted records a not retrievable by default
pytest.raises(NoResultFound, Record.get_record, record.id)
# Deleted records can be retrieved if you explicit request it
record = Record.get_record(record.id, with_deleted=True)
# Deleted records are empty
assert record == {}
assert record.model.json is None
# Deleted records *cannot* be modified
record["title"] = "deleted"
assert pytest.raises(MissingModelError, record.commit)
# Deleted records *can* be reverted
record = record.revert(-2)
assert record["title"] == "test 2"
db.session.commit()
# The "undeleted" record can now be retrieve again
record = Record.get_record(record.id)
assert record["title"] == "test 2"
# Force deleted record cannot be retrieved again
record.delete(force=True)
db.session.commit()
pytest.raises(NoResultFound, Record.get_record, record.id, with_deleted=True)