49 lines
1.3 KiB
Python
49 lines
1.3 KiB
Python
#!/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):
|
|
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):
|
|
p = mongo.db.programs.find_one_or_404({"_id": ObjectId(_id)})
|
|
|
|
return jsonify(self.program_schema.dump(p)), 200
|
|
|
|
@json_required
|
|
def post(self):
|
|
|
|
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):
|
|
r = mongo.db.programs.delete_one({"_id": ObjectId(_id)})
|
|
|
|
if r.deleted_count > 0:
|
|
return Response(status=204)
|
|
else:
|
|
abort(404)
|