flaskforge-cli 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- flaskforge_cli-0.1.0/LICENSE +21 -0
- flaskforge_cli-0.1.0/PKG-INFO +77 -0
- flaskforge_cli-0.1.0/README.md +62 -0
- flaskforge_cli-0.1.0/pyproject.toml +31 -0
- flaskforge_cli-0.1.0/setup.cfg +4 -0
- flaskforge_cli-0.1.0/src/flaskforge/__init__.py +3 -0
- flaskforge_cli-0.1.0/src/flaskforge/__main__.py +4 -0
- flaskforge_cli-0.1.0/src/flaskforge/cli.py +23 -0
- flaskforge_cli-0.1.0/src/flaskforge/commands.py +70 -0
- flaskforge_cli-0.1.0/src/flaskforge/generators.py +235 -0
- flaskforge_cli-0.1.0/src/flaskforge/management.py +110 -0
- flaskforge_cli-0.1.0/src/flaskforge/registry.py +311 -0
- flaskforge_cli-0.1.0/src/flaskforge/scaffold.py +156 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/app/__init__.py.tpl +1 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/app/forms.py.tpl +7 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/app/index.html.tpl +9 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/app/models.py.tpl +17 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/app/schemas.py.tpl +9 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/app/test_app.py.tpl +20 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/app/views.py.tpl +61 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/ext/login/__init__.py.tpl +1 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/ext/login/_csrf.html.tpl +2 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/ext/login/commands.py.tpl +24 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/ext/login/login.html.tpl +15 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/ext/login/models.py.tpl +28 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/ext/login/profile.html.tpl +13 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/ext/login/register.html.tpl +15 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/ext/login/test_accounts.py.tpl +31 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/ext/login/views.py.tpl +70 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/ext/sqlalchemy/mixins.py.tpl +15 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/project/Dockerfile.tpl +14 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/project/README.md.tpl +40 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/project/apps/__init__.py.tpl +1 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/project/apps/main/__init__.py.tpl +1 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/project/apps/main/templates/main/index.html.tpl +15 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/project/apps/main/views.py.tpl +13 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/project/config/__init__.py.tpl +3 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/project/config/settings.py.tpl +60 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/project/core/__init__.py.tpl +53 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/project/core/errors.py.tpl +15 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/project/core/extensions.py.tpl +17 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/project/dot_env.example.tpl +2 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/project/dot_env.tpl +2 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/project/dot_gitignore.tpl +16 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/project/manage.py.tpl +18 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/project/pytest.ini.tpl +2 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/project/requirements-dev.txt.tpl +3 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/project/requirements.txt.tpl +3 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/project/static/css/style.css.tpl +23 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/project/templates/base.html.tpl +35 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/project/templates/errors/error.html.tpl +9 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/project/tests/__init__.py.tpl +1 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/project/tests/conftest.py.tpl +21 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/project/tests/test_main.py.tpl +13 -0
- flaskforge_cli-0.1.0/src/flaskforge/templates/project/wsgi.py.tpl +4 -0
- flaskforge_cli-0.1.0/src/flaskforge_cli.egg-info/PKG-INFO +77 -0
- flaskforge_cli-0.1.0/src/flaskforge_cli.egg-info/SOURCES.txt +60 -0
- flaskforge_cli-0.1.0/src/flaskforge_cli.egg-info/dependency_links.txt +1 -0
- flaskforge_cli-0.1.0/src/flaskforge_cli.egg-info/entry_points.txt +2 -0
- flaskforge_cli-0.1.0/src/flaskforge_cli.egg-info/requires.txt +7 -0
- flaskforge_cli-0.1.0/src/flaskforge_cli.egg-info/top_level.txt +1 -0
- flaskforge_cli-0.1.0/tests/test_flaskforge.py +128 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Diyorbek Qodirboyev
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: flaskforge-cli
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Django-like CLI that scaffolds and extends large Flask projects
|
|
5
|
+
Requires-Python: >=3.9
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Requires-Dist: click>=8.1
|
|
9
|
+
Requires-Dist: Jinja2>=3.1
|
|
10
|
+
Requires-Dist: Flask>=3.0
|
|
11
|
+
Requires-Dist: python-dotenv>=1.0
|
|
12
|
+
Provides-Extra: dev
|
|
13
|
+
Requires-Dist: pytest; extra == "dev"
|
|
14
|
+
Dynamic: license-file
|
|
15
|
+
|
|
16
|
+
# flaskforge
|
|
17
|
+
|
|
18
|
+
Flask uchun Django'ga o'xshash CLI: katta loyiha strukturasini avtomatik yaratadi va
|
|
19
|
+
Flask extensionlarini bitta buyruq bilan ulaydi.
|
|
20
|
+
|
|
21
|
+
## O'rnatish
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
pip install -e .
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Ishlatish
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
flaskforge startproject shop --preset web # minimal | web | api | full
|
|
31
|
+
cd shop
|
|
32
|
+
python -m venv .venv && source .venv/bin/activate
|
|
33
|
+
pip install -r requirements-dev.txt && pip install -e /path/to/flaskforge
|
|
34
|
+
|
|
35
|
+
python manage.py startapp blog # apps/blog (HTML blueprint)
|
|
36
|
+
python manage.py startapp posts --api # apps/posts (JSON API, /api/posts)
|
|
37
|
+
python manage.py add mail cache limiter # extension qo'shish (pip install + kod ulash)
|
|
38
|
+
python manage.py makemigrations -m "initial" # Flask-Migrate (init avtomatik)
|
|
39
|
+
python manage.py migrate
|
|
40
|
+
python manage.py createsuperuser # `add login` dan keyin
|
|
41
|
+
python manage.py runserver # http://127.0.0.1:8000
|
|
42
|
+
python manage.py extensions # ro'yxat
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
`flaskforge startapp|add|extensions` loyihaning istalgan papkasidan ham ishlaydi.
|
|
46
|
+
|
|
47
|
+
## Yaratiladigan struktura
|
|
48
|
+
|
|
49
|
+
```
|
|
50
|
+
config/settings.py Base/Development/Testing/Production, INSTALLED_APPS
|
|
51
|
+
core/__init__.py create_app() - app factory, INSTALLED_APPS ni avtomatik yuklaydi
|
|
52
|
+
core/extensions.py db, login_manager, ... (marker'lar orqali avtomatik to'ldiriladi)
|
|
53
|
+
apps/<name>/ views.py (bp), models.py, [forms.py, schemas.py, events.py, commands.py]
|
|
54
|
+
templates/ static/ tests/ wsgi.py Dockerfile .env
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Har bir app'dan avtomatik yuklanadi: `models.py`, `events.py`, `views.py` (`bp`),
|
|
58
|
+
`commands.py` (`commands = [...]` -> `manage.py` buyruqlari).
|
|
59
|
+
|
|
60
|
+
## Qo'llab-quvvatlanadigan extensionlar
|
|
61
|
+
|
|
62
|
+
sqlalchemy, migrate, login (apps/accounts bilan), wtf (CSRF), mail, cors, jwt, cache,
|
|
63
|
+
limiter, babel, marshmallow, socketio, admin, debugtoolbar, talisman, compress.
|
|
64
|
+
|
|
65
|
+
Yangisini qo'shish: `src/flaskforge/registry.py` ichiga bitta `Extension(...)` yozuvi.
|
|
66
|
+
|
|
67
|
+
## Qanday ishlaydi
|
|
68
|
+
|
|
69
|
+
`add` buyrug'i `core/extensions.py` va `config/settings.py` ichidagi `# forge:...`
|
|
70
|
+
izohlari (marker) tepasiga kod qo'shadi. Amal idempotent: ikki marta ishlatsangiz
|
|
71
|
+
hech narsa takrorlanmaydi. Mavjud fayllar `--force`siz ustidan yozilmaydi.
|
|
72
|
+
|
|
73
|
+
## Test
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
pip install -e ".[dev]" && pytest
|
|
77
|
+
```
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# flaskforge
|
|
2
|
+
|
|
3
|
+
Flask uchun Django'ga o'xshash CLI: katta loyiha strukturasini avtomatik yaratadi va
|
|
4
|
+
Flask extensionlarini bitta buyruq bilan ulaydi.
|
|
5
|
+
|
|
6
|
+
## O'rnatish
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
pip install -e .
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## Ishlatish
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
flaskforge startproject shop --preset web # minimal | web | api | full
|
|
16
|
+
cd shop
|
|
17
|
+
python -m venv .venv && source .venv/bin/activate
|
|
18
|
+
pip install -r requirements-dev.txt && pip install -e /path/to/flaskforge
|
|
19
|
+
|
|
20
|
+
python manage.py startapp blog # apps/blog (HTML blueprint)
|
|
21
|
+
python manage.py startapp posts --api # apps/posts (JSON API, /api/posts)
|
|
22
|
+
python manage.py add mail cache limiter # extension qo'shish (pip install + kod ulash)
|
|
23
|
+
python manage.py makemigrations -m "initial" # Flask-Migrate (init avtomatik)
|
|
24
|
+
python manage.py migrate
|
|
25
|
+
python manage.py createsuperuser # `add login` dan keyin
|
|
26
|
+
python manage.py runserver # http://127.0.0.1:8000
|
|
27
|
+
python manage.py extensions # ro'yxat
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
`flaskforge startapp|add|extensions` loyihaning istalgan papkasidan ham ishlaydi.
|
|
31
|
+
|
|
32
|
+
## Yaratiladigan struktura
|
|
33
|
+
|
|
34
|
+
```
|
|
35
|
+
config/settings.py Base/Development/Testing/Production, INSTALLED_APPS
|
|
36
|
+
core/__init__.py create_app() - app factory, INSTALLED_APPS ni avtomatik yuklaydi
|
|
37
|
+
core/extensions.py db, login_manager, ... (marker'lar orqali avtomatik to'ldiriladi)
|
|
38
|
+
apps/<name>/ views.py (bp), models.py, [forms.py, schemas.py, events.py, commands.py]
|
|
39
|
+
templates/ static/ tests/ wsgi.py Dockerfile .env
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Har bir app'dan avtomatik yuklanadi: `models.py`, `events.py`, `views.py` (`bp`),
|
|
43
|
+
`commands.py` (`commands = [...]` -> `manage.py` buyruqlari).
|
|
44
|
+
|
|
45
|
+
## Qo'llab-quvvatlanadigan extensionlar
|
|
46
|
+
|
|
47
|
+
sqlalchemy, migrate, login (apps/accounts bilan), wtf (CSRF), mail, cors, jwt, cache,
|
|
48
|
+
limiter, babel, marshmallow, socketio, admin, debugtoolbar, talisman, compress.
|
|
49
|
+
|
|
50
|
+
Yangisini qo'shish: `src/flaskforge/registry.py` ichiga bitta `Extension(...)` yozuvi.
|
|
51
|
+
|
|
52
|
+
## Qanday ishlaydi
|
|
53
|
+
|
|
54
|
+
`add` buyrug'i `core/extensions.py` va `config/settings.py` ichidagi `# forge:...`
|
|
55
|
+
izohlari (marker) tepasiga kod qo'shadi. Amal idempotent: ikki marta ishlatsangiz
|
|
56
|
+
hech narsa takrorlanmaydi. Mavjud fayllar `--force`siz ustidan yozilmaydi.
|
|
57
|
+
|
|
58
|
+
## Test
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
pip install -e ".[dev]" && pytest
|
|
62
|
+
```
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "flaskforge-cli"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Django-like CLI that scaffolds and extends large Flask projects"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
dependencies = [
|
|
12
|
+
"click>=8.1",
|
|
13
|
+
"Jinja2>=3.1",
|
|
14
|
+
"Flask>=3.0",
|
|
15
|
+
"python-dotenv>=1.0",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
[project.optional-dependencies]
|
|
19
|
+
dev = ["pytest"]
|
|
20
|
+
|
|
21
|
+
[project.scripts]
|
|
22
|
+
flaskforge = "flaskforge.cli:main"
|
|
23
|
+
|
|
24
|
+
[tool.setuptools.packages.find]
|
|
25
|
+
where = ["src"]
|
|
26
|
+
|
|
27
|
+
[tool.setuptools.package-data]
|
|
28
|
+
flaskforge = ["templates/**/*"]
|
|
29
|
+
|
|
30
|
+
[tool.pytest.ini_options]
|
|
31
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""Entry point of the global `flaskforge` command (like `django-admin`)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import click
|
|
6
|
+
|
|
7
|
+
from . import __version__
|
|
8
|
+
from .commands import PROJECT_COMMANDS, startproject
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@click.group(help="Django-like scaffolding for large Flask projects.")
|
|
12
|
+
@click.version_option(__version__, prog_name="flaskforge")
|
|
13
|
+
def cli():
|
|
14
|
+
pass
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
cli.add_command(startproject)
|
|
18
|
+
for _cmd in PROJECT_COMMANDS:
|
|
19
|
+
cli.add_command(_cmd)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def main() -> None:
|
|
23
|
+
cli(prog_name="flaskforge")
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Click commands shared by `flaskforge` and the generated `manage.py`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import click
|
|
6
|
+
|
|
7
|
+
from .generators import add_extensions, create_app, create_project, parse_with
|
|
8
|
+
from .registry import EXTENSIONS, PRESETS, resolve_key
|
|
9
|
+
from .scaffold import Project
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@click.command(help="Create a new Flask project (app factory, settings, blueprints, tests).")
|
|
13
|
+
@click.argument("name")
|
|
14
|
+
@click.argument("directory", required=False)
|
|
15
|
+
@click.option("--preset", type=click.Choice(sorted(PRESETS)), default="minimal", show_default=True,
|
|
16
|
+
help="Ready-made extension bundle.")
|
|
17
|
+
@click.option("-e", "--with", "with_", multiple=True, metavar="EXT[,EXT]",
|
|
18
|
+
help="Extra extensions (repeat or comma-separate). See `flaskforge extensions`.")
|
|
19
|
+
@click.option("--install/--no-install", default=False, show_default=True,
|
|
20
|
+
help="pip install the project's requirements right away.")
|
|
21
|
+
@click.option("--force", is_flag=True, help="Allow a non-empty directory / overwrite files.")
|
|
22
|
+
def startproject(name, directory, preset, with_, install, force):
|
|
23
|
+
project = create_project(name, directory, preset, parse_with(with_), install, force)
|
|
24
|
+
cd = "" if name == "." else f" cd {directory or name}\n"
|
|
25
|
+
click.secho("\nProject ready. Next steps:", bold=True)
|
|
26
|
+
click.echo(
|
|
27
|
+
f"{cd}"
|
|
28
|
+
" python -m venv .venv && source .venv/bin/activate\n"
|
|
29
|
+
" pip install -r requirements-dev.txt # + flaskforge itself for manage.py\n"
|
|
30
|
+
" python manage.py runserver"
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@click.command(help="Create a new app (blueprint package) inside apps/ and register it.")
|
|
35
|
+
@click.argument("name")
|
|
36
|
+
@click.option("--api", is_flag=True, help="JSON API blueprint mounted at /api/<name>.")
|
|
37
|
+
@click.option("--force", is_flag=True)
|
|
38
|
+
def startapp(name, api, force):
|
|
39
|
+
create_app(Project.find(), name, api=api, force=force)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@click.command(help="Install and wire up Flask extensions, e.g. `add sqlalchemy login mail`.")
|
|
43
|
+
@click.argument("names", nargs=-1, required=True)
|
|
44
|
+
@click.option("--install/--no-install", default=True, show_default=True,
|
|
45
|
+
help="Run pip install for the extension packages.")
|
|
46
|
+
@click.option("--force", is_flag=True, help="Overwrite scaffolded files that already exist.")
|
|
47
|
+
def add(names, install, force):
|
|
48
|
+
try:
|
|
49
|
+
keys = [resolve_key(n) for n in names]
|
|
50
|
+
except KeyError as exc:
|
|
51
|
+
raise click.ClickException(exc.args[0]) from exc
|
|
52
|
+
done = add_extensions(Project.find(), list(dict.fromkeys(keys)), install=install, force=force)
|
|
53
|
+
if done:
|
|
54
|
+
click.secho("\nDone: " + ", ".join(done), bold=True)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@click.command(name="extensions", help="List supported extensions and what is installed.")
|
|
58
|
+
def list_extensions():
|
|
59
|
+
try:
|
|
60
|
+
installed = set(Project.find().extensions)
|
|
61
|
+
except click.ClickException:
|
|
62
|
+
installed = set()
|
|
63
|
+
width = max(len(k) for k in EXTENSIONS)
|
|
64
|
+
for key, ext in EXTENSIONS.items():
|
|
65
|
+
mark = click.style("[x]", fg="green") if key in installed else "[ ]"
|
|
66
|
+
click.echo(f"{mark} {key.ljust(width)} {ext.title:<20} {ext.description}")
|
|
67
|
+
click.echo("\nPresets: " + "; ".join(f"{p} = {', '.join(v) or '-'}" for p, v in PRESETS.items()))
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
PROJECT_COMMANDS = [startapp, add, list_extensions]
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
"""The actual work behind startproject / startapp / add."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
import secrets
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
import click
|
|
12
|
+
|
|
13
|
+
from . import __version__
|
|
14
|
+
from .registry import EXTENSIONS, PRESETS, Extension, resolve_key
|
|
15
|
+
from .scaffold import (
|
|
16
|
+
MANIFEST,
|
|
17
|
+
TEMPLATES_DIR,
|
|
18
|
+
Project,
|
|
19
|
+
add_requirements,
|
|
20
|
+
inject,
|
|
21
|
+
render,
|
|
22
|
+
set_env,
|
|
23
|
+
write_file,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
RESERVED_APP_NAMES = {
|
|
27
|
+
"core", "config", "apps", "tests", "templates", "static", "migrations",
|
|
28
|
+
"instance", "flask", "manage", "wsgi", "venv",
|
|
29
|
+
}
|
|
30
|
+
_PROJECT_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_-]*$")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# --------------------------------------------------------------------------- helpers
|
|
34
|
+
def _ctx(project: Project, **extra) -> dict:
|
|
35
|
+
return {
|
|
36
|
+
"project": project.name,
|
|
37
|
+
"project_slug": project.slug,
|
|
38
|
+
"ext": set(project.extensions),
|
|
39
|
+
**extra,
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _render_files(project: Project, files, ctx: dict, force: bool = False) -> None:
|
|
44
|
+
for template, dest in files:
|
|
45
|
+
write_file(project.root / dest, render(template, ctx), root=project.root, force=force)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _pip_install(args: list) -> None:
|
|
49
|
+
cmd = [sys.executable, "-m", "pip", "install", *args]
|
|
50
|
+
click.secho(" run " + " ".join(cmd), fg="cyan")
|
|
51
|
+
try:
|
|
52
|
+
subprocess.check_call(cmd)
|
|
53
|
+
except subprocess.CalledProcessError as exc:
|
|
54
|
+
raise click.ClickException(
|
|
55
|
+
f"pip failed (exit {exc.returncode}). Nothing was changed in your project."
|
|
56
|
+
) from exc
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def register_app(project: Project, dotted: str) -> None:
|
|
60
|
+
"""Add ``dotted`` to INSTALLED_APPS (settings file + manifest)."""
|
|
61
|
+
inject(project.root / "config" / "settings.py", "# forge:apps", [f'"{dotted}",'])
|
|
62
|
+
if dotted not in project.apps:
|
|
63
|
+
project.apps.append(dotted)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
# --------------------------------------------------------------------------- startproject
|
|
67
|
+
def parse_with(values) -> list:
|
|
68
|
+
keys = []
|
|
69
|
+
for value in values:
|
|
70
|
+
for part in value.split(","):
|
|
71
|
+
if part.strip():
|
|
72
|
+
try:
|
|
73
|
+
keys.append(resolve_key(part))
|
|
74
|
+
except KeyError as exc:
|
|
75
|
+
raise click.ClickException(exc.args[0]) from exc
|
|
76
|
+
return keys
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def create_project(name: str, directory: str | None, preset: str, extra: list,
|
|
80
|
+
install: bool, force: bool) -> Project:
|
|
81
|
+
target = Path(directory or (name if name != "." else ".")).resolve()
|
|
82
|
+
display_name = target.name if name == "." else name
|
|
83
|
+
if not _PROJECT_RE.match(display_name):
|
|
84
|
+
raise click.ClickException(
|
|
85
|
+
f"'{display_name}' is not a valid project name "
|
|
86
|
+
"(letters, digits, '-' and '_'; must start with a letter)."
|
|
87
|
+
)
|
|
88
|
+
if target.exists() and any(target.iterdir()) and not force:
|
|
89
|
+
raise click.ClickException(f"Directory {target} is not empty (use --force to continue).")
|
|
90
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
91
|
+
|
|
92
|
+
project = Project(target, {
|
|
93
|
+
"flaskforge": __version__,
|
|
94
|
+
"project": display_name,
|
|
95
|
+
"extensions": [],
|
|
96
|
+
"apps": ["apps.main"],
|
|
97
|
+
})
|
|
98
|
+
ctx = _ctx(project, secret_key=secrets.token_urlsafe(50))
|
|
99
|
+
|
|
100
|
+
click.secho(f"Creating project '{display_name}' in {target}", bold=True)
|
|
101
|
+
base = TEMPLATES_DIR / "project"
|
|
102
|
+
for tpl in sorted(base.rglob("*.tpl")):
|
|
103
|
+
rel = tpl.relative_to(base)
|
|
104
|
+
parts = list(rel.parts)
|
|
105
|
+
parts[-1] = parts[-1][: -len(".tpl")]
|
|
106
|
+
parts = [("." + p[4:]) if p.startswith("dot_") else p for p in parts]
|
|
107
|
+
write_file(
|
|
108
|
+
target.joinpath(*parts),
|
|
109
|
+
render("project/" + rel.as_posix(), ctx),
|
|
110
|
+
root=target,
|
|
111
|
+
force=force,
|
|
112
|
+
)
|
|
113
|
+
project.save()
|
|
114
|
+
|
|
115
|
+
keys = list(dict.fromkeys(PRESETS[preset] + extra))
|
|
116
|
+
if keys:
|
|
117
|
+
add_extensions(project, keys, install=False)
|
|
118
|
+
|
|
119
|
+
if install:
|
|
120
|
+
_pip_install(["-r", str(target / "requirements-dev.txt")])
|
|
121
|
+
return project
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
# --------------------------------------------------------------------------- startapp
|
|
125
|
+
def validate_app_name(project: Project, name: str) -> None:
|
|
126
|
+
import keyword
|
|
127
|
+
|
|
128
|
+
if not name.isidentifier() or keyword.iskeyword(name) or name != name.lower() or name.startswith("_"):
|
|
129
|
+
raise click.ClickException(
|
|
130
|
+
f"'{name}' is not a valid app name - use lowercase snake_case (e.g. 'blog', 'user_profile')."
|
|
131
|
+
)
|
|
132
|
+
if name in RESERVED_APP_NAMES:
|
|
133
|
+
raise click.ClickException(f"'{name}' is a reserved name, pick another one.")
|
|
134
|
+
if (project.root / "apps" / name).exists():
|
|
135
|
+
raise click.ClickException(f"apps/{name} already exists.")
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def create_app(project: Project, name: str, api: bool = False, force: bool = False) -> None:
|
|
139
|
+
validate_app_name(project, name)
|
|
140
|
+
ctx = _ctx(
|
|
141
|
+
project,
|
|
142
|
+
app_name=name,
|
|
143
|
+
class_name="".join(p.capitalize() for p in name.split("_")),
|
|
144
|
+
api=api,
|
|
145
|
+
)
|
|
146
|
+
click.secho(f"Creating {'API ' if api else ''}app '{name}'", bold=True)
|
|
147
|
+
exts = ctx["ext"]
|
|
148
|
+
files = [
|
|
149
|
+
("app/__init__.py.tpl", f"apps/{name}/__init__.py"),
|
|
150
|
+
("app/views.py.tpl", f"apps/{name}/views.py"),
|
|
151
|
+
("app/models.py.tpl", f"apps/{name}/models.py"),
|
|
152
|
+
("app/test_app.py.tpl", f"tests/test_{name}.py"),
|
|
153
|
+
]
|
|
154
|
+
if not api:
|
|
155
|
+
files.append(("app/index.html.tpl", f"apps/{name}/templates/{name}/index.html"))
|
|
156
|
+
if "wtf" in exts:
|
|
157
|
+
files.append(("app/forms.py.tpl", f"apps/{name}/forms.py"))
|
|
158
|
+
elif "marshmallow" in exts:
|
|
159
|
+
files.append(("app/schemas.py.tpl", f"apps/{name}/schemas.py"))
|
|
160
|
+
_render_files(project, files, ctx, force)
|
|
161
|
+
register_app(project, f"apps.{name}")
|
|
162
|
+
project.save()
|
|
163
|
+
prefix = f"/api/{name}" if api else f"/{name}"
|
|
164
|
+
click.secho(f" updated config/settings.py (INSTALLED_APPS += apps.{name})", fg="green")
|
|
165
|
+
click.echo(f"\nDone. Open {prefix}/ after `python manage.py runserver`.")
|
|
166
|
+
if "migrate" in exts and "sqlalchemy" in exts:
|
|
167
|
+
click.echo("Next: python manage.py makemigrations -m 'add " + name + "' && python manage.py migrate")
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
# --------------------------------------------------------------------------- add
|
|
171
|
+
def _plan(project: Project, keys: list) -> list:
|
|
172
|
+
ordered: list = []
|
|
173
|
+
seen = set(project.extensions)
|
|
174
|
+
|
|
175
|
+
def visit(key: str) -> None:
|
|
176
|
+
ext = EXTENSIONS[key]
|
|
177
|
+
for dep in ext.requires:
|
|
178
|
+
visit(dep)
|
|
179
|
+
if key not in seen:
|
|
180
|
+
seen.add(key)
|
|
181
|
+
ordered.append(ext)
|
|
182
|
+
|
|
183
|
+
for k in keys:
|
|
184
|
+
visit(k)
|
|
185
|
+
return ordered
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def add_extensions(project: Project, keys: list, install: bool = True, force: bool = False) -> list:
|
|
189
|
+
plan = _plan(project, keys)
|
|
190
|
+
already = [k for k in keys if k in project.extensions]
|
|
191
|
+
for k in already:
|
|
192
|
+
click.secho(f" {EXTENSIONS[k].title} is already installed.", fg="yellow")
|
|
193
|
+
if not plan:
|
|
194
|
+
return []
|
|
195
|
+
|
|
196
|
+
if install:
|
|
197
|
+
packages = [p for e in plan for p in e.packages]
|
|
198
|
+
_pip_install(packages)
|
|
199
|
+
|
|
200
|
+
for ext in plan:
|
|
201
|
+
_apply_extension(project, ext, force)
|
|
202
|
+
return [e.key for e in plan]
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _apply_extension(project: Project, ext: Extension, force: bool) -> None:
|
|
206
|
+
root = project.root
|
|
207
|
+
click.secho(f"Adding {ext.title}", bold=True)
|
|
208
|
+
extpy = root / "core" / "extensions.py"
|
|
209
|
+
settings = root / "config" / "settings.py"
|
|
210
|
+
for p in (extpy, settings):
|
|
211
|
+
if not p.exists():
|
|
212
|
+
raise click.ClickException(f"{project.rel(p)} is missing - cannot add extensions.")
|
|
213
|
+
|
|
214
|
+
inject(extpy, "# forge:imports", ext.imports)
|
|
215
|
+
inject(extpy, "# forge:instances", ext.instances)
|
|
216
|
+
inject(extpy, "# forge:init", ext.init)
|
|
217
|
+
if ext.settings:
|
|
218
|
+
inject(settings, "# forge:settings", [f"# {ext.title}", *ext.settings, ""])
|
|
219
|
+
if ext.prod_settings:
|
|
220
|
+
inject(settings, "# forge:prod-settings", list(ext.prod_settings))
|
|
221
|
+
click.secho(" updated core/extensions.py, config/settings.py", fg="green")
|
|
222
|
+
|
|
223
|
+
if ext.env:
|
|
224
|
+
for name in (".env", ".env.example"):
|
|
225
|
+
set_env(root / name, ext.env)
|
|
226
|
+
req = root / ("requirements-dev.txt" if ext.dev else "requirements.txt")
|
|
227
|
+
add_requirements(req, ext.packages)
|
|
228
|
+
|
|
229
|
+
project.extensions.append(ext.key) # before rendering: templates may inspect `ext`
|
|
230
|
+
_render_files(project, ext.files, _ctx(project), force)
|
|
231
|
+
for dotted in ext.apps:
|
|
232
|
+
register_app(project, dotted)
|
|
233
|
+
project.save()
|
|
234
|
+
if ext.notes:
|
|
235
|
+
click.secho(f" note {ext.notes}", fg="cyan")
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"""`python manage.py ...` - project-level commands (like Django's manage.py).
|
|
2
|
+
|
|
3
|
+
Built on flask.cli.FlaskGroup, so every built-in Flask command (shell, routes, run)
|
|
4
|
+
and every command registered by installed extensions (e.g. Flask-Migrate's `db`)
|
|
5
|
+
is available too.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import sys
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
import click
|
|
15
|
+
from flask.cli import FlaskGroup, with_appcontext
|
|
16
|
+
|
|
17
|
+
from .commands import PROJECT_COMMANDS
|
|
18
|
+
from .scaffold import Project
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _create_app():
|
|
22
|
+
from core import create_app
|
|
23
|
+
|
|
24
|
+
return create_app()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _require(key: str) -> None:
|
|
28
|
+
if key not in Project.find().extensions:
|
|
29
|
+
raise click.ClickException(
|
|
30
|
+
f"The '{key}' extension is not installed. Run: python manage.py add {key}"
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@click.command(help="Start the development server (autoreload + debugger in development).")
|
|
35
|
+
@click.option("-h", "--host", default="127.0.0.1", show_default=True)
|
|
36
|
+
@click.option("-p", "--port", default=8000, show_default=True, type=int)
|
|
37
|
+
@click.option("--debug/--no-debug", default=None, help="Defaults to the config's DEBUG.")
|
|
38
|
+
@click.option("--reload/--no-reload", default=None, help="Defaults to the debug value.")
|
|
39
|
+
def runserver(host, port, debug, reload):
|
|
40
|
+
from core import extensions
|
|
41
|
+
|
|
42
|
+
app = _create_app()
|
|
43
|
+
debug = app.debug if debug is None else debug
|
|
44
|
+
reload = debug if reload is None else reload
|
|
45
|
+
socketio = getattr(extensions, "socketio", None)
|
|
46
|
+
# FlaskGroup sets this flag, which makes app.run() a silent no-op ("Ignoring a call
|
|
47
|
+
# to app.run()"). We *are* the server command, so clear it (also covers socketio.run).
|
|
48
|
+
os.environ.pop("FLASK_RUN_FROM_CLI", None)
|
|
49
|
+
if socketio is not None:
|
|
50
|
+
socketio.run(app, host=host, port=port, debug=debug, use_reloader=reload,
|
|
51
|
+
allow_unsafe_werkzeug=True)
|
|
52
|
+
else:
|
|
53
|
+
app.run(host=host, port=port, debug=debug, use_reloader=reload)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@click.command(help="Create new migrations from model changes (runs `init` the first time).")
|
|
57
|
+
@click.option("-m", "--message", default=None, help="Migration message.")
|
|
58
|
+
@with_appcontext
|
|
59
|
+
def makemigrations(message):
|
|
60
|
+
_require("migrate")
|
|
61
|
+
import flask_migrate
|
|
62
|
+
|
|
63
|
+
if not Path("migrations").exists():
|
|
64
|
+
flask_migrate.init()
|
|
65
|
+
flask_migrate.migrate(message=message)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@click.command(help="Apply database migrations.")
|
|
69
|
+
@click.option("--revision", default="head", show_default=True)
|
|
70
|
+
@with_appcontext
|
|
71
|
+
def migrate(revision):
|
|
72
|
+
_require("migrate")
|
|
73
|
+
import flask_migrate
|
|
74
|
+
|
|
75
|
+
flask_migrate.upgrade(revision=revision)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@click.command(help="Roll back the last migration (or to --revision).")
|
|
79
|
+
@click.option("--revision", default="-1", show_default=True)
|
|
80
|
+
@with_appcontext
|
|
81
|
+
def rollback(revision):
|
|
82
|
+
_require("migrate")
|
|
83
|
+
import flask_migrate
|
|
84
|
+
|
|
85
|
+
flask_migrate.downgrade(revision=revision)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@click.command(help="Load the app and report blueprints / routes (sanity check).")
|
|
89
|
+
def check():
|
|
90
|
+
app = _create_app()
|
|
91
|
+
rules = [r for r in app.url_map.iter_rules() if r.endpoint != "static"]
|
|
92
|
+
click.secho(
|
|
93
|
+
f"System check identified no issues ({len(app.blueprints)} blueprints, {len(rules)} routes).",
|
|
94
|
+
fg="green",
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def execute_from_command_line(manage_file: str) -> None:
|
|
99
|
+
root = Path(manage_file).resolve().parent
|
|
100
|
+
os.chdir(root)
|
|
101
|
+
if str(root) not in sys.path:
|
|
102
|
+
sys.path.insert(0, str(root))
|
|
103
|
+
|
|
104
|
+
cli = FlaskGroup(
|
|
105
|
+
create_app=_create_app,
|
|
106
|
+
help="Project management utility (flaskforge). Run a command with --help for details.",
|
|
107
|
+
)
|
|
108
|
+
for cmd in (*PROJECT_COMMANDS, runserver, makemigrations, migrate, rollback, check):
|
|
109
|
+
cli.add_command(cmd)
|
|
110
|
+
cli.main(prog_name="python manage.py")
|