log.py 1.82 KB
Newer Older
崔为之's avatar
崔为之 committed
1 2 3 4 5 6 7 8 9
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# @Version     : Python 3.11.4
# @Software    : Sublime Text 4
# @Author      : StudentCWZ
# @Email       : StudentCWZ@outlook.com
# @Date        : 2023/11/19 16:05
# @File        : log.py
崔为之's avatar
崔为之 committed
10
# @Description : Defines the log API endpoints.
崔为之's avatar
崔为之 committed
11 12
"""

崔为之's avatar
崔为之 committed
13
from flask import Blueprint, jsonify, request
崔为之's avatar
崔为之 committed
14 15 16 17 18 19
from flask_restful import Api
from loguru import logger
from pydantic import ValidationError

from application.schemas import ParseLogRequestItem
from application.services import LogService
崔为之's avatar
崔为之 committed
20 21
from application.libs import JsonResponse
from application.libs import ServerError
崔为之's avatar
崔为之 committed
22

崔为之's avatar
崔为之 committed
23

崔为之's avatar
崔为之 committed
24
# Define the log API blueprint
崔为之's avatar
崔为之 committed
25 26 27 28 29 30
log_api = Blueprint('log_api', __name__)
api_logs = Api(log_api)


@log_api.route('/logs', methods=['POST'])
def parse():
崔为之's avatar
崔为之 committed
31 32 33 34 35 36
    """
    Parses the logs based on the request.

    Returns:
        The total number of logs parsed or an error message if the input data is invalid.
    """
崔为之's avatar
崔为之 committed
37
    json_data = request.get_json(force=True)
崔为之's avatar
崔为之 committed
38 39

    # If no data provided, return error message
崔为之's avatar
崔为之 committed
40 41
    if not json_data:
        logger.error('No input data provided')
崔为之's avatar
崔为之 committed
42
        return JsonResponse.error(message='No input data provided', status_code=400)
崔为之's avatar
崔为之 committed
43 44

    try:
崔为之's avatar
崔为之 committed
45
        # Validate input data
崔为之's avatar
崔为之 committed
46 47
        item = ParseLogRequestItem(**json_data)
    except ValidationError as e:
崔为之's avatar
崔为之 committed
48
        # If validation fails, return error message
崔为之's avatar
崔为之 committed
49 50
        logger.error(f'Invalid input data, error: {e}')
        return JsonResponse.error(message='Invalid input data', status_code=400)
崔为之's avatar
崔为之 committed
51

崔为之's avatar
崔为之 committed
52
    # If validation passes, parse logs and return total number of logs parsed
崔为之's avatar
崔为之 committed
53 54 55 56 57 58 59
    try:
        total = LogService.parse(item)
    except ServerError as e:
        logger.error('Internal server error')
        return JsonResponse.error(message='Internal server error', status_code=500)
    else:
        return JsonResponse.success(message='Successfully parsed', data=total)