diff --git a/app/__init__.py b/app/__init__.py index f1374e0..a63eaf7 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,7 +1,7 @@ -from flask import Flask, request +from flask import Flask, request, jsonify import time import json -from app.local_db import LocalDB +import uuid from marshmallow import Schema, fields from flask_sqlalchemy import SQLAlchemy @@ -16,16 +16,12 @@ class UserModel(db.Model): uuid = db.Column(db.String(32), unique=True, primary_key=True, nullable=False) name = db.Column(db.String(64), nullable=False) - records = db.relationship('RecordSchema', backref='user.uuid') - class CategoryModel(db.Model): __tablename__ = "category" uuid = db.Column(db.String(32), unique=True, primary_key=True, nullable=False) name = db.Column(db.String(64), nullable=False) - records = db.relationship('RecordSchema', backref='category.uuid') - -class RecordSchema(db.Model): +class RecordModel(db.Model): __tablename__ = "record" uuid = db.Column(db.String(32), primary_key=True, nullable=False) user_uuid = db.Column(db.String(32), db.ForeignKey('user.uuid')) @@ -48,6 +44,15 @@ class RecordSchema(Schema): date = fields.Date() amount = fields.Integer() +user_schema = UserSchema() +users_schema = UserSchema(many = True) + +category_schema = CategorySchema() +categories_schema = CategorySchema(many = True) + +record_schema = RecordSchema() +records_schema = RecordSchema(many = True) + # "migration" with app.app_context(): db.create_all() @@ -61,12 +66,12 @@ def ep_healthcheck(): @app.route("/reset_users_because_postman_is_dumb_like_that") def ep_reset(): - ldb.reset() return {} @app.route("/users", methods = ["GET"]) def ep_users_get(): - return ldb.get_users() + result = db.session.query(UserModel).all() + return users_schema.dumps(result) @app.route("/user/", methods = ["GET"]) def ep_user_get(user_id): @@ -81,16 +86,30 @@ def ep_user_get(user_id): def ep_user_post(): body = request.json - if 'name' in body: - r = ldb.add_user(body['name']) - - if 'uuid' in r: - return r - else: - return r, 403 - else: + if not body: return {}, 403 + if 'uuid' in body: + return {}, 403 + + body.update({'uuid': uuid.uuid4().hex}) + + try: + _ = user_schema.load(body) + except ValidationError as e: + return {}, 403 + + u = UserModel(**body) + + try: + db.session.add(u) + db.session.commit() + except Exception as e: + db.session.rollback() + return {}, 403 + + return jsonify(user_schema.load(body)), 200 + @app.route("/user/", methods = ["DELETE"]) def ep_user_delete(user_id): r = ldb.del_user(user_id)