46 lines
1.4 KiB
Python
46 lines
1.4 KiB
Python
from flask import Blueprint, jsonify, request
|
|
|
|
def generate_crud_blueprint(model, service):
|
|
bp = Blueprint(model.__name__.lower(), __name__)
|
|
|
|
@bp.get('/')
|
|
def list_items():
|
|
items = service.list(request.args)
|
|
try:
|
|
return jsonify([item.as_dict() for item in items])
|
|
except Exception as e:
|
|
return jsonify({"status": "error", "error": str(e)})
|
|
|
|
@bp.get('/<int:id>')
|
|
def get_item(id):
|
|
item = service.get(id, request.args)
|
|
try:
|
|
return jsonify(item.as_dict())
|
|
except Exception as e:
|
|
return jsonify({"status": "error", "error": str(e)})
|
|
|
|
@bp.post('/')
|
|
def create_item():
|
|
obj = service.create(request.json)
|
|
try:
|
|
return jsonify(obj.as_dict())
|
|
except Exception as e:
|
|
return jsonify({"status": "error", "error": str(e)})
|
|
|
|
@bp.patch('/<int:id>')
|
|
def update_item(id):
|
|
obj = service.update(id, request.json)
|
|
try:
|
|
return jsonify(obj.as_dict())
|
|
except Exception as e:
|
|
return jsonify({"status": "error", "error": str(e)})
|
|
|
|
@bp.delete('/<int:id>')
|
|
def delete_item(id):
|
|
service.delete(id)
|
|
try:
|
|
return jsonify({"status": "success"}), 204
|
|
except Exception as e:
|
|
return jsonify({"status": "error", "error": str(e)})
|
|
|
|
return bp
|