user.py 1.88 KB
Newer Older
Weizhi Cui's avatar
Weizhi Cui committed
1 2 3 4 5 6 7 8 9 10 11 12
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
# @Version     : Python 3.11.4
# @Software    : Sublime Text 4
# @Author      : StudentCWZ
# @Email       : StudentCWZ@outlook.com
# @Date        : 2023/10/29 00:08
# @File        : user.py
# @Description :
"""

崔为之's avatar
崔为之 committed
13 14
import json
from flask import Blueprint, current_app, request, jsonify
Weizhi Cui's avatar
Weizhi Cui committed
15 16 17 18
from application.services import UserService
from marshmallow import ValidationError

from application.schemas import UserSchema
崔为之's avatar
崔为之 committed
19
from application.utils import ElasticsearchUtil
崔为之's avatar
崔为之 committed
20
from application.common import ConfigHelper
Weizhi Cui's avatar
Weizhi Cui committed
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

user_api = Blueprint('user_api', __name__)


@user_api.route('/users', methods=['GET'])
def get_users():
    users = UserService.get_all_users()
    return jsonify([user.to_dict() for user in users])


@user_api.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
    user = UserService.get_user_by_id(user_id)
    if user is None:
        return jsonify({'error': 'User not found'}), 404
    return jsonify(user.to_dict())


@user_api.route('/users', methods=['POST'])
def create_user():
    user_schema = UserSchema()
    try:
        data = user_schema.load(request.json)
    except ValidationError as e:
        return jsonify(e.messages), 400
    username = data.username
    password = data.password
    email = data.email
    user = UserService.create_user(username, password, email)
    return jsonify(user_schema.dump(user)), 201
崔为之's avatar
崔为之 committed
51 52 53 54


@user_api.route('/tests', methods=['POST'])
def test_user():
崔为之's avatar
崔为之 committed
55 56 57
    ch = ConfigHelper(current_app)
    print(ch.System)
    print(ch.Sys)
崔为之's avatar
崔为之 committed
58 59 60
    data = request.get_json()
    start = data.get('start')
    end = data.get('end')
崔为之's avatar
崔为之 committed
61
    dsl = ElasticsearchUtil.dsl(start, end)
崔为之's avatar
崔为之 committed
62
    index = current_app.config.Elasticsearch.Index
崔为之's avatar
崔为之 committed
63
    res = ElasticsearchUtil.search(index, dsl)
崔为之's avatar
崔为之 committed
64 65 66 67 68 69 70
    print(len(res))
    data = {
        "user_name": "libai",
        "user_age": 18,
    }
    res_json = json.dumps(data)
    return res_json, 200