Moving to Typesystem

Moving to type system. Added registration endpoint. Added custom Decimal type.
deb
androiddrew 7 years ago
parent 3ef15e7b48
commit 7b23ad97d8

@ -1,3 +1,5 @@
import typing
from apistar import Include, Route, http, annotate from apistar import Include, Route, http, annotate
from apistar.backends import sqlalchemy_backend from apistar.backends import sqlalchemy_backend
from apistar.backends.sqlalchemy_backend import Session from apistar.backends.sqlalchemy_backend import Session
@ -14,6 +16,7 @@ import logbook
from cookie_api.auth import auth_routes, auth_components from cookie_api.auth import auth_routes, auth_components
from cookie_api.commands import commands from cookie_api.commands import commands
from cookie_api.models import Cookie from cookie_api.models import Cookie
#from cookie_api.schema import CookieSchema
from cookie_api.schema import CookieSchema from cookie_api.schema import CookieSchema
from cookie_api import logging from cookie_api import logging
@ -31,19 +34,19 @@ def get_state(injector: Injector, auth: Auth):
return d return d
def get_cookies(session: Session): def get_cookies(session: Session) -> typing.List[CookieSchema]:
logger.info("Accessing the Cookies resource") logger.info("Accessing the Cookies resource")
cookies = session.query(Cookie).all() cookies = session.query(Cookie).all()
return cookie_schema.dump(cookies, many=True).data return [CookieSchema(cookie) for cookie in cookies]
def get_cookie(session: Session, id): def get_cookie(session: Session, id) -> CookieSchema:
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:
logger.warn("Someone keeps requesting bad cookie locations") logger.warn("Someone keeps requesting bad cookie locations")
msg = {"error": "404 Not Found"} msg = {"error": "404 Not Found"}
return http.Response(msg, status=404) return http.Response(msg, status=404)
return cookie_schema.dump(cookie).data return CookieSchema(cookie)
def create_cookie(session: Session, json_data: http.RequestData, route: Router): def create_cookie(session: Session, json_data: http.RequestData, route: Router):

@ -10,6 +10,7 @@ from sqlalchemy.exc import IntegrityError, InvalidRequestError
from sqlalchemy.orm.exc import NoResultFound from sqlalchemy.orm.exc import NoResultFound
from cookie_api.models import User from cookie_api.models import User
from cookie_api.schema import UserSchema, UserCreateSchema
auth_components = [ auth_components = [
Component(JWT, init=get_jwt) Component(JWT, init=get_jwt)
@ -59,11 +60,8 @@ def logout():
# TODO Add user registration # TODO Add user registration
def register(json_data: http.RequestData, session: Session, mail: Mail): def register(user_rep: UserCreateSchema, session: Session, mail: Mail):
user_id = json_data.get('email') email_check = session.query(User).filter_by(email=user_rep['email']).one_or_none()
password = json_data.get('password')
email_check = session.query(User).filter_by(email=user_id).one_or_none()
if email_check is not None: if email_check is not None:
message = { message = {
@ -72,12 +70,12 @@ def register(json_data: http.RequestData, session: Session, mail: Mail):
} }
return http.Response(message, status=400) return http.Response(message, status=400)
user = User(email=user_id, password=password) user = User(email=user_rep['email'], password=user_rep['password'])
session.add(user) session.add(user)
session.commit() session.commit()
msg = Message("Thank you for registering please confirm your email", recipients=[user_id]) msg = Message("Thank you for registering please confirm your email", recipients=[user_rep['email']])
mail.send(msg) mail.send(msg)
headers = {} headers = {}
@ -85,18 +83,15 @@ def register(json_data: http.RequestData, session: Session, mail: Mail):
'status': 'success', 'status': 'success',
'message': 'Please check your inbox and confirm your email' 'message': 'Please check your inbox and confirm your email'
} }
return http.Response(message, status=200, headers=headers) return http.Response(message, status=201, headers=headers)
@annotate(authentication=[JWTAuthentication()]) @annotate(authentication=[JWTAuthentication()])
def user_profile(auth: Auth, settings: Settings, session: Session): def user_profile(auth: Auth, settings: Settings, session: Session) -> UserSchema:
token = JWT(token=auth.token, settings=settings) token = JWT(token=auth.token, settings=settings)
user_id = token.payload.get('sub') user_id = token.payload.get('sub')
user = session.query(User).filter_by(id=user_id).one() user = session.query(User).filter_by(id=user_id).one()
result = user.to_dict() return UserSchema(user)
result.pop('password', None)
return result
# TODO Add email confirmation # TODO Add email confirmation
def confirm(json_data: http.RequestData, session: Session): def confirm(json_data: http.RequestData, session: Session):

@ -1,12 +1,48 @@
from marshmallow import Schema, fields from apistar import typesystem
# from marshmallow import Schema, fields
class CookieSchema(Schema): from cookie_api.types import Datetime, Decimal
id = fields.Int()
created_date = fields.DateTime()
modified_date = fields.DateTime() # class CookieSchema(Schema):
name = fields.Str(required=True) # id = fields.Int()
recipe_url = fields.Str() # created_date = fields.DateTime()
sku = fields.Str(required=True) # modified_date = fields.DateTime()
qoh = fields.Int(required=True) # name = fields.Str(required=True)
unit_cost = fields.Decimal(required=True) # recipe_url = fields.Str()
# sku = fields.Str(required=True)
# qoh = fields.Int(required=True)
# unit_cost = fields.Decimal(required=True)
class UserSchema(typesystem.Object):
description = 'A User respresentation'
properties = {
'id': typesystem.integer(),
'created_date': Datetime,
'modified_date': Datetime,
'email': typesystem.string(max_length=255),
'confirmed': typesystem.boolean(),
'admin': typesystem.boolean()
}
class UserCreateSchema(typesystem.Object):
description = 'A User respresentation for creating a user'
properties = {
'email': typesystem.string(max_length=255),
'password': typesystem.string(max_length=255)
}
class CookieSchema(typesystem.Object):
properties = {
'id': typesystem.integer(),
'created_date': Datetime,
'modified_date': Datetime,
'name': typesystem.string(),
'recipe_url': typesystem.string(),
'sku': typesystem.string(),
'qoh': typesystem.integer(),
'unit_cost': Decimal
}

@ -1,6 +1,8 @@
import datetime import datetime
import decimal
import dateutil import dateutil
from apistar.typesystem import TypeSystemError from apistar import typesystem
class Datetime(datetime.datetime): class Datetime(datetime.datetime):
@ -13,7 +15,11 @@ class Datetime(datetime.datetime):
try: try:
return dateutil.parser.parse(args[0]) return dateutil.parser.parse(args[0])
except ValueError: except ValueError:
raise TypeSystemError(cls=cls, code='type') from None raise typesystem.TypeSystemError(cls=cls, code='type') from None
return cls.native_type(*args, **kwargs) return cls.native_type(*args, **kwargs)
class Decimal(typesystem._NumericType, decimal.Decimal):
native_type = decimal.Decimal

@ -5,7 +5,7 @@ import pytest
from cookie_api.models import Base from cookie_api.models import Base
from cookie_api.renders import JSONRenderer from cookie_api.renders import JSONRenderer
from cookie_api.app import commands, routes, components from cookie_api.app import commands, _routes, _components
settings = { settings = {
'DATABASE': { 'DATABASE': {
@ -49,5 +49,5 @@ def apistar_app_fixture():
"""Returns a session scoped WSGIApp instance""" """Returns a session scoped WSGIApp instance"""
return WSGIApp(settings=settings, return WSGIApp(settings=settings,
commands=commands, commands=commands,
components=components, components=_components,
routes=routes) routes=_routes)

Loading…
Cancel
Save