Skip to content

Commit

Permalink
Suppression des utilitaires redondant avec utils-flask-sqla
Browse files Browse the repository at this point in the history
  • Loading branch information
amandine-sahl authored and TheoLechemia committed Nov 9, 2023
1 parent 188dab9 commit c25c60c
Show file tree
Hide file tree
Showing 8 changed files with 16 additions and 147 deletions.
5 changes: 2 additions & 3 deletions apptax/taxonomie/routesbdcstatuts.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,10 @@
from sqlalchemy.orm import joinedload

from pypnusershub import routes as fnauth

from utils_flask_sqla.response import json_resp
from . import filemanager
from . import db
from ..utils.utilssqlalchemy import json_resp, csv_resp, dict_merge
from ..utils.genericfunctions import calculate_offset_page

from .repositories import BdcStatusRepository
from .models import (
TaxrefBdcStatutCorTextValues,
Expand Down
2 changes: 1 addition & 1 deletion apptax/taxonomie/routesbibattributs.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import select, or_

from ..utils.utilssqlalchemy import json_resp
from utils_flask_sqla.response import json_resp
from .models import Taxref, CorTaxonAttribut, BibAttributs

from . import db
Expand Down
3 changes: 1 addition & 2 deletions apptax/taxonomie/routesbiblistes.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,10 @@
from sqlalchemy.orm import joinedload

from pypnusershub import routes as fnauth
from utils_flask_sqla.response import json_resp

from . import filemanager
from . import db
from ..utils.utilssqlalchemy import json_resp, csv_resp
from ..utils.genericfunctions import calculate_offset_page
from .models import BibListes, CorNomListe, Taxref
from apptax.taxonomie.schemas import BibListesSchema

Expand Down
4 changes: 2 additions & 2 deletions apptax/taxonomie/routesbibnoms.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
from sqlalchemy import func
from werkzeug.exceptions import NotFound

from ..utils.utilssqlalchemy import json_resp
from ..utils.genericfunctions import calculate_offset_page

from utils_flask_sqla.response import json_resp

from .models import (
Taxref,
Expand Down
4 changes: 3 additions & 1 deletion apptax/taxonomie/routestaxref.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
from sqlalchemy.orm.exc import NoResultFound


from ..utils.utilssqlalchemy import json_resp, serializeQuery, serializeQueryOneResult
from utils_flask_sqla.response import json_resp
from utils_flask_sqla.generic import serializeQuery, serializeQueryOneResult

from .models import (
Taxref,
VMTaxrefListForautocomplete,
Expand Down
11 changes: 7 additions & 4 deletions apptax/taxonomie/routestmedias.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@
import logging
from pathlib import Path
import os
from flask import jsonify, json, Blueprint, request, Response, g, current_app, send_file
from flask import json, Blueprint, request, current_app, send_file


from .filemanager import FILEMANAGER
from ..utils.utilssqlalchemy import json_resp
from .models import TMedias
from .schemas import TMediasSchema

from .filemanager import FILEMANAGER


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

Expand Down Expand Up @@ -83,4 +84,6 @@ def getThumbnail_tmedias(id_media):

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

return send_file(os.path.join(Path(current_app.config["MEDIA_FOLDER"]).absolute(), thumbpath))
return send_file(
os.path.join(Path(current_app.config["MEDIA_FOLDER"]).absolute(), "taxhub", thumbpath)
)
24 changes: 0 additions & 24 deletions apptax/utils/genericfunctions.py

This file was deleted.

110 changes: 0 additions & 110 deletions apptax/utils/utilssqlalchemy.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,116 +3,6 @@
Fonctions utilitaires
"""
import collections.abc
from flask import jsonify, Response, current_app
import json
from functools import wraps
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Table, create_engine, MetaData
from werkzeug.datastructures import Headers


from . import db


class GenericTable:
def __init__(self, tableName, schemaName):
engine = create_engine(current_app.config["SQLALCHEMY_DATABASE_URI"])
meta = MetaData(bind=engine)
meta.reflect(schema=schemaName, views=True)
self.tableDef = meta.tables[tableName]
self.columns = [column.name for column in self.tableDef.columns]

def serialize(self, data):
return serializeQuery(data, self.columns)


def serializeQuery(data, columnDef):
rows = [
{c["name"]: getattr(row, c["name"]) for c in columnDef if getattr(row, c["name"]) != None}
for row in data
]
return rows


def serializeQueryOneResult(row, columnDef):
row = {
c["name"]: getattr(row, c["name"]) for c in columnDef if getattr(row, c["name"]) != None
}
return row


def _normalize(obj, columns):
"""
Retourne un dictionnaire dont les clés sont le tableau de colonnes
fourni (`columns`) et les valeurs sont issues de l'objet `obj` fourni.
"""
out = {}
for col in columns:
if isinstance(col.type, db.Date):
out[col.name] = str(getattr(obj, col.name))
else:
out[col.name] = getattr(obj, col.name)
return out


def normalize(obj, *parents):
"""
Prend un objet mappé SQLAlchemy et le transforme en dictionnaire pour
être sérialisé en JSON.
Le second paramêtre `parents` permet de compléter la normalisation
avec les données des tables liées par une relation d'héritage.
"""
try:
return obj.to_json()
except AttributeError:
out = _normalize(obj, obj.__table__.columns)
for p in parents:
out.update(_normalize(obj, p().__table__.columns))
return out


def json_resp(fn):
"""
Décorateur transformant le résultat renvoyé par une vue
en objet JSON
"""

@wraps(fn)
def _json_resp(*args, **kwargs):
res = fn(*args, **kwargs)
if isinstance(res, tuple):
res, status = res
else:
status = 200
return Response(json.dumps(res), status=status, mimetype="application/json")

return _json_resp


def csv_resp(fn):
"""
Décorateur transformant le résultat renvoyé en un fichier csv
"""

@wraps(fn)
def _csv_resp(*args, **kwargs):
res = fn(*args, **kwargs)
filename, data, columns, separator = res
outdata = [separator.join(columns)]

headers = Headers()
headers.add("Content-Type", "text/plain")
headers.add("Content-Disposition", "attachment", filename="export_%s.csv" % filename)

for o in data:
outdata.append(
separator.join('"%s"' % (o.get(i), "")[o.get(i) == None] for i in columns)
)

out = "\r\n".join(outdata)
return Response(out, headers=headers)

return _csv_resp


def dict_merge(dct, merge_dct):
Expand Down

0 comments on commit c25c60c

Please sign in to comment.