1. 程式人生 > 實用技巧 >Flask 專案目錄結構快速生成

Flask 專案目錄結構快速生成

import os
from threading import Thread


class FlaskProject:

    def __init__(self, project_name: str):
        self.project_name = project_name
        self.app_name = None
        self.__second_dirs = ["static", "templates", "views"]

    def create_app_dir(self):
        dir_path = self.project_name + "/" + self.project_name
        os.makedirs(dir_path)
        self.app_name = dir_path

    def create_second_dirs(self, dir_name):
        try:
            os.makedirs(self.app_name + "/" + dir_name)
        except FileExistsError as e:
            print(e)

    def create_init_py(self):
        with open(self.app_name + "/__init__.py", "w") as f:
            f.write("""from flask import Flask
from settings import DevelopConfig
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()
from demo.models import *
# 註冊藍圖
from demo.views.demo import demo


def create_app():
    app = Flask(__name__)
    app.config.from_object(DevelopConfig)
    app.register_blueprint(demo)
    db.init_app(app)
    return app""")

    def create_models_py(self):
        with open(self.app_name + "/models.py", "w") as f:
            f.write("""from demo import db


class User(db.Model):
    __tablename__ = "user"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(32), unique=True, nullable=False)
    password = db.Column(db.String(32), nullable=False)""")

    def create_manage_py(self):
        with open(self.project_name + "/manage.py", "w") as f:
            f.write("""from demo import create_app, db
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand

app = create_app()
manager = Manager(app)
migrate = Migrate(app, db)
manager.add_command("db", MigrateCommand)


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

    def create_settings_py(self):
        with open(self.project_name + "/settings.py", "w") as f:
            f.write("""class BaseConfig:
    DEBUG = False


class DevelopConfig(BaseConfig):
    DEBUG = True
    SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:[email protected]:3306/testsqlachemy?charset=utf8'
    SQLALCHEMY_POOL_SIZE = 5
    SQLALCHEMY_POOL_TIMEOUT = 30
    SQLALCHEMY_POOL_RECYCLE = -1
    SQLALCHEMY_TRACK_MODIFICATIONS = False
""")

    def create_require_text(self):
        with open(self.project_name + "/requirement.txt", "w") as f:
            f.write("""Flask_SQLAlchemy==2.4.4
Flask==1.1.2
SQLAlchemy==1.3.19
Flask_Script==2.0.6
alembic==1.4.2
Flask_Migrate==2.5.3""")

    def create_views_py(self):
        with open(self.app_name + "/views/demo.py", "w") as f:
            f.write("""from flask import Blueprint
from demo.models import *
from demo import db

demo = Blueprint("demo", __name__)""")

    def run(self):
        self.create_app_dir()
        for name in self.__second_dirs:
            t = Thread(target=self.create_second_dirs, args=(name,))
            t.start()
            t.join()
        tasks = [
            self.create_init_py,
            self.create_models_py,
            self.create_manage_py,
            self.create_settings_py,
            self.create_require_text,
            self.create_views_py
        ]
        for task in tasks:
            t = Thread(target=task)
            t.start()


if __name__ == '__main__':
    fp = FlaskProject("demo")
    fp.run()