아미(아름다운미소)

fastapi mysql crud & javascript & flutter 예제 본문

랭귀지/python

fastapi mysql crud & javascript & flutter 예제

유키공 2024. 6. 22. 18:56

fastapi

from typing import List
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from dbhelper import DBHelper

app = FastAPI()

# DBHelper 인스턴스 생성
db = DBHelper(host='localhost', user='your_username', password='your_password', database='your_database')
db.connect()

# 사용자 데이터 모델
class User(BaseModel):
    id: int
    name: str
    email: str

# CRUD 엔드포인트
@app.get("/users", response_model=List[User])
def read_users():
    # 사용자 목록 조회
    users = db.read('users').fetchall()
    return [User(**dict(user)) for user in users]

@app.post("/users", response_model=User, status_code=201)
def create_user(user: User):
    # 새 사용자 생성
    user_id = db.create('users', user.dict())
    user.id = user_id
    return user

@app.get("/users/{user_id}", response_model=User)
def read_user(user_id: int):
    # 특정 사용자 조회
    user = db.read('users', {'id': user_id}).fetchone()
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return User(**dict(user))

@app.put("/users/{user_id}", response_model=User)
def update_user(user_id: int, user: User):
    # 사용자 정보 업데이트
    db.update('users', user.dict(), {'id': user_id})
    return user

@app.delete("/users/{user_id}", status_code=204)
def delete_user(user_id: int):
    # 사용자 삭제
    db.delete('users', {'id': user_id})

호출 javascript

// 모든 사용자 목록 조회
fetch('/users')
  .then(response => response.json())
  .then(data => console.log(data));

// 새 사용자 생성
const newUser = { name: 'John Doe', email: 'john.doe@example.com' };
fetch('/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(newUser)
})
  .then(response => response.json())
  .then(data => console.log(data));

// 특정 사용자 정보 조회
const userId = 1;
fetch(`/users/${userId}`)
  .then(response => response.json())
  .then(data => console.log(data));

// 사용자 정보 업데이트
const updatedUser = { name: 'Jane Doe' };
fetch(`/users/${userId}`, {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(updatedUser)
})
  .then(response => response.json())
  .then(data => console.log(data));

// 사용자 삭제
fetch(`/users/${userId}`, {
  method: 'DELETE'
})
  .then(response => console.log(response.status));

플러터로 호출

yaml

dependencies:
  flutter:
    sdk: flutter
  http: ^0.13.0

dart

import 'dart:convert';
import 'package:flutter/[PII](URL)';
import 'package:http/[PII](URL)';

class User {
  final int id;
  final String name;
  final String email;

  User({required this.id, required this.name, required this.email});

  factory User.fromJson(Map<String, dynamic> json) {
    return User(
      id: json['id'],
      name: json['name'],
      email: json['email'],
    );
  }
}

class UserService {
  static const _baseUrl = 'http://your_fastapi_server/users';

  static Future<List<User>> getUsers() async {
    final response = await [PII](URL).get(_baseUrl);
    if (response.statusCode == 200) {
      final List<dynamic> usersJson = json.decode(response.body);
      return usersJson.map((json) => User.fromJson(json)).toList();
    } else {
      throw Exception('Failed to load users');
    }
  }

  static Future<User> createUser(String name, String email) async {
    final response = await [PII](URL).post(
      _baseUrl,
      headers: {'Content-Type': 'application/json'},
      body: json.encode({'name': name, 'email': email}),
    );
    if (response.statusCode == 201) {
      return User.fromJson(json.decode(response.body));
    } else {
      throw Exception('Failed to create user');
    }
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'User Management',
      home: UserList(),
    );
  }
}

class UserList extends StatefulWidget {
  @override
  _UserListState createState() => _UserListState();
}

class _UserListState extends State<UserList> {
  late Future<List<User>> _users;

  @override
  void initState() {
    super.initState();
    _users = UserService.getUsers();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('User List'),
      ),
      body: FutureBuilder<List<User>>(
        future: _users,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return ListView.builder(
              itemCount: snapshot.data!.length,
              itemBuilder: (context, index) {
                final user = snapshot.data![index];
                return ListTile(
                  title: Text(user.name),
                  subtitle: Text(user.email),
                );
              },
            );
          } else if (snapshot.hasError) {
            return Center(
              child: Text('Error: ${snapshot.error}'),
            );
          } else {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          final newUser = await UserService.createUser('John Doe', 'john.doe@example.com');
          setState(() {
            _users = UserService.getUsers();
          });
        },
        child: Icon(Icons.add),
      ),
    );
  }
}

'랭귀지 > python' 카테고리의 다른 글

타입지정  (0) 2024.06.26
pandas 날짜차이 분으로 환산  (0) 2024.06.24
flask restapi mysql 예제  (0) 2024.06.22
python mysql dbhelper  (0) 2024.06.22
pandas lamda 예제  (0) 2024.06.22
Comments