diff --git a/mvc_flask/__init__.py b/mvc_flask/__init__.py index 23abee8..be085ce 100644 --- a/mvc_flask/__init__.py +++ b/mvc_flask/__init__.py @@ -1,10 +1,11 @@ from importlib import import_module -from flask import Flask, render_template, request +from flask import Flask from flask.blueprints import Blueprint from mvc_flask import plugins from .router import Router +from . import cli class FlaskMVC: @@ -20,6 +21,7 @@ def init_app(self, app: Flask = None, path="app"): self.register_blueprint(app) plugins.register(app) + cli.init_app(app) def register_blueprint(self, app: Flask): # load routes defined from users diff --git a/mvc_flask/cli.py b/mvc_flask/cli.py new file mode 100644 index 0000000..105e9b0 --- /dev/null +++ b/mvc_flask/cli.py @@ -0,0 +1,50 @@ +import os +from black import format_str, FileMode + +import click +from flask.cli import with_appcontext + + +BASEDIR = os.path.dirname(os.path.dirname(__file__)) +MVC_DIR = os.path.join(BASEDIR, "mvc_flask") + + +@click.group() +def generate(): + """Use this command for generate controller, models, auth and etc.""" + pass + + +@generate.command() +@click.argument("name") +@with_appcontext +def controller(name): + """Generate controller, e.g: flask generate controller home""" + controller_template = os.path.join(MVC_DIR, "templates", "controller.md") + controller_filename = f"{name}_controller.py".lower() + file_content = None + + with open(controller_template, "r") as controller: + file_content = controller.read() + + file = os.path.join(os.getcwd(), "app", "controllers", controller_filename) + + if os.path.exists(file): + print( + "\033[31m conflict" + + f"\033[37m app/controllers/{controller_filename} already exists" + ) + quit() + + with open(file, "w+") as f: + string = file_content.format(name=f"{name}".title()) + content = format_str(string, mode=FileMode()) + f.write(content) + + print( + "\033[92m create" + f"\033[37m app/controllers/{controller_filename}" + ) + + +def init_app(app): + app.cli.add_command(generate) diff --git a/mvc_flask/templates/controller.md b/mvc_flask/templates/controller.md new file mode 100644 index 0000000..70e96e4 --- /dev/null +++ b/mvc_flask/templates/controller.md @@ -0,0 +1,3 @@ +class {name}Controller: + def index(): + ... \ No newline at end of file