Added Marshmallow validation to views

email
AndroidDrew 7 years ago
parent ef75599675
commit 4f3ee63faf

@ -13,6 +13,7 @@ from cookie_api.schema import CookieSchema
cookie_schema = CookieSchema() cookie_schema = CookieSchema()
@annotate(authentication=[JWTAuthentication()]) @annotate(authentication=[JWTAuthentication()])
def get_state(injector: Injector, auth: Auth): def get_state(injector: Injector, auth: Auth):
state = injector.state state = injector.state
@ -23,46 +24,68 @@ def get_state(injector: Injector, auth: Auth):
def get_cookies(session: Session): def get_cookies(session: Session):
"""Retrieves all Cookies"""
cookies = session.query(Cookie).all() cookies = session.query(Cookie).all()
return cookie_schema.dump(cookies, many=True).data return cookie_schema.dump(cookies, many=True).data
def create_cookie(session: Session, json_data: http.RequestData, route: Router):
"""Create a Cookie"""
cookie_data, errors = cookie_schema.load(json_data)
if errors:
msg = {"message": "400 Bad Request", "error": errors}
return http.Response(msg, status=400)
cookie = Cookie(**cookie_data)
session.add(cookie)
session.flush()
headers = {'Location': route.reverse_url('get_cookie', dict(id=cookie.id))}
return http.Response(cookie_schema.dump(cookie).data, status=201, headers=headers)
def get_cookie(session: Session, id): def get_cookie(session: Session, id):
"""Retrieve Cookie by id"""
cookie = session.query(Cookie).filter_by(id=id).one_or_none() cookie = session.query(Cookie).filter_by(id=id).one_or_none()
if cookie is None: if cookie is None:
msg = {"error": "404 Not Found"} msg = {"message": "404 Not Found"}
return http.Response(msg, status=404) return http.Response(msg, status=404)
return cookie_schema.dump(cookie).data return cookie_schema.dump(cookie).data
def create_cookie(session: Session, json_data: http.RequestData, route: Router): def patch_cookie(session: Session, json_data: http.RequestData, id: int):
cookie_data = cookie_schema.load(json_data) """Update Cookie through partial update"""
cookie = session.query(Cookie).filter_by(id=id).one_or_none()
#cookie = Cookie(name=json_data['name'], if cookie is None:
# recipe_url=json_data['recipe_url'], msg = {"message": "404 Not Found"}
# sku=json_data['sku'], return http.Response(msg, status=404)
# qoh=json_data['qoh'], # run schema validation of fields
# unit_cost=json_data['unit_cost']) cookie_data, errors = cookie_schema.load(json_data, partial=True)
cookie = Cookie(**cookie_data) if errors:
session.add(cookie) msg = {"message": "400 Bad Request", "error": errors}
session.commit() return http.Response(msg, status=400)
headers = {'Location': route.reverse_url('get_cookie', dict(id=cookie.id))}
return http.Response(cookie_schema.dump(cookie), status=201, headers=headers) for k, v in cookie_data.items():
setattr(cookie, k, v)
session.flush()
return cookie_schema.dump(cookie).data
def delete_cookie(session: Session, id: int): def delete_cookie(session: Session, id: int):
"""Delete a Cookie"""
cookie = session.query(Cookie).filter_by(id=id).one_or_none() cookie = session.query(Cookie).filter_by(id=id).one_or_none()
if cookie is None: if cookie is None:
msg = {"error": "404 Not Found"} msg = {"message": "404 Not Found"}
return http.Response(msg, status=404) return http.Response(msg, status=404)
session.delete(cookie) session.delete(cookie)
return {"message": "200 OK"} return {"message": "200 OK"}
routes = [ routes = [
Route('/state', 'GET', get_state), Route('/state', 'GET', get_state),
Route('/cookies', 'GET', get_cookies), Route('/cookies', 'GET', get_cookies),
Route('/cookies', 'POST', create_cookie), Route('/cookies', 'POST', create_cookie),
Route('/cookies/{id}', 'GET', get_cookie), Route('/cookies/{id}', 'GET', get_cookie),
Route('/cookies/{id}', 'PATCH', patch_cookie),
Route('/cookies/{id}', 'DELETE', delete_cookie),
Include('/docs', docs_urls), Include('/docs', docs_urls),
Include('/static', static_urls) Include('/static', static_urls)
] ]

@ -14,7 +14,7 @@ from cookie_api.models import User
auth_components = [ auth_components = [
Component(JWT, init=get_jwt) Component(JWT, init=get_jwt)
] ]
[]
# /auth/login # /auth/login
def login(settings: Settings, json_data: http.RequestData, session: Session): def login(settings: Settings, json_data: http.RequestData, session: Session):

@ -1,12 +1,25 @@
from marshmallow import Schema, fields from marshmallow import Schema, fields, ValidationError
def non_neg(value):
if not value >= 0:
raise ValidationError('Value cannot be negative')
def non_neg_non_zero(value):
if not value > 0:
raise ValidationError('Value cannot be negative or zero')
class CookieSchema(Schema): class CookieSchema(Schema):
id = fields.Int() id = fields.Int(dump_only=True)
created_date = fields.DateTime() created_date = fields.DateTime(dump_only=True)
modified_date = fields.DateTime() modified_date = fields.DateTime()
name = fields.Str(required=True) name = fields.Str(required=True, error_messages={'required': "Cookie name is required"})
recipe_url = fields.Str() recipe_url = fields.Str()
sku = fields.Str(required=True) sku = fields.Str(required=True, error_messages={'required': "Cookie sku is required"})
qoh = fields.Int(required=True) qoh = fields.Int(validate=non_neg, required=True, error_messages={'required': "Cookie qoh is required"})
unit_cost = fields.Decimal(required=True) unit_cost = fields.Decimal(validate=non_neg_non_zero, required=True, error_messages={'required': "Cookie unit_cost is required"})
class Meta:
ordered = True

Loading…
Cancel
Save