Vérification acronymes dept

This commit is contained in:
Emmanuel Viennet 2023-03-20 12:17:28 +01:00
parent 7de4be3c59
commit 738de9d5ed

View File

@ -2,12 +2,15 @@
"""ScoDoc models : departements """ScoDoc models : departements
""" """
import re
from app import db from app import db
from app.models import SHORT_STR_LEN from app.models import SHORT_STR_LEN
from app.models.preferences import ScoPreference from app.models.preferences import ScoPreference
from app.scodoc.sco_exceptions import ScoValueError from app.scodoc.sco_exceptions import ScoValueError
VALID_DEPT_EXP = re.compile(r"^[\w@\\\-\.]+$")
class Departement(db.Model): class Departement(db.Model):
"""Un département ScoDoc""" """Un département ScoDoc"""
@ -60,6 +63,15 @@ class Departement(db.Model):
} }
return data return data
@classmethod
def invalid_dept_acronym(cls, dept_acronym: str) -> bool:
"Check that dept_acronym is invalid"
return (
not dept_acronym
or (len(dept_acronym) >= SHORT_STR_LEN)
or not VALID_DEPT_EXP.match(dept_acronym)
)
@classmethod @classmethod
def from_acronym(cls, acronym): def from_acronym(cls, acronym):
dept = cls.query.filter_by(acronym=acronym).first_or_404() dept = cls.query.filter_by(acronym=acronym).first_or_404()
@ -70,6 +82,8 @@ def create_dept(acronym: str, visible=True) -> Departement:
"Create new departement" "Create new departement"
from app.models import ScoPreference from app.models import ScoPreference
if Departement.invalid_dept_acronym(acronym):
raise ScoValueError("acronyme departement invalide")
existing = Departement.query.filter_by(acronym=acronym).count() existing = Departement.query.filter_by(acronym=acronym).count()
if existing: if existing:
raise ScoValueError(f"acronyme {acronym} déjà existant") raise ScoValueError(f"acronyme {acronym} déjà existant")