Ch 02 데이터 베이스를 이용한 앱만들기
2.2 앱 실행하기: Blueprint의 이용
- CRUD- Create(데이터 작성) Read Update Delete
- Blueprint?
- 앱을 분할하기 위한 플라스크 기능 ⇒ 앱의 규모가 커져도 간결한 상태유지
- Blueprint 단위로 템플릿/정적 파일을 나눌 수 있다.
- Blueprint 인수 설명인수 테이블 (page 92)
- Blueprint 객체 생성예
# Blueprint 객체 생성 예 sample = Blueprint( __name__, "sample", # Blueprint 앱 이름 static_folder="static", # Blueprint 앱의 static 파일용 폴더 디렉터리(폴더 위치) ex styl.css template_folder="templates", # Blueprint 앱의 템플릿 파일 폴더 디렉터리, xx.html 과 연결하기 위함 url_prefix="/sample", # Blueprint앱의 모든 URL의 맨앞에 추가하여 다른 앱의 경로와 구별 하기 위한 경로 subdomain="example", # Blueprint를 서브 도매인으로 하는 경우에 지정 ) # Blueprint 객체 등록 app.register_blueprint(sample, url_prefix="/sample", subdomain="example")
- CRUD 모듈 앱 작성 예( 90page)
- from apps.crud import views as crud_views
- 현재 만든 apps 라는 폴더에서 curd 폴더에 있는 views.py 라는 파일을 호출
- from apps.crud import views as crud_views
- 엔드포인트 만들기
- apps/crud/view.py 를 작성하고 여기에 crud 앱의 엔드 포인트 만
from flask import Blueprint, render_template ------------------------------------- Q # Blueprint로 crud 앱을 생성한다 crud = Blueprint( "crud", template_folder="templates", static_folder="static". ) # index 엔드포인트를 작성하고 index.html을 반환한다 @crud.route("/") def index(): return render_template("crud/index.html")
- apps/crud/view.py 를 작성하고 여기에 crud 앱의 엔드 포인트 만
- Blueprint?
2.3 SQLAlchemy 설정하기
- SQLAlchemy? O/R or ORM (Object-Relational Mapping)
- SQLAlchemy 가 python 코드를 SQL로 변환
- SQL코드를 쓰지 않고도 Python을 이용하여서 데이터베이스 조작가능.
- SQLAlchemy 가 python 코드를 SQL로 변환
- 확장 기능 설치
- pip install flask-sqlalchemy
- pip install flask-migrate
- 사용법 코드 ⇒ p. 100
2.4 데이터 베이스 조작
- model.py 에 유저 모델을 정의 (p.102) 하고 마이그레이션 함으로써 DB에 유저테이블 작성 가능
- 모델을 사용하기 위해서 apps/crud/__init__.py
- models.py 선언 import apps.crud.models
- 모델을 사용하기 위해서 apps/crud/__init__.py
- flask db 관련 명령어를 파워셀에 입력하여서 데이터베이스 초기화 및 마이그레션하기
- flask db init
- 주소를 적는거라고 생각했는데 왜 숫자를 요구할까?
File "E:\_CosmosMedic\스터디\Flask\venv\lib\site-packages\sqlalchemy\engine\url.py", line 893, in _parse_url components["port"] = int(components["port"]) ValueError: invalid literal for int() with base 10: '\\_CosmosMedic\\스터디\\Flask\\local.sqlite'
- 해 ⇒ A code in page 100 수정 필요
# 앱의 config 설정 # app.config.from_mapping( # SECRET_KEY="2AZSMss3p5QPbcY2hBsJ", # SQLALCHEMY_DATABASE_URI=f"sqlite://{Path(__file__).parent.parent / 'local.sqlite'}", # SQLALCHEMY_TRACK_MODIFICATIONS=False, # ) import os basedir = os.path.abspath(os.path.dirname(__file__)) app.config["SECRET_KEY"] = "2AZSMss3p5QPbcY2hBsJ" app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + os.path.join( basedir, "database.sqlite " ) app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
- 주소를 적는거라고 생각했는데 왜 숫자를 요구할까?
- flask db migrate 실행시 models.py 에 정의 된 테이블 명(users) 및 칼럼의 정보가 생성
- flask db upgrade 실행시 생성된 users 테이블 생성
- flask db init
- 생성된 데이터베이스는 vscode로 확인 가능
- VScode 에서 SQLite 와 SQLite Viewer 설치
- local.sqlite 에서 확인가능
- SQLAIchenu를 사용한 기본적인 데이터 조작 방법은 p.107 참조
2.5 데이터베이스 이용한 crud 앱 만들기
- pip install flask-wtf <유효성 검증이나 CSRF에 대 처하기 위한 폼을 작성하는 플라스크 확장>
- 실습내용
- 사용자를 신규 장성하기 (p. 117)
- 사용자 일람 표시하기 (p. 125)
- 사용자 편집하기 (p. 127)
- 사용자 삭제하기 (p. 131)
2.6 템플릿의 공통화 상속
- jinja2 템플릿 엔진에는 HTML 공통의 템플릿 파일을 상속하는 기능소유
- base.html 을 생성하여서 HTML 파일에 중복되는 것을 작성하기 (p.133)
<!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8" /> <!-- title을 상속처에서 구현한다 --> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="{{ url_for('crud.static', filename='style.css') }}" /> </head> <body> <!-- content를 상속처에서 구현한다 --> {% block content %}{% endblock %} <!-- 상속처에 개별의 구현이 필요하면 여러 개를 사용 --> <!-- 예시 --> <table> {% block table%} {% endblock %} </table> </body> </html>
- base.html 사용법
<!-- base.html 상속 해서 --> {% extends "crud/base.html" %} {% block title %}사용자의 일람{% endblock %} <!-- body --> {% block content %} <h2> base.html 사용법</h2> ..... {%block table} <tr> <th> ID </th> <th>사용자 명 </th> <th>메일주소</th> </tr> {% endblock %}
- base.html 을 생성하여서 HTML 파일에 중복되는 것을 작성하기 (p.133)
2.7 config 설정하기
- 앱 개발환경 등 각각의 환경에 설정해야 하는 config의 값이 환경마다 다르므로 직접기입하지 않고 config를 읽어들어버리는 방법을 학습
- 설정 방식
- from_object를 사용하는 방법 (p. 137)
- from_mapping을 사용하는 방법 (p. 139)
- from_envvar를 사용하는 방법 ( p. 140)
- from_pyfile을 사용하는 방법 (p. 141)
- from_file을 사용하는 방법 (p. 142)
'책 > Python Flask Web App 개발입문' 카테고리의 다른 글
Part 0 파이썬 플라스크 소개 (3) | 2023.11.21 |
---|---|
책관련 자료 (1) | 2023.11.21 |