-
Notifications
You must be signed in to change notification settings - Fork 51
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add endpoint for creating objects (fixes #178) #188
Merged
Merged
Changes from 11 commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
81935eb
Add objects endpoint
DavidMStraub b551e82
Add POST to all object endpoints
DavidMStraub b557ea0
Check for correct _class and add if missing
DavidMStraub b37eff3
Add test
DavidMStraub 96e9fc0
Fail if handle already exists
DavidMStraub d84ae3e
Fail with 400 instead of 500
DavidMStraub dc5ecaf
Add API docs for POST
DavidMStraub 3526d21
[apispec] Add additional properties for POST
DavidMStraub be421cb
Add more tests
DavidMStraub ebb3ae0
add_object: simplify and check for duplicate gramps ID
DavidMStraub 0008ddc
[apispec] Document /objects/
DavidMStraub fe565c1
Add update_object, clean up
DavidMStraub 443eb89
Review improvements
DavidMStraub 8a6692c
Fix typo
DavidMStraub a89885c
Implement writable db handle
DavidMStraub 7fab386
Implement readonly database connection
DavidMStraub 11a60a7
Fix test
DavidMStraub File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
# | ||
# Gramps Web API - A RESTful API for the Gramps genealogy program | ||
# | ||
# Copyright (C) 2020 David Straub | ||
# Copyright (C) 2020 Christopher Horn | ||
# | ||
# This program is free software; you can redistribute it and/or modify | ||
# it under the terms of the GNU Affero General Public License as published by | ||
# the Free Software Foundation; either version 3 of the License, or | ||
# (at your option) any later version. | ||
# | ||
# This program is distributed in the hope that it will be useful, | ||
# but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
# GNU Affero General Public License for more details. | ||
# | ||
# You should have received a copy of the GNU Affero General Public License | ||
# along with this program. If not, see <https://www.gnu.org/licenses/>. | ||
# | ||
|
||
"""Object creation API resource.""" | ||
|
||
import json | ||
from typing import Any, Dict, Sequence | ||
|
||
import gramps | ||
import jsonschema | ||
from flask import Response, abort, request | ||
from gramps.gen.db import DbTxn | ||
from gramps.gen.db.base import DbWriteBase | ||
from gramps.gen.lib import ( | ||
Citation, | ||
Event, | ||
Family, | ||
Media, | ||
Note, | ||
Person, | ||
Place, | ||
Repository, | ||
Source, | ||
Tag, | ||
) | ||
from gramps.gen.lib.primaryobj import BasicPrimaryObject as GrampsObject | ||
from gramps.gen.lib.serialize import from_json | ||
|
||
from ...auth.const import PERM_ADD_OBJ | ||
from ..auth import require_permissions | ||
from ..util import get_db_handle | ||
from . import ProtectedResource | ||
from .util import add_object, validate_object_dict | ||
|
||
|
||
class CreateObjectsResource(ProtectedResource): | ||
"""Resource for creating multiple objects.""" | ||
|
||
def _parse_objects(self) -> Sequence[GrampsObject]: | ||
"""Parse the objects.""" | ||
payload = request.json | ||
objects = [] | ||
for obj_dict in payload: | ||
if not validate_object_dict(obj_dict): | ||
abort(400) | ||
obj = from_json(json.dumps(obj_dict)) | ||
objects.append(obj) | ||
return objects | ||
|
||
def post(self) -> Response: | ||
"""Post the objects.""" | ||
require_permissions([PERM_ADD_OBJ]) | ||
objects = self._parse_objects() | ||
if not objects: | ||
abort(400) | ||
db_handle = get_db_handle() | ||
with DbTxn("Add objects", db_handle) as trans: | ||
for obj in objects: | ||
try: | ||
add_object(db_handle, obj, trans, fail_if_exists=True) | ||
except ValueError: | ||
abort(400) | ||
return Response(status=201) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -19,10 +19,15 @@ | |
# | ||
|
||
"""Gramps utility functions.""" | ||
|
||
|
||
from typing import Any, Dict, List, Optional, Tuple, Union | ||
|
||
import gramps | ||
import jsonschema | ||
from gramps.gen.const import GRAMPS_LOCALE as glocale | ||
from gramps.gen.db.base import DbReadBase | ||
from gramps.gen.db import DbTxn | ||
from gramps.gen.db.base import DbReadBase, DbWriteBase | ||
from gramps.gen.display.name import NameDisplay | ||
from gramps.gen.display.place import PlaceDisplay | ||
from gramps.gen.errors import HandleError | ||
|
@@ -31,11 +36,14 @@ | |
Event, | ||
Family, | ||
Media, | ||
Note, | ||
Person, | ||
Place, | ||
PlaceType, | ||
Repository, | ||
Source, | ||
Span, | ||
Tag, | ||
) | ||
from gramps.gen.lib.primaryobj import BasicPrimaryObject as GrampsObject | ||
from gramps.gen.soundex import soundex | ||
|
@@ -716,3 +724,40 @@ def get_rating(db_handle: DbReadBase, obj: GrampsObject) -> Tuple[int, int]: | |
if citation.confidence > confidence: | ||
confidence = citation.confidence | ||
return count, confidence | ||
|
||
|
||
def add_object( | ||
db_handle: DbWriteBase, | ||
obj: GrampsObject, | ||
trans: DbTxn, | ||
fail_if_exists: bool = False, | ||
): | ||
"""Commit a Gramps object to the database.""" | ||
obj_class = obj.__class__.__name__.lower() | ||
if fail_if_exists: | ||
has_handle = db_handle.method("has_%s_handle", obj_class) | ||
if obj.handle and has_handle(obj.handle): | ||
raise ValueError("Handle already exists.") | ||
has_grampsid = db_handle.method("has_%s_gramps_id", obj_class) | ||
if hasattr(obj, "gramps_id") and obj.gramps_id and has_grampsid(obj.gramps_id): | ||
raise ValueError("Gramps ID already exists.") | ||
try: | ||
add_method = db_handle.method("add_%s", obj_class) | ||
return add_method(obj, trans) | ||
except AttributeError: | ||
raise ValueError("Database does not support writing.") | ||
raise ValueError("Unexpected object type.") | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Isn't this line dead? It looks like we either already returned, or some error is already raised at this point. |
||
|
||
|
||
def validate_object_dict(obj_dict: Dict[str, Any]) -> bool: | ||
"""Validate a dict representation of a Gramps object vs. its schema.""" | ||
try: | ||
obj_cls = getattr(gramps.gen.lib, obj_dict["_class"]) | ||
except (KeyError, AttributeError): | ||
return False | ||
schema = obj_cls.get_schema() | ||
try: | ||
jsonschema.validate(obj_dict, schema) | ||
except jsonschema.exceptions.ValidationError: | ||
return False | ||
return True |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Copy and paste date?