#1. DB 연동하여 Web 만들기

12408 단어 Face OutFace Out

1. 전체 구성



2. MySQL에서 mosaic db 만들기



3. init.py

from flask import Flask, render_template, request
from werkzeug.utils import secure_filename
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Question, QuestionContent

engine = create_engine('mysql+pymysql://root:root@localhost/mosaic')
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
session = DBSession()

app = Flask( __name__)

4. database_setup.py

from sqlalchemy import Column, ForeignKey, Integer, String, Text, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine

Base = declarative_base()

class Question(Base):
    __tablename__ = 'question'

    id = Column(Integer, primary_key=True) # 카테고리 번호
    name = Column(String(100), nullable=False) # 카테고리 이름

    @property
    def serialize(self):
        return {
            'name': self.name,
            'id': self.id,
        }

class QuestionContent(Base):
    __tablename__ = 'question_content'

    id = Column(Integer, primary_key=True) # 질문 번호
    content = Column(Text, nullable=False) # 질문 내용
    create_date = Column(DateTime(), nullable=False) # 질문 등록날짜

    question_id = Column(Integer, ForeignKey('question.id'))
    question = relationship(Question)  # 질문이랑 연결

    @property
    def serialize(self):
        return {
            'id': self.id,
            'content':self.content,
            'create_date':self.create_date,
        }


engine = create_engine('mysql+pymysql://root:root@localhost/mosaic')
Base.metadata.create_all(engine)

5. mosaic_data.py

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from database_setup import Base, Question, QuestionContent

engine = create_engine('mysql+pymysql://root:root@localhost/mosaic')
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
session = DBSession()

question_upload = Question(name='동영상 업로드')
question_download = Question(name='동영상 다운로드')
question_save = Question(name='동영상 저장')
question_notice = Question(name='공지사항')

session.add(question_upload)
session.add(question_download)
session.add(question_save)
session.add(question_notice)
session.commit()

# 데이터 잘 들어가는지 확인용
question_content1 = QuestionContent(content='됐나?', create_date='2021-8-10', question=question_upload)

session.add(question_content1)
session.commit()

6. table간의 관계

question_content table에서 question_id 가 의미하는 것은 question table에서 id가 1인 동영상 업로드와 연결된다는 의미

question table

question_content table


7. 실행

database_setup.py 실행 -> mosaic_data.py 실행 -> __init__.py 실행

좋은 웹페이지 즐겨찾기