resource impl
This commit is contained in:
53
api/resource.py
Normal file
53
api/resource.py
Normal file
@@ -0,0 +1,53 @@
|
||||
#api/resource.py
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from contexts.RequestContext import RequestContext
|
||||
from db import get_db
|
||||
from db.models.Resource import Resource
|
||||
from api import require_auth
|
||||
import logging
|
||||
resource_bp = Blueprint('resource', __name__, url_prefix='/api/resource')
|
||||
logger = logging.getLogger(__name__)
|
||||
@resource_bp.route('/<identifier>', methods=['GET'])
|
||||
def get_resource(identifier):
|
||||
with get_db() as db:
|
||||
resource = db.query(Resource).get(identifier)
|
||||
if resource is None:
|
||||
logger.error(f"resource not found: {identifier}")
|
||||
errno = RequestContext.get_error_id()
|
||||
return jsonify({"error": f"resource not found - {errno}"}), 404
|
||||
return jsonify(resource.to_dict()), 200
|
||||
|
||||
@resource_bp.route('/', methods=['POST'])
|
||||
@require_auth(roles=["admin", "creator"])
|
||||
def create_resource():
|
||||
data = request.get_json()
|
||||
identifier = data.get('id')
|
||||
content = data.get('content')
|
||||
data_type = data.get('data_type')
|
||||
if not identifier or not content or not data_type:
|
||||
return jsonify({"error": "missing required fields"}), 400
|
||||
resource_entry = Resource(id=identifier, content=content, data_type=data_type)
|
||||
with get_db() as db:
|
||||
try:
|
||||
db.add(resource_entry)
|
||||
db.commit()
|
||||
return jsonify(resource_entry.to_dict()), 201
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
logger.error(f"Failed to create resource: {e}")
|
||||
errno = RequestContext.get_error_id()
|
||||
return jsonify({"error": f"failed to create resource - {errno}"}), 500
|
||||
|
||||
@resource_bp.route('/<identifier>', methods=['DELETE'])
|
||||
@require_auth(roles=["admin"])
|
||||
def delete_resource(identifier):
|
||||
with get_db() as db:
|
||||
resource = db.query(Resource).get(identifier)
|
||||
if not resource:
|
||||
logger.error(f"resource not found: {identifier}")
|
||||
errno = RequestContext.get_error_id()
|
||||
return jsonify({"error": f"Resource not found - {errno}"}), 404
|
||||
db.delete(resource)
|
||||
db.commit()
|
||||
return jsonify({"message": "Resource deleted"}), 200
|
||||
Reference in New Issue
Block a user