From ef75599675cfd67e7e65e08c336432b7007a3438 Mon Sep 17 00:00:00 2001 From: AndroidDrew Date: Fri, 10 Nov 2017 13:04:26 -0500 Subject: [PATCH] added a marshmallow schema for cookie --- cookie_api/app.py | 24 ++++++++++++++---------- cookie_api/schema.py | 12 ++++++++++++ 2 files changed, 26 insertions(+), 10 deletions(-) diff --git a/cookie_api/app.py b/cookie_api/app.py index 9b5837e..be1d43c 100644 --- a/cookie_api/app.py +++ b/cookie_api/app.py @@ -5,10 +5,13 @@ from apistar.frameworks.wsgi import WSGIApp as App from apistar.handlers import docs_urls, static_urls from apistar.interfaces import Router, Injector, Auth from apistar_jwt.authentication import JWTAuthentication + from cookie_api.auth import auth_routes, auth_components from cookie_api.commands import commands from cookie_api.models import Cookie +from cookie_api.schema import CookieSchema +cookie_schema = CookieSchema() @annotate(authentication=[JWTAuthentication()]) def get_state(injector: Injector, auth: Auth): @@ -21,9 +24,7 @@ def get_state(injector: Injector, auth: Auth): def get_cookies(session: Session): cookies = session.query(Cookie).all() - result = [cookie.to_dict() for cookie in cookies] - - return result + return cookie_schema.dump(cookies, many=True).data def get_cookie(session: Session, id): @@ -31,19 +32,22 @@ def get_cookie(session: Session, id): if cookie is None: msg = {"error": "404 Not Found"} return http.Response(msg, status=404) - return cookie.to_dict() + return cookie_schema.dump(cookie).data def create_cookie(session: Session, json_data: http.RequestData, route: Router): - cookie = Cookie(name=json_data['name'], - recipe_url=json_data['recipe_url'], - sku=json_data['sku'], - qoh=json_data['qoh'], - unit_cost=json_data['unit_cost']) + cookie_data = cookie_schema.load(json_data) + + #cookie = Cookie(name=json_data['name'], + # recipe_url=json_data['recipe_url'], + # sku=json_data['sku'], + # qoh=json_data['qoh'], + # unit_cost=json_data['unit_cost']) + cookie = Cookie(**cookie_data) session.add(cookie) session.commit() headers = {'Location': route.reverse_url('get_cookie', dict(id=cookie.id))} - return http.Response(cookie.to_dict(), status=201, headers=headers) + return http.Response(cookie_schema.dump(cookie), status=201, headers=headers) def delete_cookie(session: Session, id: int): diff --git a/cookie_api/schema.py b/cookie_api/schema.py index e69de29..87c82e2 100644 --- a/cookie_api/schema.py +++ b/cookie_api/schema.py @@ -0,0 +1,12 @@ +from marshmallow import Schema, fields + + +class CookieSchema(Schema): + id = fields.Int() + created_date = fields.DateTime() + modified_date = fields.DateTime() + name = fields.Str(required=True) + recipe_url = fields.Str() + sku = fields.Str(required=True) + qoh = fields.Int(required=True) + unit_cost = fields.Decimal(required=True)