Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create CLI commands for Flask MVC #32

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion mvc_flask/__init__.py
Original file line number Diff line number Diff line change
@@ -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:
Expand All @@ -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
Expand Down
50 changes: 50 additions & 0 deletions mvc_flask/cli.py
Original file line number Diff line number Diff line change
@@ -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)
3 changes: 3 additions & 0 deletions mvc_flask/templates/controller.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
class {name}Controller:
def index():
...