101
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

Flask-SQLAlchemyの使い方

Flask-SQLAlchemy: FlaskでSQLALchemyを簡単に扱うための拡張

インストール
$ pip install flask-sqlalchemy

使い方

1. モデルを作る

  • db = flask_sqlalchemy.SQLAlchemy()をつくる
  • db.Modelを継承してモデルをつくる
  • db.Columnでcolumnを定義する
  • db.relationshipでモデル同士を繋ぐ
app.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

    def __init__(self, username, email):
        self.username = username
        self.email = email

    def __repr__(self):
        return '<User %r>' % self.username

2. データベースを作る

>>> from app import db
>>> db.create_all()

3. CRUD操作

create

user = User('shinzo', 'shinzo.abe@example.com')
db.session.add(user)
db.session.commit()

read all

users = User.query.all()

read, delete

user = db.session.query(User).filter_by(name='shinzo').first()
db.session.delete(user)
db.session.commit()

read, update

user = db.session.query(User).filter_by(name='shinzo').first()
user.email = 'shinzo.abe@google.com'
db.session.add(user)
db.session.commit()
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
101
Help us understand the problem. What are the problem?