Event-CRUD-Flask-python3-API/routes/eventRoutes.py

87 lines
No EOL
2.9 KiB
Python

from flask import Blueprint, jsonify, request, g
from services.EventService import EventService
from middlewares.userMiddlewares import authenticate_user
from middlewares.eventMiddlewares import validate_event_post_request
eventRoutes = Blueprint('eventRoutes', __name__)
# Create new event
@eventRoutes.route('/', methods=['POST'])
@eventRoutes.route('', methods=['POST'])
@validate_event_post_request
@authenticate_user
def create_event():
try:
data = request.json
data['user_id'] = g.user_id
new_event = EventService.create_event(data)
if new_event:
return jsonify(new_event.to_dict()), 201
else:
return jsonify({'error': 'Failed to create event'}), 400
except Exception as e:
return jsonify({'error': str(e)}), 500
@eventRoutes.route('/', methods=['GET'])
@eventRoutes.route('', methods=['GET'])
def get_events():
try:
location = request.args.get('location')
sort_by = request.args.get('sort_by')
user_events = EventService.get_upcoming_events(location, sort_by)
return {"events": user_events, "count": len(user_events)}, 200
except Exception as e:
return {"error": str(e)}, 500
@eventRoutes.route('/<int:event_id>', methods=['GET'])
@authenticate_user
def get_event(event_id):
try:
return {"event": EventService.get_event_by_id(event_id, g.user_id)}, 200
except Exception as e:
return {"error": str(e)}, 500
@eventRoutes.route('/<int:event_id>', methods=['PUT'])
@validate_event_post_request
@authenticate_user
def update_event(event_id):
try:
data = request.json
updated_event = EventService.update_event(event_id, data)
if updated_event:
return jsonify(updated_event.to_dict()), 200
else:
return jsonify({'error': 'Event not found'}), 404
except Exception as e:
return jsonify({'error': str(e)}), 500
@eventRoutes.route('/<int:event_id>', methods=['DELETE'])
@authenticate_user
def delete_event(event_id):
try:
deleted_event = EventService.delete_event(event_id)
if deleted_event:
return jsonify(deleted_event.to_dict()), 200
else:
return jsonify({'error': 'Event not found'}), 404
except Exception as e:
return jsonify({'error': str(e)}), 500
@eventRoutes.route('/<int:event_id>/attend', methods=['POST'])
@authenticate_user
def attend_event(event_id):
response = EventService.attend_event(event_id)
if 'error' in response:
return jsonify({'error': response['error']}), 400
return jsonify({'message': response['message']}), 200
@eventRoutes.route('/<int:event_id>/unattend', methods=['POST'])
@authenticate_user
def unattend_event(event_id):
response = EventService.unattend_event(event_id)
if 'error' in response:
return jsonify({'error': response['error']}), 400
return jsonify({'message': response['message']}), 200