Skip to main content

DSL de validation de données et de formulaires pour Python.

Project description

pyarcjon

DSL de validation de données et de formulaires pour Python.

pyarcjon propose une API fluide (chaînage de méthodes) pour construire des schémas de validation, valider des valeurs, et récupérer une valeur nettoyée ou une erreur. Il supporte les chaînes, nombres, booléens, dates, objets, tableaux, énumérations et types conditionnels.

Conçu et maintenu par INICODE.


Table des matières

  1. Installation
  2. Démarrage rapide
  3. Types de validation
  4. API commune à tous les schémas
  5. Exemples par type
  6. Règles personnalisées
  7. Résultat de validation
  8. Architecture
  9. Auteur

Installation

pip install pyarcjon

Installation en mode développeur

git clone https://github.com/inicode/pyarc-utilities.git
cd pyarc-utilities
python cmd.py --build --only pyarcjon
pip install dist/pyarcjon-*.whl

Démarrage rapide

import pyarcjon as JON

# Chaîne requise, format email
schema = JON.String('fr').label('email').required().email()
res = schema.validate('test@example.com')
print(res['valid'])   # True
print(res['data'])    # 'test@example.com'

# Nombre contraint
schema = JON.Number('fr').label('age').required().min(18).max(120)
res = schema.validate(25)
print(res['valid'])   # True

Types de validation

Classe Description
String Chaînes de caractères.
Number Nombres entiers / décimaux.
Boolean Booléens.
Date Dates / datetimes.
Object Objets / dictionnaires structurés.
Array Listes / tableaux typés.
Enum Valeur parmi un ensemble.
NotEnum Valeur exclue d'un ensemble.
ChosenType Union de plusieurs schémas.
AnyType Accepte toute valeur.

API commune à tous les schémas

schema.validate(value)   # -> {'valid': bool, 'data': any, 'error': any}
schema.isValid(value)    # -> bool
schema.error(value)      # -> erreur
schema.sanitize(value)   # -> valeur nettoyée

# Configuration
schema.label('nom')
schema.default(valeur)
schema.lang('fr' | 'en')
schema.required()
schema.enum(*choix)
schema.enumNot(*choix)
schema.defaultError('msg' | {'fr': ..., 'en': ...})

# Mapping / règles personnalisées
schema.applyApp(rule=fn, sanitize=fn, exception=...)
schema.applyMapping(fn)
schema.applyPreMapping(fn)
schema.initMapError(fn)

Exemples par type

String

import pyarcjon as JON

# Chaîne simple
schema = JON.String('fr').label('nom').required().min(2).max(50)
res = schema.validate("Alice")

# Email
email = JON.String('fr').label('email').required().email()
print(email.validate("alice@example.com")['valid'])  # True

# Regex
code = JON.String('fr').label('code').required().regexp(r'^[A-Z]{3}-\d{4}$')
print(code.validate("ABC-1234")['valid'])  # True

# Formats spéciaux
url = JON.String('fr').url()
ip = JON.String('fr').IPAddress('v4')
guid = JON.String('fr').guid()
hexa = JON.String('fr').hexa()
card = JON.String('fr').creditCard()

Options de String : min, max, less, greater, length, regexp, alphanum, base64, lowercase, uppercase, capitalize, ucFirst, creditCard, dataUri, domain, url, hostname, email, guid, hexa, binary, identifier, enum, notEnum.

Number

import pyarcjon as JON

age = JON.Number('fr').label('age').required().min(0).max(120)
print(age.validate(30)['valid'])  # True

port = JON.Number('fr').label('port').required().TCPPort()
print(port.validate(8080)['valid'])  # True

integer = JON.Number('fr').integer()
positive = JON.Number('fr').positive()
multiple = JON.Number('fr').multiple(5)

Boolean

import pyarcjon as JON

actif = JON.Boolean('fr').label('actif').default(False)
print(actif.validate('true')['data'])   # True
print(actif.validate('non')['data'])    # False

Date

import pyarcjon as JON

naissance = JON.Date('fr').label('naissance').changeFormat('%Y/%m/%d').toDate()
res = naissance.validate('1990/05/15')
print(res['valid'])   # True

Object

import pyarcjon as JON

utilisateur = JON.Object('fr').label('utilisateur').required().struct({
    'nom': JON.String('fr').required().min(2),
    'age': JON.Number('fr').required().greater(0),
    'email': JON.String('fr').required().email(),
})

res = utilisateur.validate({
    'nom': 'Alice',
    'age': 30,
    'email': 'alice@example.com'
})
print(res['valid'])   # True

Array

import pyarcjon as JON

tags = JON.Array('fr').label('tags').types(
    JON.String('fr').required()
).min(1).max(5)

res = tags.validate(['python', 'validation'])
print(res['valid'])   # True

Enum / NotEnum

import pyarcjon as JON

statut = JON.Enum('fr').label('statut').choices('actif', 'inactif', 'en_attente')
print(statut.validate('actif')['valid'])  # True

pays_interdit = JON.NotEnum('fr').label('pays').choices('X', 'Y')

ChosenType (union)

import pyarcjon as JON

valeur = JON.ChosenType('fr').label('valeur').choices(
    JON.Number('fr'),
    JON.String('fr').min(1)
)

print(valeur.validate(42)['valid'])       # True
print(valeur.validate('texte')['valid'])  # True

Règles personnalisées

import pyarcjon as JON

score = JON.Number('fr').label('score').min(0).max(100).applyApp(
    rule=lambda v: v > 50,
    sanitize=lambda v: v * 2
)

res = score.validate(60)
print(res['data'])    # 120

Jusqu'à 50 règles personnalisées sont gérées en interne (CUSTOM01 à CUSTOM50).


Résultat de validation

Toutes les méthodes validate retournent un dictionnaire :

{
    'valid': bool,
    'data': any,      # valeur nettoyée / transformée
    'error': any      # None si valide, sinon Exception ou str
}

Architecture

pyarcjon/
├── __init__.py        # API publique
├── JON.py             # Assemblage des classes
├── JON_default.py     # Classe de base JONDefaultSchema
├── JON_sup.py         # Types String, Number, Boolean, Date, Object, Array, Enum, ...
├── JON_hybrid.py      # Helpers hybrides
├── JON_simplify.py    # Simplification / réallocation de validateurs
└── JON_sup.py         # Suppléments

Auteur

Développé avec passion par INICODEcontact.inicode@gmail.com.

Licence : MIT.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pyarcjon-0.0.1.tar.gz (1.9 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pyarcjon-0.0.1-py3-none-any.whl (2.1 MB view details)

Uploaded Python 3

File details

Details for the file pyarcjon-0.0.1.tar.gz.

File metadata

  • Download URL: pyarcjon-0.0.1.tar.gz
  • Upload date:
  • Size: 1.9 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.9.7

File hashes

Hashes for pyarcjon-0.0.1.tar.gz
Algorithm Hash digest
SHA256 ab7522a63bbab33afd7852f03208b31ed53ece42d031869a178645b3d79a421d
MD5 11575d6c58718cea4c809f16e518f682
BLAKE2b-256 e5d4ac81fcfd6b76f7e15640e132b25511a7c051d34b45c38ccdcbbbcee1c1d7

See more details on using hashes here.

File details

Details for the file pyarcjon-0.0.1-py3-none-any.whl.

File metadata

  • Download URL: pyarcjon-0.0.1-py3-none-any.whl
  • Upload date:
  • Size: 2.1 MB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.9.7

File hashes

Hashes for pyarcjon-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 cab0a5ede8d5119620bf50a18da57e1a4ffb62d1249cd61c77df7c186a164609
MD5 1028871cef848730baa2af31dc4fe57e
BLAKE2b-256 11eb8405e834258869be23dd86093ac9f08af6291b71da82c5ce7831dc253579

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page