def execute(argv, argv0, engine): if not argv or '--help' in argv: usage(argv0) os.environ["AIOWEB_ENV"] = "test" environment = os.getenv("AIOWEB_ENV", "development") os.environ.setdefault("AIOWEB_SETTINGS_MODULE", "settings") import lib, inflection from aioweb import settings controllers_dir = lib.dirs(settings, format=["tests_controllers"]) controller = inflection.underscore(argv[0]) controller_path = os.path.join(controllers_dir, controller + ".py") if not controllers_dir: print("No model found!") sys.exit(0) if '--list' in argv: [ print(m[:-3]) for m in os.listdir(controllers_dir) if m.endswith(".py") and not m.startswith("__") ] sys.exit(0) test_file = os.path.join(controllers_dir, controller + ".py") if not os.path.exists(test_file): print("No such file: " + test_file) sys.exit(1) os.system("python3 " + test_file)
def execute(argv, argv0, engine): if not argv or '--help' in argv: usage(argv0) os.environ["AIOWEB_ENV"] = "test" environment = os.getenv("AIOWEB_ENV", "development") os.environ.setdefault("AIOWEB_SETTINGS_MODULE", "settings") import lib from aioweb import settings tests_dir = lib.dirs(settings, format=["tests_models"], check=True) if not tests_dir: print("No model found!") sys.exit(0) if '--list' in argv: [ print(m[:-3]) for m in os.listdir(tests_dir) if m.endswith(".py") and not m.startswith("__") ] sys.exit(0) test_file = os.path.join(tests_dir, lib.names(argv[0] + ".py", format=["model"])) if not os.path.exists(test_file): print("No such file: " + test_file) sys.exit(1) os.system("python3 " + test_file)
def execute(argv, argv0, engine): import lib, importlib os.environ.setdefault("AIOWEB_SETTINGS_MODULE", "settings") from aioweb import settings sys.path.append(os.getcwd()) environment = os.getenv("AIOWEB_ENV", "development") if '-h' in argv or '--help' in argv: usage(argv0) oldcwd = os.getcwd() os.makedirs(os.path.join(settings.BASE_DIR, 'db'), exist_ok=True) os.chdir(os.path.join(settings.BASE_DIR, 'db')) print("[ app ]") migrations_dir = lib.dirs(settings, format=["migrations"], check=True) if migrations_dir: os.system( "echo y | orator migrate:rollback -c %(base)s/config/database.yml -p %(egg)s -d %(environment)s" % { 'environment': environment, 'base': settings.BASE_DIR, 'egg': migrations_dir, }) else: print("No migrations found") os.chdir(oldcwd)
def execute(argv, argv0, engine): import lib, inflection, re os.environ.setdefault("AIOWEB_SETTINGS_MODULE", "settings") from aioweb import settings sys.path.append(os.getcwd()) if len(argv) < 2: usage(argv0) controller_name = inflection.camelize(argv[0]) + "Controller" controller_file_name = inflection.underscore(argv[0]) + ".py" method_name = inflection.underscore(argv[1]) controllers_dir = lib.dirs(settings, format=["tests_controllers"]) dest_file = os.path.join(controllers_dir, controller_file_name) os.makedirs(os.path.dirname(dest_file), exist_ok=True) template = lib.get_template("tests/controller_method.py", settings) if not os.path.exists(dest_file): print("Sorry but {} does not exist!".format(dest_file)) return print("adding 'test_{}' to {}".format(method_name, dest_file)) with open(template, "r") as f: method_code = f.read().replace("METHOD", method_name).replace( "CLASS", controller_name).replace("CONTROLLER_NAME", controller_file_name[:-3]) lib.insert_in_python(dest_file, ["class test_{}".format(controller_name)], method_code.split("\n"), in_end=True, ignore_pass=True)
def import_migrations_from_app(app): migrations_dir = lib.dirs(settings, app=app, format=["migrations"], check=True) if not migrations_dir: return print("[ %s ]" % app) existant_migrations = [] for m in sorted(os.listdir(dest_dir)): if not m.startswith('_') and m.endswith('.py'): mp = os.path.join(dest_dir, m) with open(mp) as f: if "# {} module".format(app) in f.read(): existant_migrations.append(mp) if existant_migrations: rc = lib.ask("The migrations for {} alerady installed.\nDo You wanna remove its?".format(app)) if rc == 'n': return for m in existant_migrations: print("removing " + m) os.unlink(m) print("") migrations = [(os.path.join(migrations_dir, m), re.sub(r"^[\d_]+", "", m)[:-3]) for m in sorted(os.listdir(migrations_dir)) if not m.startswith('_') and m.endswith('.py')] for path, name in migrations: ts = datetime.utcnow().strftime("%Y_%m_%d_%H%M%S%f") dest_file = os.path.join(dest_dir, ts + "_" + name + ".py") print("creating " + dest_file) shutil.copy2(path, dest_file) lib.insert_in_python(dest_file, ["from"], ["# {} module. please dont remove this line".format(app)], in_end=True, ignore_pass=True)
def execute(argv, argv0, engine): if '--help' in argv or '-h' in argv: usage(argv0) os.environ["AIOWEB_ENV"] = "test" environment = os.getenv("AIOWEB_ENV", "development") os.environ.setdefault("AIOWEB_SETTINGS_MODULE", "settings") import lib, inflection from aioweb import settings tests_dir = lib.dirs(settings, format=["tests_controllers"], check=True) if not tests_dir: print("No controller found!") sys.exit(0) controllers = [m[:-3] for m in os.listdir(tests_dir) if m.endswith(".py") and not m.startswith("__")] if '--list' in argv: [print(m[:-3]) for m in os.listdir(tests_dir) if m.endswith(".py") and not m.startswith("__")] sys.exit(0) for ctrl in controllers: print(ctrl) test_file = os.path.join(tests_dir, ctrl + ".py") print("testing " + ctrl) rc = None if os.system("python3 " + test_file) != 0 and rc != 'a': rc = lib.ask("Do You wanna continue?", ['y', 'n', 'a']) if rc == 'n': sys.exit(1)
def execute(argv, argv0, engine): import lib, inflection os.environ.setdefault("AIOWEB_SETTINGS_MODULE", "settings") from aioweb import settings sys.path.append(os.getcwd()) if len(argv) < 2: usage(argv0) controller_name = inflection.camelize(argv[0]) + "Controller" controller_file_name = inflection.underscore(argv[0]) + ".py" methods = argv[1:] dest_file = os.path.join(lib.dirs(settings, format=["controllers"]), controller_file_name) os.makedirs(os.path.dirname(dest_file), exist_ok=True) template = lib.get_template("controllers/simple_controller.py", settings) if os.path.exists(dest_file): if lib.ask("{} already exists!\nDo you wanna replace it?".format(dest_file)) == 'n': print("Controller generation was aborted!") return print("creating {}".format(dest_file)) with open(template, "r") as f: controller_code = f.read().replace("CLASS", controller_name) with open(dest_file, "w") as df: df.write(controller_code) for method in methods: engine["commands"]["generate"]["controller_method"]([argv[0], method], argv0, engine) engine["commands"]["generate"]["test"]["controller"](argv, argv0, engine)
def execute(argv, argv0, engine): import lib, inflection os.environ.setdefault("AIOWEB_SETTINGS_MODULE", "settings") from aioweb import settings if len(argv) == 0 or '-h' in argv or '--help' in argv: usage(argv0) additional_fields = lib.get_fields_from_argv(argv[1:], usage, argv0) tests_dir = lib.dirs(settings, format=["tests_controllers"]) table, model_name, model_class, controller_class = lib.names( argv[0], ["table", "model", "class", 'crud_class']) controller_file_name = "{}.py".format(table) dest_file = os.path.join(tests_dir, controller_file_name) test_field = "strawberry_field" if len(additional_fields) > 0: test_field = additional_fields[0][1] replacements = { 'MODEL': model_name, 'MODEL_CLASS': model_class, 'CONTROLLER_CLASS': controller_class, 'TABLE': table, 'TEST_FIELD': test_field, } crud_test_code = lib.read_template("tests/crud.py", settings=settings, replacements=replacements) print("generating {}...".format(dest_file)) os.makedirs(tests_dir, exist_ok=True) with open(dest_file, "w") as f: f.write(crud_test_code)
def execute(argv, argv0, engine): import lib, re os.environ.setdefault("AIOWEB_SETTINGS_MODULE", "settings") from aioweb import settings sys.path.append(os.getcwd()) migrations_dir, models_dir = lib.dirs(settings, format=["migrations", "models"]) table, model_name = lib.names(argv[0], ["table", "model"]) migration_name = "create_{}_table".format(table) model_file = os.path.join(models_dir, "{}.py".format(model_name)) if os.path.exists(model_file): print("delete " + model_file) os.unlink(model_file) try: rc = [ os.path.join(migrations_dir, f) for f in os.listdir(migrations_dir) if os.path.isfile(os.path.join(migrations_dir, f)) ] except FileNotFoundError: rc = [] for file_path in rc: sr = None with open(file_path, "r") as f: sr = re.search(r"schema\.\w+\(\s*['\"]{}['\"]".format(table), f.read()) if sr: print("delete " + file_path) os.unlink(file_path) print("destroying factory") engine["commands"]["destroy"]["test"]["factory"](argv, argv0, engine) engine["commands"]["destroy"]["test"]["model"](argv, argv0, engine)
def execute(argv, argv0, engine): import lib os.environ.setdefault("AIOWEB_SETTINGS_MODULE", "settings") from aioweb import settings sys.path.append(os.getcwd()) if len(argv) < 1 or '-h' in argv or '--help' in argv: usage(argv0) seeds_dir = lib.dirs(settings, format=["seeds"]) seed_name = argv[0] try: seeds = [os.path.join(seeds_dir, f) for f in os.listdir(seeds_dir) if seed_name in f] except FileNotFoundError: seeds = [] rc = None for m in seeds: if rc not in ['a', 'all']: rc = lib.ask( "\n{} already exists.\nDo you wanna remove it before create migration?".format(m), ['y', 'n', 'e', 'exit', 'all', 'a', 'skip all']) if rc in ['skip all']: break if rc in ['e', 'exit']: print("migration aborted") sys.exit(1) if rc in ['a', 'y', 'all']: print("delete " + m) os.unlink(m) os.system("orator make:seed {} -p {}".format(seed_name, seeds_dir))
def execute(argv, argv0, engine): if not argv: usage(argv0) import lib os.environ.setdefault("AIOWEB_SETTINGS_MODULE", "settings") from aioweb import settings table, model_name, model_class = lib.names(argv[0], ["table", "model", "class"]) dest_path = os.path.join(lib.dirs(settings, format=["tests"]), "models/" + model_name + ".py") os.makedirs(os.path.dirname(dest_path), exist_ok=True) if os.path.exists(dest_path): if lib.ask("{} already exists!\nDo You wanna rewrite it?".format( dest_path)) == 'n': return template = lib.get_template("tests/model.py", settings) with open(template, "r") as f: print("generating " + dest_path) content = f.read().replace("MODEL", model_name).replace( "CLASS", model_class).replace("TABLE", table) with open(dest_path, "w") as df: df.write(content)
def execute(argv, argv0, engine): import lib, importlib, re import code os.environ.setdefault("AIOWEB_SETTINGS_MODULE", "settings") from aioweb import settings sys.path.append(settings.BASE_DIR) # Initialize Orator ORM lib.init_orator(settings) local_vars = {} print("") for app in settings.APPS + [None]: models_dir = lib.dirs(settings, app, ["models"], check=True) if not models_dir: continue models = [model_file.replace(".py", '') for model_file in os.listdir(models_dir) \ if re.match(r"^[a-z0-9_]+\.py$", model_file) and model_file != "__init__.py"] # Import models for model in models: class_name = lib.names(model, ["class"]) model_import = lib.get_import("models", model, app) try: m = importlib.import_module(model_import) exec("{0} = m.{0}".format(class_name)) local_vars[class_name] = locals()[class_name] print("from " + model_import + " import " + class_name) except: print("WARNING: cannot import {}".format(model_import)) code.interact(local=local_vars, banner="You are welcome in the aioweb console!\n\n")
def execute(argv, argv0, engine): import lib, importlib, re, shutil from datetime import datetime os.environ.setdefault("AIOWEB_SETTINGS_MODULE", "settings") from aioweb import settings sys.path.append(os.getcwd()) if '-h' in argv or '--help' in argv or not argv: usage(argv0) if argv[0] not in settings.APPS + ["all"]: print("ERROR: can't locate the {} app".format(argv[0])) print("available apps: {}".format(", ".join(settings.APPS))) usage(argv0) dest_dir = lib.dirs(settings, format=["migrations"]) os.makedirs(dest_dir, exist_ok=True) def import_migrations_from_app(app): migrations_dir = lib.dirs(settings, app=app, format=["migrations"], check=True) if not migrations_dir: return print("[ %s ]" % app) existant_migrations = [] for m in sorted(os.listdir(dest_dir)): if not m.startswith('_') and m.endswith('.py'): mp = os.path.join(dest_dir, m) with open(mp) as f: if "# {} module".format(app) in f.read(): existant_migrations.append(mp) if existant_migrations: rc = lib.ask("The migrations for {} alerady installed.\nDo You wanna remove its?".format(app)) if rc == 'n': return for m in existant_migrations: print("removing " + m) os.unlink(m) print("") migrations = [(os.path.join(migrations_dir, m), re.sub(r"^[\d_]+", "", m)[:-3]) for m in sorted(os.listdir(migrations_dir)) if not m.startswith('_') and m.endswith('.py')] for path, name in migrations: ts = datetime.utcnow().strftime("%Y_%m_%d_%H%M%S%f") dest_file = os.path.join(dest_dir, ts + "_" + name + ".py") print("creating " + dest_file) shutil.copy2(path, dest_file) lib.insert_in_python(dest_file, ["from"], ["# {} module. please dont remove this line".format(app)], in_end=True, ignore_pass=True) if argv[0] == 'all': for app in settings.APPS: import_migrations_from_app(app) else: import_migrations_from_app(argv[0])
def execute(argv, argv0, engine): import lib os.environ.setdefault("AIOWEB_SETTINGS_MODULE", "settings") from aioweb import settings sys.path.append(os.getcwd()) if len(argv) <= 1 or '-h' in argv or '--help' in argv: usage(argv0) additional_fields = lib.get_fields_from_argv(argv[2:], usage, argv0) migrations_dir = lib.dirs(settings, format=["migrations"]) table_name = argv[0] migration_name = argv[1] try: migrations = [ os.path.join(migrations_dir, f) for f in os.listdir(migrations_dir) if migration_name in f ] except FileNotFoundError: migrations = [] rc = None for m in migrations: if rc not in ['a', 'all']: rc = lib.ask( "\n{} already exists.\nDo you wanna remove it before create migration?" .format(m), ['y', 'n', 'e', 'exit', 'all', 'a', 'skip all']) if rc in ['skip all']: break if rc in ['e', 'exit']: print("migration aborted") sys.exit(1) if rc in ['a', 'y', 'all']: print("delete " + m) os.unlink(m) os.system("orator make:migration {} -p {} -t {}".format( migration_name, migrations_dir, table_name)) file_name = os.path.join(migrations_dir, [ f for f in sorted(os.listdir(migrations_dir)) if migration_name in f ][-1]) print("patching " + file_name) lib.insert_in_python( file_name, ["def up", "as table:"], ["table.{}('{}')".format(tp, name) for tp, name in additional_fields]) lib.insert_in_python(file_name, ["def down", "as table:"], [ "table.drop_column('{}')".format(name) for tp, name in additional_fields ])
def execute(argv, argv0, engine): import lib, re os.environ.setdefault("AIOWEB_SETTINGS_MODULE", "settings") from aioweb import settings if not argv: usage(argv0) model_name = lib.names(argv[0], ["model"]) dest_path = os.path.join(lib.dirs(settings, format=["tests"]), "models/" + model_name + ".py") if os.path.exists(dest_path): print("removing " + dest_path) os.unlink(dest_path)
def execute(argv, argv0, engine): import lib, re os.environ.setdefault("AIOWEB_SETTINGS_MODULE", "settings") from aioweb import settings if not argv: usage(argv0) table = lib.names(argv[0], ["table"]) factory_path = os.path.join(lib.dirs(settings, format=["factories"]), '{}_factory.py'.format(table)) if os.path.exists(factory_path): print("removing " + factory_path) os.unlink(factory_path)
def execute(argv, argv0, engine): import lib, importlib os.environ.setdefault("AIOWEB_SETTINGS_MODULE", "settings") from aioweb import settings sys.path.append(os.getcwd()) environment = os.getenv("AIOWEB_ENV", "development") if '-h' in argv or '--help' in argv: usage(argv0) oldcwd = os.getcwd() os.makedirs(os.path.join(settings.BASE_DIR, 'db'), exist_ok=True) os.chdir(os.path.join(settings.BASE_DIR, 'db')) for app in settings.APPS: print("[ %s ]" % app) seeds_dir = lib.dirs(settings, format=["seeds"], app=app) print("%(seeds_dir)s" % {'seeds_dir': seeds_dir}) os.system("orator db:seed -c %(base)s/config/database.yml -p %(seeds_dir)s -d %(environment)s -f" % { 'environment': environment, 'base': settings.BASE_DIR, 'seeds_dir': seeds_dir, }) print("[ app ]") seeds_dir = lib.dirs(settings, format=["seeds"]) print("%(seeds_dir)s" % {'seeds_dir': seeds_dir}) os.system("orator db:seed -c %(base)s/config/database.yml -p %(seeds_dir)s -d %(environment)s -f" % { 'environment': environment, 'base': settings.BASE_DIR, 'seeds_dir': seeds_dir, }) os.chdir(oldcwd)
def execute(argv, argv0, engine): import lib, shutil, inflection os.environ.setdefault("AIOWEB_SETTINGS_MODULE", "settings") from aioweb import settings sys.path.append(os.getcwd()) if len(argv) == 0 or '-h' in argv or '--help' in argv: usage(argv0) controllers_dir = lib.dirs(settings, format=["tests_controllers"]) controller = inflection.underscore(argv[0]) controller_path = os.path.join(controllers_dir, controller + ".py") if os.path.exists(controller_path): print("removing " + controller_path) os.unlink(controller_path)
def execute(argv, argv0, engine): import lib, importlib os.environ.setdefault("AIOWEB_SETTINGS_MODULE", "settings") from aioweb import settings sys.path.append(os.getcwd()) environment = os.getenv("AIOWEB_ENV", "development") if '-h' in argv or '--help' in argv: usage(argv0) flags = [] if '--no-input' in argv or '-n' in argv: flags.append('-n -f') oldcwd = os.getcwd() os.makedirs(os.path.join(settings.BASE_DIR, 'db'), exist_ok=True) os.chdir(os.path.join(settings.BASE_DIR, 'db')) # for app in settings.APPS: # print("[ %s ]" % app) # migrations_dir = lib.dirs(settings, format=["migrations"], app=app) # print("%(migrations_dir)s" % {'migrations_dir': migrations_dir}) # os.system("echo y | orator migrate -c %(base)s/config/database.yml -p %(migrations_dir)s -d %(environment)s" % { # 'environment': environment, # 'base': settings.BASE_DIR, # 'migrations_dir': migrations_dir, # }) migrations_dir = lib.dirs(settings, format=["migrations"]) os.system( "orator migrate -c %(base)s/config/database.yml " "--migration-config %(base)s/config/migrations.yml " "-p %(migrations_dir)s " "-d %(environment)s %(flags)s" % { 'environment': environment, 'base': settings.BASE_DIR, 'migrations_dir': migrations_dir, 'flags': ' '.join(flags) }) os.chdir(oldcwd)
def execute(argv, argv0, engine): import lib os.environ.setdefault("AIOWEB_SETTINGS_MODULE", "settings") from aioweb import settings migrations_dir = lib.dirs(settings, format=["migrations"]) sys.path.append(os.getcwd()) if len(argv) == 0 or '-h' in argv or '--help' in argv: usage(argv0) migration_name = argv[0 if len(argv) == 1 else 1] try: migrations = [ os.path.join(migrations_dir, f) for f in os.listdir(migrations_dir) if migration_name in f ] except FileNotFoundError: migrations = [] for m in migrations: print("delete " + m) os.unlink(m)
def execute(argv, argv0, engine): import lib, importlib os.environ.setdefault("AIOWEB_SETTINGS_MODULE", "settings") from aioweb import settings sys.path.append(os.getcwd()) environment = os.getenv("AIOWEB_ENV", "development") if '-h' in argv or '--help' in argv: usage(argv0) oldcwd = os.getcwd() os.makedirs(os.path.join(settings.BASE_DIR, 'db'), exist_ok=True) os.chdir(os.path.join(settings.BASE_DIR, 'db')) migrations_dir = lib.dirs(settings, format=["migrations"], check=True) engine["commands"]["db"]["reset"](argv, argv0, engine) engine["commands"]["db"]["migrate"](argv, argv0, engine) # os.system("orator migrate:refresh -c %(base)s/config/database.yml -p %(egg)s -d %(environment)s -n" % { # 'environment': environment, # 'base': settings.BASE_DIR, # 'egg': migrations_dir, # }) os.chdir(oldcwd)
def execute(argv, argv0, engine): if not argv: usage(argv0) import lib os.environ.setdefault("AIOWEB_SETTINGS_MODULE", "settings") from aioweb import settings additional_fields = lib.get_fields_from_argv(argv[1:], usage, argv0) if not additional_fields: additional_fields = [("string", "somefield")] table, model_name, model_class = lib.names(argv[0], ["table", "model", "class"]) factories_dir = lib.dirs(settings, format=["factories"]) os.makedirs(factories_dir, exist_ok=True) dest_path = os.path.join(factories_dir, '{}_factory.py'.format(table)) if os.path.exists(dest_path): if lib.ask(dest_path + " exists\nDo You wanna rewrite it?") == 'n': print("factory generation cancelled") return template = lib.get_template("tests/factory.py", settings) with open(template, "r") as f: print("generating " + dest_path) content = f.read().replace("MODEL", model_name).replace( "CLASS", model_class).replace("TABLE", table) with open(dest_path, "w") as df: df.write(content) lib.insert_in_python( dest_path, ["import"], ['from app.models.{} import {}'.format(model_name, model_class)]) lib.insert_in_python( dest_path, ["return"], map(lambda prm: ' "{}": None, '.format(prm[1]), additional_fields))
def execute(argv, argv0, engine): import lib, inflection, re os.environ.setdefault("AIOWEB_SETTINGS_MODULE", "settings") from aioweb import settings sys.path.append(os.getcwd()) if len(argv) == 0 or '-h' in argv or '--help' in argv or argv[0].startswith('-'): usage(argv0) additional_fields = lib.get_fields_from_argv(argv[1:], usage, argv0) migrations_dir, models_dir = lib.dirs(settings, format=["migrations", "models"]) table, model_name, model_class = lib.names(argv[0], ["table", "model", "class"]) migration_name = "create_{}_table".format(table) model_file = os.path.join(models_dir, "{}.py".format(model_name)) rewrite = True if os.path.exists(model_file): if lib.ask("{} already exists. Do you wanna rewrite it?".format(model_file)) == 'n': rewrite = False if rewrite: print("delete " + model_file) os.unlink(model_file) if rewrite: os.system("orator make:model {} -p app/models".format(inflection.singularize(table).capitalize())) rewrite = True try: rc = [f for f in os.listdir(migrations_dir) if migration_name in f] except FileNotFoundError: rc = [] if len(rc) > 0: if lib.ask( "{} already exists.\nDo you wanna rewrite it?".format("db/migrations/" + rc[0])) == 'n': rewrite = False if rewrite: for f in rc: print("delete " + "db/migrations/" + f) os.unlink(os.path.join(migrations_dir, f)) if rewrite: os.system("orator make:migration {} -p db/migrations/ -C -t {}".format(migration_name, table)) file_name = os.path.join(migrations_dir, [f for f in sorted(os.listdir(migrations_dir)) if migration_name in f][-1]) print("patching " + file_name) lib.insert_in_python(file_name, ["def up", "as table:"], ["table.{}('{}').nullable()".format(tp, name) for tp, name in additional_fields], in_end=True) print("patching " + model_file) with open(model_file, "r") as fr: content = fr.read() wrong_class_name = re.search(r"class ([_a-zA-Z0-9]+)", content).group(1) right_class_name = inflection.camelize(wrong_class_name.lower()) with open(model_file, "w") as f: f.write(re.sub(wrong_class_name, right_class_name, content)) fillable = "__fillable__ = [{}]".format(", ".join( ['"{}"'.format(name) for tp, name in additional_fields] )) lib.insert_in_python(model_file, ["class"], [fillable] + ["# {}{} - {}".format(name, (25 - len(name)) * ' ', tp) for tp, name in additional_fields], ignore_pass=True) print("generating factory") engine["commands"]["generate"]["test"]["factory"](argv, argv0, engine) engine["commands"]["generate"]["test"]["model"](argv[:1], argv0, engine)
def execute(argv, argv0, engine): import lib, inflection, re from aioweb import settings if len(argv) == 0 or '-h' in argv or '--help' in argv: usage(argv0) additional_fields = lib.get_fields_from_argv(argv[1:], usage, argv0) controllers_dir, models_dir, views_dir, configs_dir = lib.dirs(settings, format=["controllers", "models", "views", "config"]) table, model_name, model_class, controller_class = lib.names(argv[0], ["table", "model", "class", 'crud_class']) controller_file = os.path.join(controllers_dir, "{}.py".format(table)) views_dir= os.path.join(views_dir, table) routes_file = os.path.join(configs_dir, "routes.py") rewrite=False replacements= { 'MODEL': model_name, 'MODEL_CLASS': model_class, 'CONTROLLER_CLASS': controller_class, 'TABLE': table, 'MODEL_FIELD_NAMES': ', '.join(list(map(lambda type_name: '"' + type_name[1] + '"', additional_fields))), } controller_code = lib.read_template("crud/controller.py", settings=settings, replacements=replacements) os.makedirs(controllers_dir, exist_ok=True) if os.path.exists(controller_file): if lib.ask(controller_file + " already exists.\nDo you wanna rewrite it?") == 'n': sys.exit(1) print("creating {}...".format(controller_file)) with open(controller_file, "w") as f: f.write(controller_code) with open(routes_file, "r") as f: if not re.search(r"['\"]{}['\"]".format(table), f.read()): print("patching {}".format(routes_file)) lib.insert_in_python(routes_file, ["setup(router)"], ["router.resource('{}', '{}')".format(table, table)], in_end=True) print("") if os.path.exists(views_dir): if lib.ask(views_dir + "/ already exists.\nDo you wanna wipe out it?") == 'n': sys.exit(1) form_fields = "" for tp, name in additional_fields: form_fields+='<div class="field">\n' form_fields+=' <label>{}\n'.format(name) form_fields+=' <input' if tp in ['decimal', 'double', 'integer', 'big_integer', 'float']: form_fields += ' type="number" ' else: form_fields += ' type="text" ' form_fields+='name="{}[{}]" '.format(model_name, name) form_fields+= '{% if model.' + name + ' != None %} ' + 'value="{{ model.' + name + ' }}" ' + '{% endif %}' form_fields+='>' + "</input>" form_fields+="\n" form_fields+=' </label>\n</div>' replacements={ 'MODEL': model_name, 'TABLE': table, 'FORM_FIELDS': form_fields, } os.makedirs(views_dir, exist_ok=True) for view_name in ["index.html", "get.html", "form.html", "edit_page.html", "add.html", "add_page.html", "edit.html", "delete.html"]: view_file = os.path.join(views_dir, view_name) print("creating {}...".format(view_file)) view_code = lib.read_template("crud/{}".format(view_name), settings=settings, replacements=replacements) with open(view_file, "w") as f: f.write(view_code) engine["commands"]["generate"]["test"]["crud"](argv, argv0, engine)