728x90

Python을 사용하여 REST API를 구축하고 이를 Svelte 애플리케이션과 연동하는 방법을 설명하겠습니다. 이 과정은 다음 단계로 나뉩니다:

  1. Python REST API 구축: Python과 Flask를 사용하여 RESTful API를 구현합니다.
  2. Svelte 애플리케이션 개발: Svelte를 사용하여 사용자 인터페이스를 만들고, Python API와 통신하여 CRUD 작업을 수행합니다.

1단계: Python REST API 구축

1.1. 프로젝트 설정

Flask를 사용하여 REST API를 구축합니다. 먼저 Flask와 필요한 패키지를 설치합니다:

pip install flask flask-cors flask-mysql

1.2. 데이터베이스 설정

MySQL 또는 MariaDB에서 데이터베이스와 테이블을 생성합니다. MariaDB 콘솔이나 phpMyAdmin에서 다음 SQL을 실행합니다:

CREATE DATABASE my_database;
USE my_database;

CREATE TABLE items (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL
);

1.3. Flask 애플리케이션 작성

다음과 같은 구조로 프로젝트를 설정합니다:

/api
├── app.py

api/app.py:

from flask import Flask, request, jsonify
from flask_cors import CORS
import mysql.connector

app = Flask(__name__)
CORS(app)  # CORS 설정

# 데이터베이스 연결
def get_db_connection():
    conn = mysql.connector.connect(
        host='localhost',
        user='your-username',
        password='your-password',
        database='my_database'
    )
    return conn

@app.route('/items', methods=['GET'])
def get_items():
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)
    cursor.execute('SELECT * FROM items')
    items = cursor.fetchall()
    cursor.close()
    conn.close()
    return jsonify(items)

@app.route('/items', methods=['POST'])
def create_item():
    new_item = request.json
    name = new_item['name']
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute('INSERT INTO items (name) VALUES (%s)', (name,))
    conn.commit()
    cursor.close()
    conn.close()
    return jsonify({'id': cursor.lastrowid, 'name': name}), 201

@app.route('/items/<int:id>', methods=['PUT'])
def update_item(id):
    updated_item = request.json
    name = updated_item['name']
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute('UPDATE items SET name = %s WHERE id = %s', (name, id))
    conn.commit()
    cursor.close()
    conn.close()
    return jsonify({'id': id, 'name': name})

@app.route('/items/<int:id>', methods=['DELETE'])
def delete_item(id):
    conn = get_db_connection()
    cursor = conn.cursor()
    cursor.execute('DELETE FROM items WHERE id = %s', (id,))
    conn.commit()
    cursor.close()
    conn.close()
    return jsonify({'id': id})

if __name__ == '__main__':
    app.run(debug=True)

2단계: Svelte 애플리케이션 개발

2.1. 프로젝트 설정

Svelte 프로젝트를 설정하고 Axios를 설치합니다:

npx degit sveltejs/template svelte-frontend
cd svelte-frontend
npm install axios

2.2. Svelte 컴포넌트 작성

src/App.svelte:

<script>
    import axios from 'axios';

    let items = [];
    let newItem = '';
    let editItem = { id: null, name: '' };

    // Fetch items from the API
    const fetchItems = async () => {
        try {
            const response = await axios.get('http://localhost:5000/items');
            items = response.data;
        } catch (error) {
            console.error('Error fetching items:', error);
        }
    };

    // Add a new item
    const addItem = async () => {
        if (newItem.trim()) {
            try {
                const response = await axios.post('http://localhost:5000/items', { name: newItem });
                items = [...items, response.data];
                newItem = '';
            } catch (error) {
                console.error('Error adding item:', error);
            }
        }
    };

    // Start editing an item
    const startEdit = (item) => {
        editItem = { ...item };
    };

    // Update an existing item
    const updateItem = async () => {
        if (editItem.id !== null && editItehttp://m.name.trim()) {
            try {
                await axios.put(`http://localhost:5000/items/${editItem.id}`, { name: editItem.name });
                items = items.map(item => item.id === editItem.id ? editItem : item);
                editItem = { id: null, name: '' };
            } catch (error) {
                console.error('Error updating item:', error);
            }
        }
    };

    // Delete an item
    const deleteItem = async (id) => {
        try {
            await axios.delete(`http://localhost:5000/items/${id}`);
            items = items.filter(item => item.id !== id);
        } catch (error) {
            console.error('Error deleting item:', error);
        }
    };

    // Fetch items on component mount
    fetchItems();
</script>

<main>
    <h1>Items</h1>
    <input
        type="text"
        bind:value={newItem}
        placeholder="New item"
    />
    <button on:click={addItem}>Add Item</button>

    {#if editItem.id !== null}
        <div>
            <input
                type="text"
                bind:value={editItem.name}
                placeholder="Edit item"
            />
            <button on:click={updateItem}>Update Item</button>
        </div>
    {/if}

    <ul>
        {#each items as item}
            <li>
                {item.name}
                <button on:click={() => startEdit(item)}>Edit</button>
                <button on:click={() => deleteItem(item.id)}>Delete</button>
            </li>
        {/each}
    </ul>
</main>

<style>
    main {
        text-align: center;
        max-width: 800px;
        margin: 0 auto;
        padding: 1em;
    }

    input {
        margin: 0.5em;
    }
</style>

3단계: 실행 및 테스트

  1. Flask 서버 실행:

    Flask 애플리케이션을 실행합니다:

    python api/app.py

    기본적으로 http://localhost:5000에서 Flask API가 실행됩니다.

  2. Svelte 애플리케이션 실행:

    cd svelte-frontend
    npm run dev

    기본적으로 http://localhost:5000에서 Svelte 애플리케이션을 열 수 있습니다. 이 포트는 Flask와 충돌할 수 있으므로, 필요에 따라 Svelte의 기본 포트를 변경할 수 있습니다.

이제 http://localhost:5000에서 Svelte 애플리케이션을 열고 CRUD 작업을 테스트할 수 있습니다. Flask를 통해 제공된 REST API와 Svelte 애플리케이션이 성공적으로 연동되어 데이터베이스와 상호작용하게 됩니다.

참고 사항

  • CORS 설정: Flask의 flask-cors를 사용하여 CORS 문제를 해결합니다. 이를 통해 다른 출처에서 API에 접근할 수 있습니다.

  • 환경 설정: 실제 배포 환경에서는 보안 설정, 환경 변수 관리, 서버 설정 등을 추가로 고려해야 합니다.

  • 서버 포트: Flask와 Svelte가 동일한 포트에서 실행되면 충돌이 발생할 수 있습니다. Svelte의 npm run dev 명령어로 기본 포트를 변경할 수 있습니다. package.json에서 scripts 부분을 수정하여 포트를 변경할 수 있습니다.

이 예제는 기본적인 CRUD 작업을 다루며, 실제 애플리케이션에서는 추가적인 기능과 보안 조치를 고려해야 합니다.

728x90
반응형

'ChatGPT 대답' 카테고리의 다른 글

NodeJS 설명해줘  (0) 2024.07.22
Webpack 설명해줘  (0) 2024.07.22
PHP와 MariaDB를 사용하여 CRUD  (0) 2024.07.21
Svelte를 사용하여 MariaDB와 CRUD  (1) 2024.07.21
React와 MariaDB를 사용하여 CRUD  (0) 2024.07.21

+ Recent posts