티스토리 뷰

개요

python으로 db로직을 개발 할 때 사용하기 위해 sqlAlchemy, sqlite로 db에 table을 create하고 insert, select를 하는 로직입니다.

 

Git Repository

Kyeongrok/python-sqlalchemy (github.com)

 

GitHub - Kyeongrok/python-sqlalchemy

Contribute to Kyeongrok/python-sqlalchemy development by creating an account on GitHub.

github.com

 

Create Db, Insert

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///hello.db'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    email = db.Column(db.String(20), unique=True, nullable=False)
    image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
    password = db.Column(db.String(60), nullable=False, default='default.jpg')
    posts = db.relationship('Post', backref='author', lazy=True)

    def __repr__(self):
        return f"User('{self.username}', '{self.email}', '{self.image_file}')"

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    content = db.Column(db.Text, nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

    def __repr__(self):
        return f"Post('{self.id}', '{self.title}', '{self.date_posted}')"

db.create_all()

위 코드를 실행하면 hello.db라는 파일이 생성 됩니다.

Select

user_1 = User(username='kyeongrok', email='oceanfog1@gmail.com', password='12345')
db.session.add(user_1)
db.session.commit()

user = db.query.get(1)
print(user)
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
글 보관함