Flask-기본 응용 구축 모델
윈도 우즈 든 리 눅 스 든 PyCharm 을 IDE 로 사용 할 수 있어 기능 이 완비 되 고 사용 이 편리 하 다.
2.VirtualEvn 만 들 기
PyCharm 을 사용 하면 명령 행 에 ve 를 만 들 지 않 고 새 프로젝트 를 만 들 고 create virtualevn 을 선택 하여 이름 을 짓 고 저장 경 로 를 선택 하면 됩 니 다.
3.패키지 의존 패키지 설치
PyCharm 에 서 는 메뉴[File]->[Settings]->[Project:youprocject name]->[Project Interpreter]를 통 해 이 환경 에 설 치 된 가방 을 볼 수 있 으 며,"+"아이콘 을 누 르 면 새 가방 을 추가 할 수도 있 고,여기 서 가방 을 삭제 할 수도 있 습 니 다.일반 Flask 프로젝트 의 수요 에 따라 우리 가 설치 해 야 할 가방 은 다음 과 같 습 니 다.
이 가방 들 을 설치 할 때 의존 가방 을 추가 로 설치 할 수 있 습 니 다.
4.프로젝트 디 렉 터 리 구조
전형 적 인 프로젝트 디 렉 터 리 구 조 는 다음 과 같다.
+program    //    
    +app                  //      
        +view1            //    1
            -__init__.py  //    ,     ,         
            -view.py      //    1       
        +view2            //    2
        +models           //    
            -model1.py    //          
        +static           //    (css,js,images )
        +templates        //    ,      ,                
        -__init__.py      //  SQLAlchemy   ,   create_app      Flask        
    +log                  //     
    +venv                 //    
    +migrations           //    ,     ,    
    -config.py            //      (   ,   )
    -manage.py            //      
    -run.py               //  app5. config.py
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
    DEBUG = False
    TESTING = False
    SECRET_KEY = os.environ.get('SECRET_KEY') or \
                 b'\x90\x87d\xcfk\xbd\x81\xa2\\G\xb2\x9a\x8d\xe5\xb5c\xa3\xbd\x85\x8c\x8c\x86\xbc`\x94ZM\xf5\xdaN\x92'
    SQLALCHEMY_COMMIT_ON_TEARDOWN = True
    @staticmethod
    def init_app(app):
        pass
class DevelopmentConfig(Config):
    DEBUG = True
    SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
        'sqlite:////database/flaskdb.db'
    SQLALCHEMY_TRACK_MODIFICATIONS = True
class TestingConfig(Config):
    TESTING = True
    SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
        'sqlite:////database/flaskdb.db'
    SQLALCHEMY_TRACK_MODIFICATIONS = True
class ProductionConfig(Config):
    SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
        'mysql://user:password&lp@localhost:3306/flaskdb'
    SQLALCHEMY_TRACK_MODIFICATIONS = True
config = {
    'development':DevelopmentConfig,
    'testing':TestingConfig,
    'production':ProductionConfig,
    'default':DevelopmentConfig,
}6. app/__init__.py
from flask import Flask, render_template, logging
from flask_sqlalchemy import SQLAlchemy
from logging.handlers import TimedRotatingFileHandler
from config import config
db = SQLAlchemy()
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])    
    #      
    mylog = TimedRotatingFileHandler('log/mylog.log', 'D')
    mylog.setLevel(logging.DEBUG)
    mylog.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(message)s'))
    app.logger.addHandler(mylog)
    #   DB
    db.init_app(app)
    #    
    from app.view1 import view1 as view1_blueprint
    app.register_blueprint(view1_blueprint, url_prefix='/view1')
    #    ,       
    
    return app7. run.py
import os
from app import create_app
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
if __name__ == '__main__':
    app.run()8. manage.py
import os
from app import create_app, db
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
'''
manager    :
    :python3 manager.py db [command]
 PyCharm   manager.py     db [command]
command  :
init-        (    migrations     ),       
migrate-      ,    model          ,     
upgrade-      ,             ,        
downgrade-      ,            
'''
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command('db', MigrateCommand)
manager.run()9. model1.py
from app import db
class Book(db.Model):
    __tablename__ = 'book'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), unique=True)
    pub_date = db.Column(db.DateTime)
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return "" % self.name 10. app/view1/__init__.py
from flask import Blueprint
#    
view1 = Blueprint('view1', __name__)
from app.view1 import view
#      
@book.app_template_filter('reverse')
def reverse_filter(s):
    return s[::-1]
#        ,       ,            
@book.context_processor
def utility_processor():
    rt = dict()
    def format_date(date):
        return date.strftime('%Y{y}%m{m}%d{d}').format(y=' ', m=' ', d=' ')
    rt['formatdate'] = format_date
    def format_date2(date):
        return date.strftime('%Y-%m-%d')
    rt['formatdate2'] = format_date2
    rt['xname'] = 'other strings'
    return rt11. app/view1/view.py
from flask import render_template, flash, current_app
from app.models.model1 import Book
from . import view1
@view1.route('/', methods=['GET'])
def index():
    books = Book.query.all()
    return render_template('book/bookindex.html', books=books)
@view1.route('/index2', method=['GET', 'POST'])
def index2():
    books = Book.query.all()
    return  render_template('book/bookindex2.html', books=books)12. app/templates/book/bookindex.html,layout.html
layout.html
    
         
    
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
    {% for category, message in messages %}
    - {{ message }}{% endfor %}
{% endif %}
{% endwith %}
{% block body %}{% endblock %}{% extends "book/layout.html" %}
{% block body %}
첫 페이지 
{%for book in books%}
{{ book.name | reverse }}==={{ formatdate(book.pub_date) }} 
{%endfor%}
{% endblock %}이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Python의 None과 NULL의 차이점 상세 정보그래서 대상 = 속성 + 방법 (사실 방법도 하나의 속성, 데이터 속성과 구별되는 호출 가능한 속성 같은 속성과 방법을 가진 대상을 클래스, 즉 Classl로 분류할 수 있다.클래스는 하나의 청사진과 같아서 하나의 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.