Torniojaws / vortech-backend

Python 3 backend for the Vortech website.
https://vortechmusic.com
MIT License
0 stars 0 forks source link

Take JSONSchema into use for validation #85

Open Torniojaws opened 5 years ago

Torniojaws commented 5 years ago

https://schematics.readthedocs.io/en/latest/

eg.

from schematics.models import Model
from schematics.types import StringType, URLType

class News(Model):
    title = StringType(required=True)
    author = StringType(required=True)
    contents = StringType(required=True)

data = json.loads(request.data)
news = News()
news.title = data['title']
news.author = data['author']
news.contents = data['contents']

try:
    news.validate()
except ValidationError:
    # 400 Bad Request

Could/Should be used in pretty much all endpoints, but the critical parts are places where Users can input something (Guestbook for now, but later all news/release/song/photo, etc comments).

Public:

User-accessible:

"Automatic" things:

Admin-only:

Torniojaws commented 5 years ago

Added to User registration form. Can use the same for all others.

Torniojaws commented 3 years ago

Schematics seems to be abandoned. JSONSchema seems to be alive: https://python-jsonschema.readthedocs.io/en/stable/

Torniojaws commented 3 years ago
>>> from jsonschema import validate

>>> # A sample schema, like what we'd get from json.load()
>>> schema = {
...     "type" : "object",
...     "properties" : {
...         "price" : {"type" : "number"},
...         "name" : {"type" : "string"},
...     },
... }

>>> # If no exception is raised by validate(), the instance is valid.
>>> validate(instance={"name" : "Eggs", "price" : 34.99}, schema=schema)

>>> validate(
...     instance={"name" : "Eggs", "price" : "Invalid"}, schema=schema,
... )                                   
Traceback (most recent call last):
    ...
ValidationError: 'Invalid' is not of type 'number'