corpusAPI.py 1.76 KB
Newer Older
1
"""The corpus API. Add it to your REST API to provide users with metadata about specific texts."""
2
from typing import Union
3

4 5 6 7 8
import connexion
from connexion.lifecycle import ConnexionResponse
from flask import Response

from mcserver import Config
9
from mcserver.app import db
10
from mcserver.app.services import NetworkService
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
from mcserver.models_auto import Corpus


def delete(cid: int) -> Union[Response, ConnexionResponse]:
    """The DELETE method for the corpus REST API. It deletes metadata for a specific text."""
    corpus: Corpus = db.session.query(Corpus).filter_by(cid=cid).first()
    if corpus is None:
        return connexion.problem(404, Config.ERROR_TITLE_NOT_FOUND, Config.ERROR_MESSAGE_CORPUS_NOT_FOUND)
    db.session.delete(corpus)
    db.session.commit()
    return NetworkService.make_json_response(True)


def get(cid: int) -> Union[Response, ConnexionResponse]:
    """The GET method for the corpus REST API. It provides metadata for a specific text."""
    corpus: Corpus = db.session.query(Corpus).filter_by(cid=cid).first()
    if corpus is None:
        return connexion.problem(404, Config.ERROR_TITLE_NOT_FOUND, Config.ERROR_MESSAGE_CORPUS_NOT_FOUND)
    return NetworkService.make_json_response(corpus.to_dict())
30 31


32 33 34 35 36 37 38 39 40 41
def patch(cid: int, **kwargs) -> Union[Response, ConnexionResponse]:
    """The PUT method for the corpus REST API. It provides updates metadata for a specific text."""
    corpus: Corpus = db.session.query(Corpus).filter_by(cid=cid).first()
    if corpus is None:
        return connexion.problem(404, Config.ERROR_TITLE_NOT_FOUND, Config.ERROR_MESSAGE_CORPUS_NOT_FOUND)
    for k, v in kwargs.items():
        if v is not None:
            setattr(corpus, k, v)
    db.session.commit()
    return NetworkService.make_json_response(corpus.to_dict())