1. 程式人生 > >python flask框架專案拆分

python flask框架專案拆分

一 \結構

二\manage.py

from flask_migrate import MigrateCommand
from flask_script import Manager

from app import create_app

app = create_app()
manager = Manager(app)
manager.add_command('db',MigrateCommand)


if __name__ == '__main__':
    manager.run()
 

三\init.py

from flask import Flask

from app.ext import init_ext
from app.settings import init_app
from app.views import init_blue


def create_app(env_name='default'):
    app = Flask(__name__)

    #配置
    init_app(app, env_name)

    #擴充套件
    init_ext(app)

    #藍圖
    init_blue(app)
    return app

四 路由/檢視\views.py

from flask import Blueprint

from app.models import User

blue = Blueprint('blue',__name__)
def init_blue(app):
    app.register_blueprint(blueprint=blue)

@blue.route('/')
def index():
    return 'Hello World!'

五 配置\ext.py

from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()
migrate = Migrate()

def init_ext(app):
    db.init_app(app=app)
    migrate.init_app(app=app,db=db)

六\models.py

from app.ext import db


class User(db.Model):
    id = db.Column(db.Integer,primary_key=True,
                   autoincrement=True)
    name = db.Column(db.String(10

七\settings.py

# URI拼接
def get_db_uri(database):
    db = database.get('db') or 'mysql'
    driver = database.get('driver') or 'pymysql'
    username = database.get('username') or 'root'
    password = database.get('password') or 'root'
    host = database.get('host') or '127.0.0.1'
    port = database.get('port') or '3306'
    dbname = database.get('dbname') or 'flask1'

    return '{}+{}://{}:{}@{}:{}/{}'.format(db,driver,username,password,host,port,dbname)
class BaseConfig(object):
    DEBUG = False
    TESTING = False
    SECRET_KEY = '$%^&*()345671231adFGHJBHJK,./'
    SQLALCHEMY_TRACK_MODIFICATIONS = False

class DevelopConfig(BaseConfig):
    DEBUG = True
    DATABASE = {
        'dbname': 'flask1'
    }
    SQLALCHEMY_DATABASE_URI= get_db_uri(DATABASE)


config = {
    'develop':DevelopConfig,
    'default':DevelopConfig,
    }

def init_app(app,env_name):
    app.config.from_object(config.get(env_name))

八\現在可以啟動伺服器運行了

python manage.py runserver -r -d

初始化資料庫

python manage.py db init
資料遷移

 python manage.py db migrate

python manage.py db upgrade