23/05/17(플라스크+5/18이어서)

조영문·2023년 5월 17일
0

Raspberry

목록 보기
3/3

5/17

점프 투 플라스크 (공부할 때 참고하기!)

https://wikidocs.net/book/4542

플라스크 서버 세팅

  1. 파이썬 설치

cmd를 열어서 python -V 을 입력하면 파이썬 설치 유무 및 버전을 확인할 수 있다.

  1. 플라스크 개발 환경 준비하기

cd \
mkdir venvs // venvs라는 폴더를 생성한다.
cd ven*
python -m venv myproject // venvs 폴더 안에 myproject를 생성한다.

cd C:\venvs\myproject\Scripts
activate // python 실행 (콘솔)
deactivate // python 실행 종료 (콘솔)

// python에서 필요한 패키지를 설치할 때 pip install을 사용한다.
pip install flask // flask 패키지를 설치한다.
python -m pip install --upgrade pip // pip 업그레이드 시키는 명령어

새로운 cmd 창 연 뒤에!

cd \
mkdir projects
cd projects
C:\venvs\myproject\Scripts\activate
mkdir myproject
cd my*

네이트온에 bat 파일 다운로드 받기! (myproject.bat)

C:\venvs 안에 myproject.bat 파일을 넣는다.

PyCharm을 열어서 open file > projects\myproject을 연다.

setting > Project: myproject > Python Interpreter에서 설치 된 패키지를 확인 할 수 있다.
(pip, setuptools 깔린 상태)

우측 상단에 있는 Add Python Interpreter 클릭! > Exising 클릭 > 경로는 C:\venvs\myproject\Scripts\python.exe로 설정

설정 이후에는 패키지들이 자동적으로 둘어와있을 것입니다~.

main.py > pybo.py 로 rename 한 뒤,

from flask import Flask
app = Flask(name)

@app.route('/')
def hello_pybo():
return 'Hello, Pybo!'

를 작성한다.

이후에 set FLASK_APP=pybo 를 한 뒤, flask run을 하면 주소가 뜬다.
이 주소를 복사하여 브라우저를 열어서 붙여넣기 한다.

Hello, Pybo! 라고 뜬다.

set FLASK_APP=pybo
set FLASK_DEBUG=true

설정한 뒤에

flask run

git

https://github.com/youngmoon97/flask



pybo

static

bootstrap.min.css

style.css

templates

question/question_detail.html

<!--<link rel="stylesheet" href="{{ url_for('static', filename='bootstrap.min.css') }}">-->
{% extends 'base.html' %}
{% block content%}
<div class="container my-3">
    <!-- 질문 -->
    <h2 class="border-bottom py-2">{{ question.subject }}</h2>
    <div class="card my-3">
        <div class="card-body">
            <div class="card-text" style="white-space: pre-line;">{{ question.content }}</div>
            <div class="d-flex justify-content-end">
                <div class="badge bg-light text-dark p-2">
                    {{ question.create_date }}
                </div>
            </div>
        </div>
    </div>
    <!-- 답변 목록 -->
    <h5 class="border-bottom my-3 py-2">{{ question.answer_set|length }}개의 답변이 있습니다.</h5>
    {% for answer in question.answer_set %}
    <div class="card my-3">
        <div class="card-body">
            <div class="card-text" style="white-space: pre-line;">{{ answer.content }}</div>
            <div class="d-flex justify-content-end">
                <div class="badge bg-light text-dark p-2">
                    {{ answer.create_date }}
                </div>
            </div>
        </div>
    </div>
    {% endfor %}
    <!-- 답변 등록 -->
    <form action="{{ url_for('answer.create', question_id=question.id) }}" method="post" class="my-3">
        <div class="mb-3">
            <textarea name="content" id="content" class="form-control" rows="10"></textarea>
        </div>
        <input type="submit" value="답변등록" class="btn btn-primary">
    </form>
</div>
{% endblock %}

question/question_list.html

<!-- 질문 목록 -->
 {% extends 'base.html' %}
{% block content%}
<div class="container my-3">
    <table class="table">
        <thead>
        <tr class="table-dark">
            <th>번호</th>
            <th>제목</th>
            <th>작성일시</th>
        </tr>
        </thead>
        <tbody>
        {% if question_list %}
        {% for question in question_list %}
        <tr>
            <td>{{ loop.index }}</td>
            <td><a href="{{url_for('question.detail',question_id=question.id)}}">{{ question.subject }}</a></td>
            <td>{{question.create_date}}</td>
        </tr>
        {% endfor %}
        {% else %}
        <tr>
            <p>질문이 없습니다.</p>
        </tr>
        {% endif %}
        </tbody>
    </table>
</div>
{% endblock %}

base.html

<!doctype html>
<html lang="ko">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="{{ url_for('static', filename='bootstrap.min.css') }}">
    <!-- pybo CSS -->
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    <title>Hello, pybo!</title>
</head>
<body>
<!-- 기본 템플릿 안에 삽입될 내용 Start -->
{% block content %}
{% endblock %}
<!-- 기본 템플릿 안에 삽입될 내용 End -->
</body>
</html>

views

answer_views.py

from flask import Blueprint, url_for, request
from datetime import datetime
from werkzeug.utils import redirect

from pybo import db
from pybo.models import Question, Answer

bp = Blueprint('answer', __name__, url_prefix='/answer')


@bp.route('/create/<int:question_id>', methods=('POST',))
def create(question_id):
    question = Question.query.get_or_404(question_id)
    content = request.form['content']
    answer = Answer(content=content, create_date=datetime.now())
    question.answer_set.append(answer)
    db.session.commit()
    return redirect(url_for('question.detail', question_id=question_id))

main_views.py

from flask import Blueprint, url_for
from werkzeug.utils import redirect
from pybo.models import Question

bp = Blueprint('main', __name__, url_prefix='/')


@bp.route('/')
def index():
    return redirect(url_for('question._list'))


@bp.route('/hello')
def hello_pybo():
    return 'Hello, Pybo!'

question_views.py

from flask import Blueprint, render_template
from pybo.models import Question

bp = Blueprint('question', __name__, url_prefix='/question')


@bp.route('/list')
def _list():
    question_list = Question.query.order_by(Question.create_date.desc())
    return render_template('question/question_list.html', question_list=question_list)


@bp.route('/detail/<int:question_id>/')
def detail(question_id):
    question = Question.query.get(question_id)
    return render_template('question/question_detail.html', question=question)

init.py

from flask import Flask
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy

import config

db = SQLAlchemy()
migrate = Migrate()


def create_app():
    app = Flask(__name__)
    app.config.from_object(config)

    # ORM
    db.init_app(app)
    migrate.init_app(app, db)
    from . import models

    # 블루프린트
    from .views import main_views, question_views, answer_views
    app.register_blueprint(main_views.bp)
    app.register_blueprint(question_views.bp)
    app.register_blueprint(answer_views.bp)

    return app

models.py

from pybo import db


class Question(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    subject = db.Column(db.String(200), nullable=False)
    content = db.Column(db.Text(), nullable=False)
    create_date = db.Column(db.DateTime(), nullable=False)


class Answer(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    question_id = db.Column(db.Integer, db.ForeignKey('question.id', ondelete='CASCADE'))
    question = db.relationship('Question', backref=db.backref('answer_set'))
    content = db.Column(db.Text(), nullable=False)
    create_date = db.Column(db.DateTime(), nullable=False)

config.py

import os

BASE_DIR = os.path.dirname(__file__)

SQLALCHEMY_DATABASE_URI = 'sqlite:///{}'.format(os.path.join(BASE_DIR, 'pybo.db'))
SQLALCHEMY_TRACK_MODIFICATIONS = False

0개의 댓글