Skip to content

Commit

Permalink
clean code and use marshmallow
Browse files Browse the repository at this point in the history
  • Loading branch information
TheoLechemia committed Nov 9, 2023
1 parent 2b82dbb commit 188dab9
Show file tree
Hide file tree
Showing 8 changed files with 101 additions and 74 deletions.
34 changes: 0 additions & 34 deletions apptax/taxonomie/repositories.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,39 +23,6 @@
logger = logging.getLogger()


class MediaRepository:
def __init__(self, DBSession):
self.session = DBSession

def _format_media(self, media, force_path):
f_media = {**media.as_dict(), **media.types.as_dict()}

return f_media

def get_media_filter_by(self, filters):
q = self.session.query(TMedias)
if filters:
q = q.filter_by(**filters)
return q.all()

def get_and_format_media_filter_by(self, filters, force_path=False):
results = self.get_media_filter_by(filters)
medias = []
for media in results:
medias.append(self._format_media(media, force_path))
return medias

def get_one_media(self, id):
return self.session.query(TMedias).get(id)

def get_and_format_one_media(self, id, force_path=False):
media = self.get_one_media(id)
if media:
return self._format_media(media, force_path)
else:
return None


class BdcStatusRepository:
def get_status(
self,
Expand Down Expand Up @@ -109,7 +76,6 @@ def get_status(
.joinedload(TaxrefBdcStatutCorTextValues.text)
.joinedload(TaxrefBdcStatutText.type_statut)
)
print(q)
data = q.all()

# Retour des données sous forme formatées ou pas
Expand Down
10 changes: 6 additions & 4 deletions apptax/taxonomie/routesbiblistes.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@
adresses = Blueprint("bib_listes", __name__)
logger = logging.getLogger()

# !! les routes get_biblistes et get_biblistesbyTaxref ne retourne pas les données
# selon le même format !!!


@adresses.route("/", methods=["GET"])
@json_resp
Expand All @@ -37,15 +40,14 @@ def get_biblistes(id=None):

@adresses.route("/<regne>", methods=["GET"])
@adresses.route("/<regne>/<group2_inpn>", methods=["GET"])
@json_resp
def get_biblistesbyTaxref(regne, group2_inpn=None):
q = db.session.query(BibListes)
if regne:
q = q.filter(or_(BibListes.regne == regne, BibListes.regne == None))
q = q.filter(or_(BibListes.v_regne == regne, BibListes.v_regne == None))
if group2_inpn:
q = q.filter(or_(BibListes.group2_inpn == group2_inpn, BibListes.group2_inpn == None))
q = q.filter(or_(BibListes.v_group2_inpn == group2_inpn, BibListes.v_group2_inpn == None))
results = q.all()
return [liste.as_dict() for liste in results]
return BibListesSchema(exclude=("v_regne", "v_group2_inpn")).dump(results, many=True)


@adresses.route("/cor_nom_liste", methods=["GET"])
Expand Down
10 changes: 4 additions & 6 deletions apptax/taxonomie/routesbibnoms.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,15 @@
BibAttributs,
)
from .repositories import MediaRepository
from .models import Taxref, CorTaxonAttribut, BibThemes, BibAttributs, TMedias
from .schemas import TMediasSchema
from pypnusershub import routes as fnauth
from . import db

adresses = Blueprint("bib_noms", __name__)
logger = logging.getLogger()


media_repo = MediaRepository(db.session)


@adresses.route("/taxoninfo/<int(signed=True):cd_nom>", methods=["GET"])
@json_resp
def getOne_bibtaxonsInfo(cd_nom):
Expand Down Expand Up @@ -69,8 +68,7 @@ def getOne_bibtaxonsInfo(cd_nom):
o["nom_theme"] = theme.as_dict()["nom_theme"]
obj["attributs"].append(o)
# Ajout des medias
obj["medias"] = media_repo.get_and_format_media_filter_by(
filters={"cd_ref": cd_ref}, force_path=request.args.get("forcePath", False)
)
medias = TMedias.query.filter_by(**{"cd_ref": cd_ref}).all()
obj["medias"] = TMediasSchema().dump(medias, many=True)

return obj
47 changes: 21 additions & 26 deletions apptax/taxonomie/routestmedias.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,43 +4,38 @@
import os
from flask import jsonify, json, Blueprint, request, Response, g, current_app, send_file

from sqlalchemy.exc import IntegrityError

from pypnusershub import routes as fnauth

from . import db
from .filemanager import FILEMANAGER
from ..utils.utilssqlalchemy import json_resp
from .models import TMedias, BibTypesMedia
from .repositories import MediaRepository
from .models import TMedias
from .schemas import TMediasSchema

adresses = Blueprint("t_media", __name__)
logger = logging.getLogger()

media_repo = MediaRepository(db.session)


@adresses.route("/", methods=["GET"])
@adresses.route("/<int:id>", methods=["GET"])
@json_resp
def get_tmedias(id=None):
"""
Liste des médias
TODO add pagination
"""
if id:
return media_repo.get_and_format_one_media(id)
return media_repo.get_and_format_media_filter_by(
filters={}, force_path=request.args.get("forcePath", False)
)
media = TMedias.query.get(id)
return TMediasSchema().dump(media)
medias = TMedias.query.all()
return TMediasSchema().dump(medias, many=True)


@adresses.route("/bycdref/<cdref>", methods=["GET"])
@json_resp
def get_tmediasbyTaxon(cdref):
filters = {}
if cdref:
filters = {"cd_ref": cdref}
obj = media_repo.get_and_format_media_filter_by(
filters=filters, force_path=request.args.get("forcePath", False)
)
return obj
@adresses.route("/bycdref/<cd_ref>", methods=["GET"])
def get_tmediasbyTaxon(cd_ref):
"""
Liste des médias associés à un taxon
"""
q = TMedias.query.filter_by(**{"cd_ref": cd_ref})
medias = q.all()
return TMediasSchema().dump(medias, many=True)


@adresses.route("/thumbnail/<int:id_media>", methods=["GET"])
Expand All @@ -60,8 +55,8 @@ def getThumbnail_tmedias(id_media):
Image générée
"""

myMedia = media_repo.get_one_media(id_media)
if myMedia is None:
media = TMedias.query.get(id)
if media is None:
return (
json.dumps(
{
Expand All @@ -86,6 +81,6 @@ def getThumbnail_tmedias(id_media):
if ("regenerate" in params) and (params.get("regenerate") == "true"):
regenerate = True

thumbpath = FILEMANAGER.create_thumb(myMedia, size, force, regenerate)
thumbpath = FILEMANAGER.create_thumb(media, size, force, regenerate)

return send_file(os.path.join(Path(current_app.config["MEDIA_FOLDER"]).absolute(), thumbpath))
16 changes: 15 additions & 1 deletion apptax/taxonomie/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,21 @@

from pypnusershub.env import ma

from apptax.taxonomie.models import BibListes, VMRegne, VMGroup2Inpn
from apptax.taxonomie.models import BibListes, VMRegne, VMGroup2Inpn, TMedias, BibTypesMedia


class BibTypesMediaSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = BibTypesMedia
include_fk = True


class TMediasSchema(ma.SQLAlchemyAutoSchema):
class Meta:
model = TMedias
include_fk = True

types = fields.Nested(BibTypesMediaSchema())


class VMRegneSchema(SmartRelationshipsMixin, ma.SQLAlchemyAutoSchema):
Expand Down
36 changes: 35 additions & 1 deletion apptax/tests/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,45 @@ def liste():
if _liste:
return _liste

_liste = BibListes(code_liste="TEST_LIST", nom_liste="Liste test")
_liste = BibListes(
code_liste="TEST_LIST", nom_liste="Liste test", desc_liste="Liste description"
)
db.session.add(_liste)
return _liste


def_liste = [
{
"code_liste": "TEST_LIST_NO_REGNE",
"nom_liste": "Liste test no regne",
"desc_liste": "Liste description",
},
{
"code_liste": "TEST_LIST_Animalia",
"nom_liste": "Liste test Animalia",
"desc_liste": "Liste description",
"v_regne": "Animalia",
},
{
"code_liste": "TEST_LIST_Plantae",
"nom_liste": "Liste test Plantae",
"desc_liste": "Liste description",
"v_regne": "Plantea",
},
]


@pytest.fixture()
def listes():
with db.session.begin_nested():
_listes = []
for l in def_liste:
_liste = BibListes(**l)
db.session.add(_liste)
_listes.append(_liste)
return _listes


@pytest.fixture
def noms_example(attribut_example, liste):
taxref_obj = []
Expand Down
20 changes: 19 additions & 1 deletion apptax/tests/test_biblistes.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,24 @@ def test_get_biblistes(self):
)
assert response.status_code == 200
data = response.json
print(data["data"])
if data:
assert self.schema_allnamebyListe.is_valid(data["data"])

def test_get_biblistesbyTaxref(self, listes):
# !! appel la route get_biblistes en réalité qui ne retourne pas le même résultat
response = self.client.get(
url_for("bib_listes.get_biblistesbyTaxref", regne="", group2_inpn=None),
)
assert response.status_code == 200
# Filter test list only
data = [d for d in response.json["data"] if d["desc_liste"] == "Liste description"]

assert len(data) == 3

self.schema_allnamebyListe.validate(data)
response = self.client.get(
url_for("bib_listes.get_biblistesbyTaxref", regne="Animalia", group2_inpn=None),
)
# Filter test list only
data = [d for d in response.json if d["desc_liste"] == "Liste description"]
assert len(data) == 2
2 changes: 1 addition & 1 deletion apptax/tests/test_media.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def user():
@pytest.mark.usefixtures("client_class", "temporary_transaction")
class TestAPIMedia:
def test_get_tmediasbyTaxon(self, noms_example):
response = self.client.get(url_for("t_media.get_tmediasbyTaxon", cdref=67111))
response = self.client.get(url_for("t_media.get_tmediasbyTaxon", cd_ref=67111))
assert response.status_code == 200

def test_get_tmedias(self):
Expand Down

0 comments on commit 188dab9

Please sign in to comment.