読者です 読者をやめる 読者になる 読者になる

KZKY memo

自分用メモ.

Flask-SQLAlchemy 基本

SQLAlchemyの基本

  • ORM: Object Relational Mapper
  • DMP: Data Mapper Pattern; classes mapped to a database

Quick Start

で事たりる

  • hello_sqlalchemy_mysql.py
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

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

username=""
password=""
host=""
port=""
dbname=""
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@server/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
  • ipython
from hello_sqlalchemy_mysql import db
from hello_sqlalchemy_mysql import User

db.create_all()

admin = User('admin', 'admin@example.com')
guest = User('guest', 'guest@example.com')

db.session.add(admin)
db.session.add(guest)
db.session.commit()

users = User.query.all()
admin = User.query.filter_by(username='admin').first()

MYSQLを使う

app.config['SQLALCHEMY_DATABASE_URI'] = "mysql://%s:%s@%s:%s/%s" %
                                                  (user, password, host, port, dbname)

Raw SQL

result = self.db.engine.execute("select * from job_status;")