log.py 1.46 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 20
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
21

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


@log_api.route('/logs', methods=['POST'])
def parse():
崔为之's avatar
崔为之 committed
29 30 31 32 33 34
    """
    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
35
    json_data = request.get_json(force=True)
崔为之's avatar
崔为之 committed
36 37

    # If no data provided, return error message
崔为之's avatar
崔为之 committed
38 39 40 41 42
    if not json_data:
        logger.error('No input data provided')
        return jsonify({"message": "No input data provided"}), 400

    try:
崔为之's avatar
崔为之 committed
43
        # Validate input data
崔为之's avatar
崔为之 committed
44 45
        item = ParseLogRequestItem(**json_data)
    except ValidationError as e:
崔为之's avatar
崔为之 committed
46
        # If validation fails, return error message
崔为之's avatar
崔为之 committed
47 48
        return jsonify({"message": "Invalid input data", "errors": e.errors()}), 400

崔为之's avatar
崔为之 committed
49
    # If validation passes, parse logs and return total number of logs parsed
崔为之's avatar
崔为之 committed
50
    total = LogService.parse(item)
崔为之's avatar
崔为之 committed
51
    return jsonify(search_total=total), 200