user.py 1.27 KB
Newer Older
Weizhi Cui's avatar
Weizhi Cui committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 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
#!/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 :
"""

from flask import Blueprint, request, jsonify
from application.services import UserService
from marshmallow import ValidationError

from application.schemas import UserSchema

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