0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[備忘録]カテゴリをDBに登録&取得してフロントに表示してみた

Last updated at Posted at 2025-04-08

まえおき

自分用なので端折ってるところ多いです

やりたいこと

  • SQLALchemyでDBとカテゴリーテーブルを初期化
  • 初期カテゴリーデータを登録
  • Flask APIでカテゴリー一覧を返す
  • JavaScriptでカテゴリー取得→ボタン表示
  • ついでにCIRSエラー対処

DBを初期化してカテゴリー登録

モデル定義

models.py
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class Category(db.Model):
    __tablename__ = 'categories'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    expence_type = db.Column(db.String(10), nullable=False)
    

初期化スクリプト

init_db.py
from flask import Flask
from models import db, Category

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///your_db.sqlite'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db.init_app(app)

initial_categories = [
    # expense
    ("食費", "expense"), ("交通費", "expense"), ("娯楽", "expense"),
    ("日用品", "expense"), ("医療", "expense"), ("通信費", "expense"),
    ("交際費", "expense"), ("教育", "expense"), ("光熱費", "expense"),
    ("家賃", "expense"), ("貯金", "expense"), ("その他", "expense"),
    # income
    ("給料", "income"), ("ボーナス", "income"), ("副業", "income"),
    ("投資収入", "income"), ("その他収入", "income"),
]

with app.app_context():
    db.drop_all()
    db.create_all()

    for name, expence_type in initial_categories:
        db.session.add(Category(name=name, expence_type=expence_type))
    
    db.session.commit()
    print("DB初期化&カテゴリ登録完了!")

実行

python init_db.py

Flask APIを作成

app.py
from flask import Flask, jsonify
from flask_cors import CORS
from models import db, Category

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///your_db.sqlite'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db.init_app(app)
CORS(app)

@app.route("/api/categories")
def get_categories():
    categories = Category.query.all()
    result = [
        {
            "id": cat.id,
            "name": cat.name,
            "expence_type": cat.expence_type
        }
        for cat in categories
    ]
    return jsonify(result)

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

JavaScriptでカテゴリを取得&表示

async fetchCategories() {
    try {
        const res = await fetch("http://localhost:5000/api/categories");
        const data = await res.json();

        const categories = { expense: [], income: [] };
        data.forEach(item => {
            const type = item.expence_type;
            if (type === "expense" || type === "income") {
                categories[type].push(item.name);
            }
        });

        this.categories = categories;
        this.render(); // 表示更新
    } catch (err) {
        console.error("カテゴリ取得エラー:", err);
        alert("カテゴリーの取得に失敗しました");
    }
}

CORS対策

  • pip install flask-cors
  • from flask-cors import CORS
  • CORS(app) を追加

最後に

# DB初期化(1回だけ)
python init_db.py

# Flaskアプリ起動
python app.py

# フロントから http://localhost:5000/api/categories
にアクセス

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?