user.py 1.77 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 ElasticsearchUtils
Weizhi Cui's avatar
Weizhi Cui committed
20 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

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
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66


@user_api.route('/tests', methods=['POST'])
def test_user():
    data = request.get_json()
    start = data.get('start')
    end = data.get('end')
    dsl = ElasticsearchUtils.dsl(start, end)
    index = current_app.config.Elasticsearch.Index
    res = ElasticsearchUtils.search(index, dsl)
    print(len(res))
    data = {
        "user_name": "libai",
        "user_age": 18,
    }
    res_json = json.dumps(data)
    return res_json, 200