FlaskのTutorialのモデル部分をSQLAlchemyにしてみた(Declarative)。
database.py
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:////Users/kzfm/flask/flaskr/flaskr.db', convert_unicode=True)
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()
def init_db():
Base.metadata.create_all(bind=engine)
models.py
from sqlalchemy import Column, Integer, String, Text
from database import Base
class Entry(Base):
__tablename__ = 'entries'
id = Column(Integer, primary_key=True)
title = Column(String(500), unique=True)
text = Column(Text(), unique=True)
def __init__(self, title=None, text=None):
self.title = title
self.text = text
def __repr__(self):
return '<Title %r>' % (self.title)
これで、まだSQLiteのデータベースができてない場合にはpythonのシェルから
>>> from database import init.db
>>> from models import Entry
>>> init_db()
でデータベースが出来上がる。あとはflaskr部分。login,logoutはチュートリアルと一緒なので省略
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash
from contextlib import closing
from database import db_session
from models import Entry
DATABASE = '/Users/kzfm/flask/flaskr/flaskr.db'
DEBUG = True
SECRET_KEY = 'development key'
USERNAME = 'admin'
PASSWORD = 'default'
app = Flask(__name__)
app.config.from_object(__name__)
@app.after_request
def after_request(response):
db_session.remove()
return response
@app.route('/')
def show_entries():
entries = Entry.query.all()
return render_template('show_entries.html', entries=entries)
@app.route('/add', methods=['POST'])
def add_entry():
if not session.get('logged_in'):
abort(401)
entry = Entry(request.form['title'], request.form['text'])
db_session.add(entry)
db_session.commit()
return redirect(url_for('show_entries'))
簡単だ。
参考