Python Flask Tutorial #4 - Database with Flask-SQLAlchemy

· 6년 전 · 1631

 

Flask-SQLAlchemy에 대해서 배웁니다.

 

https://flask-sqlalchemy.palletsprojects.com/en/2.x/

 

SQLAlchemy는 여러가지 데이타베이스를 지원합니다.  

https://docs.sqlalchemy.org/en/13/core/engines.html

 

PostgreSQL

MySQL

Oracle

Microsoft SQL Server

SQLite

 

몽고 DB는 별도로 지원합니다. https://pythonhosted.org/Flask-MongoAlchemy/

 

```

pipenv install flask-sqlalchemy

```

 

> pipfile에 제대로 등록되어 있는지 체크하세요

 

```

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

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(120), unique=True, nullable=False)

    image_file = db.Column(db.String(20), nullable=False, default='default.jpg')

    password = db.Column(db.String(60), nullable=False)

    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.title}', '{self.date_posted}')"

```

 

현재 디렉토리에 site.db라는 sqlite파일이 만들어집니다.  

 

테이블은 2개 user, post

 

https://sqlitebrowser.org/   로 확인해보면

 

1808292852_1575603769.9969.png

 

python을 실행해서 Command라인에서 바로 입력해서 확인하니 좋네요..

 

user와 post의 관계는 one to many  관계입니다.

 

User 는 many Post를 가질수 있고,  Post는 one User만 있게 됩니다.

 

 

Relationship에서 lazy 옵션이 있는데,  이것에 대한 설명

 

|
댓글을 작성하시려면 로그인이 필요합니다.

파이썬 게시판 만들기

+
제목 글쓴이 날짜 조회
6년 전 조회 1,217
6년 전 조회 1,537
6년 전 조회 1,476
6년 전 조회 1,118
6년 전 조회 922
6년 전 조회 1,195
6년 전 조회 1,834
6년 전 조회 1,296
6년 전 조회 1,008
6년 전 조회 1,381
6년 전 조회 982
6년 전 조회 1,223
6년 전 조회 1,453
6년 전 조회 1,248
6년 전 조회 1,632
6년 전 조회 1,288
6년 전 조회 1,225
6년 전 조회 1,156
6년 전 조회 2,550
6년 전 조회 1,070
6년 전 조회 2,591
6년 전 조회 1,060
6년 전 조회 1,169
6년 전 조회 1,215
6년 전 조회 1,431
6년 전 조회 1,125
6년 전 조회 1,176
6년 전 조회 1,183
6년 전 조회 1,299
6년 전 조회 1,026