Quantcast
Channel: 一言多いプログラマーの独り言
Viewing all articles
Browse latest Browse all 846

Python+Flaskに、ORMのSQLAlchemyを設定

$
0
0
Python+Flaskに、ORMのSQLAlchemyを設定してみました。SQLite3のデータベースに接続しています。


from flask import Flask
from flask_sqlalchemy import SQLAlchemy

# 初期設定
app.config.update(dict(
SQLALCHEMY_DATABASE_URI = 'sqlite:////path/to/flaskr.db',
))

# DB接続
db = SQLAlchemy(app)

# モデルの定義
class Entry(db.Model):
__tablename__ = 'entries'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(500), unique=True)
text = db.Column(db.Text(), unique=True)

def __init__(self, title=None, text=None):
self.title = title
self.text = text

def __repr__(self):
return '<Title %r>' % (self.title)

@app.route('/')
def index():
# 接続
entries = Entry.query.all()
return render_template('index.html', entries=entries)

実際に設定してみたのがこちら

参考サイト
Flask-SQLAlchemy(Flask-SQLAlchemy Documentation)
FlaskrのモデルをSQLAlchemyで(drkcoreさん)

Viewing all articles
Browse latest Browse all 846

Trending Articles