pip install flask_sqlalchemy
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:{계정}@{주소}/{DB명}'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False # 참고: https://github.com/pallets/flask-sqlalchemy/issues/365
db = SQLAlchemy(app)
class Item(db.Model):
__tablename__ = 'item'
id = db.Column(db.Integer, primary_key=True)
item_name = db.Column(db.String(250))
item_id = db.Column(db.String(250))
# __init__method는 SQLAlchemy가 자동 생성
# def __init__(self, item_name, item_id):
# self.item_name = item_name
# self.item_id = item_id
# Super class의 생성자를 override하고 싶은 경우
def __init__(**kwargs):
super(Item, self).__init__(**kwargs)
# 위와 같이 Super class의 생성자를 먼저 호출하고, 추가 작업 진행
def __repr__(self):
return "<Item('%d', '%s', '%s', '%s')>" % (self.id, self.item_name, self.item_id)
db.create_all()
item_1 = Item(item_name='레인보우라이트 50+ 멀티비타민 미니-타블렛', item_id='123456')
item_2 = Item(item_name='멀티비타민앤미네랄 영양제 보충제 포틴', item_id='654321')
db.session.add(item_1)
db.session.add(item_2)
db.session.commit()
# table 전체 쿼리
Item.query.all()
# 조건 쿼리
User.query.filter_by(username='admin').first()
from datetime import datetime
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(80), nullable=False)
body = db.Column(db.Text, nullable=False)
pub_date = db.Column(db.DateTime, nullable=False,
default=datetime.utcnow)
category_id = db.Column(db.Integer, db.ForeignKey('category.id'),
nullable=False)
category = db.relationship('Category',
backref=db.backref('posts', lazy=True))
def __repr__(self):
return '<Post %r>' % self.title
class Category(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50), nullable=False)
def __repr__(self):
return '<Category %r>' % self.name
py = Category(name='Python')
# Post object는 Category add 시 함께 추가되기 때문에 별도로 추가할 필요 x
Post(title='Hello Python!', body='Python is pretty cool', category=py)
p = post(title='Snakes', body='Ssssss')
py.posts.append(p)
db.session.add(py)
https://flask-sqlalchemy.palletsprojects.com/en/2.x/quickstart/#a-minimal-application