Ejemplo n.º 1
0
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)
Ejemplo n.º 2
0
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)
Ejemplo n.º 3
0
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")
Ejemplo n.º 4
0
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)
Ejemplo n.º 5
0
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)
Ejemplo n.º 6
0
 def test_without_format(s):
     word = "super_users"
     ok = {
         "model": "super_user",
         "table": "super_users",
         "class": "SuperUser"
     }
     for word in [
             "super_users", "super_user", "SuperUsers", "SuperUser",
             "Super_Users"
     ]:
         s.assertTrue(lib.names(word) == ok)
Ejemplo n.º 7
0
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)
Ejemplo n.º 8
0
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)
Ejemplo n.º 9
0
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))
Ejemplo n.º 10
0
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)
Ejemplo n.º 11
0
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)
Ejemplo n.º 12
0
 def test_with_one_format(s):
     word = "super_users"
     s.assertTrue(lib.names(word, ["model"]) == "super_user")
Ejemplo n.º 13
0
 def test_with_format(s):
     word = "super_users"
     s.assertTrue(
         lib.names(word, ["class", "model"]) == ["SuperUser", "super_user"])