Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
95
Help us understand the problem. What is going on with this article?
@msrks

Flask-SQLAlchemyの使い方

More than 3 years have passed since last update.

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()
95
Help us understand the problem. What is going on with this article?
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
msrks
Computer Scienceと物理が好きです

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
95
Help us understand the problem. What is going on with this article?