diff --git a/program_service/schemas/__init__.py b/program_service/schemas/__init__.py index 5f7ce86..1673fd9 100644 --- a/program_service/schemas/__init__.py +++ b/program_service/schemas/__init__.py @@ -1 +1,2 @@ -#!/usr/bin/env python3 \ No newline at end of file +#!/usr/bin/env python3 +from .program_schema import ProgramSchema diff --git a/program_service/schemas/program_schema.py b/program_service/schemas/program_schema.py new file mode 100644 index 0000000..21d5045 --- /dev/null +++ b/program_service/schemas/program_schema.py @@ -0,0 +1,28 @@ +from marshmallow import Schema, fields +from marshmallow.validate import Length, Equal +from marshmallow import RAISE + +from datetime import datetime + +SUPPORTED_PROGRAM_STRUCTURE_VERSION = 1 + + +class CommandSchema(Schema): + command = fields.Str(required=True) + args = fields.Dict(required=True) + + class Meta: + unknown = RAISE + + +class ProgramSchema(Schema): + _id = fields.Str(required=False) + created_at = fields.DateTime(required=False, missing=datetime.now) + name = fields.Str() + + version = fields.Int(required=True, validate=Equal(SUPPORTED_PROGRAM_STRUCTURE_VERSION)) + load_plugins = fields.List(fields.Str(), required=True) + program = fields.Nested(CommandSchema, many=True, required=True, validate=Length(min=1)) + + class Meta: + unknown = RAISE diff --git a/program_service/views/program_view.py b/program_service/views/program_view.py index 9dd7bc2..844029c 100644 --- a/program_service/views/program_view.py +++ b/program_service/views/program_view.py @@ -1,22 +1,48 @@ #!/usr/bin/env python3 from flask import request, jsonify, current_app, abort, Response from flask_classful import FlaskView, route +from utils import mongo, json_required + +from bson.objectid import ObjectId + +from schemas import ProgramSchema +from marshmallow.exceptions import ValidationError class ProgramView(FlaskView): + program_schema = ProgramSchema(many=False, dump_only=['_id']) + programs_schema = ProgramSchema(many=True, exclude=['program']) def index(self): - pass + cursor = mongo.db.programs.find({}) + + programs = [] + for document in cursor: + programs.append(document) + + return jsonify(self.programs_schema.dump(programs)), 200 def get(self, _id: str): - pass + p = mongo.db.programs.find_one_or_404({"_id": ObjectId(_id)}) + return jsonify(self.program_schema.dump(p)), 200 + + @json_required def post(self): - pass - @route('<_id>/details') - def get_details(self, _id: str): - pass + try: + data = self.program_schema.load(request.json) + except ValidationError as e: + return abort(422, str(e)) + + mongo.db.programs.insert_one(data) # This appends _id + + return jsonify(self.program_schema.dump(data)), 201 def delete(self, _id: str): - pass + r = mongo.db.programs.delete_one({"_id": ObjectId(_id)}) + + if r.deleted_count > 0: + return Response(status=204) + else: + abort(404)