flaskforge-cli 0.1.0__py3-none-any.whl

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.
Files changed (56) hide show
  1. flaskforge/__init__.py +3 -0
  2. flaskforge/__main__.py +4 -0
  3. flaskforge/cli.py +23 -0
  4. flaskforge/commands.py +70 -0
  5. flaskforge/generators.py +235 -0
  6. flaskforge/management.py +110 -0
  7. flaskforge/registry.py +311 -0
  8. flaskforge/scaffold.py +156 -0
  9. flaskforge/templates/app/__init__.py.tpl +1 -0
  10. flaskforge/templates/app/forms.py.tpl +7 -0
  11. flaskforge/templates/app/index.html.tpl +9 -0
  12. flaskforge/templates/app/models.py.tpl +17 -0
  13. flaskforge/templates/app/schemas.py.tpl +9 -0
  14. flaskforge/templates/app/test_app.py.tpl +20 -0
  15. flaskforge/templates/app/views.py.tpl +61 -0
  16. flaskforge/templates/ext/login/__init__.py.tpl +1 -0
  17. flaskforge/templates/ext/login/_csrf.html.tpl +2 -0
  18. flaskforge/templates/ext/login/commands.py.tpl +24 -0
  19. flaskforge/templates/ext/login/login.html.tpl +15 -0
  20. flaskforge/templates/ext/login/models.py.tpl +28 -0
  21. flaskforge/templates/ext/login/profile.html.tpl +13 -0
  22. flaskforge/templates/ext/login/register.html.tpl +15 -0
  23. flaskforge/templates/ext/login/test_accounts.py.tpl +31 -0
  24. flaskforge/templates/ext/login/views.py.tpl +70 -0
  25. flaskforge/templates/ext/sqlalchemy/mixins.py.tpl +15 -0
  26. flaskforge/templates/project/Dockerfile.tpl +14 -0
  27. flaskforge/templates/project/README.md.tpl +40 -0
  28. flaskforge/templates/project/apps/__init__.py.tpl +1 -0
  29. flaskforge/templates/project/apps/main/__init__.py.tpl +1 -0
  30. flaskforge/templates/project/apps/main/templates/main/index.html.tpl +15 -0
  31. flaskforge/templates/project/apps/main/views.py.tpl +13 -0
  32. flaskforge/templates/project/config/__init__.py.tpl +3 -0
  33. flaskforge/templates/project/config/settings.py.tpl +60 -0
  34. flaskforge/templates/project/core/__init__.py.tpl +53 -0
  35. flaskforge/templates/project/core/errors.py.tpl +15 -0
  36. flaskforge/templates/project/core/extensions.py.tpl +17 -0
  37. flaskforge/templates/project/dot_env.example.tpl +2 -0
  38. flaskforge/templates/project/dot_env.tpl +2 -0
  39. flaskforge/templates/project/dot_gitignore.tpl +16 -0
  40. flaskforge/templates/project/manage.py.tpl +18 -0
  41. flaskforge/templates/project/pytest.ini.tpl +2 -0
  42. flaskforge/templates/project/requirements-dev.txt.tpl +3 -0
  43. flaskforge/templates/project/requirements.txt.tpl +3 -0
  44. flaskforge/templates/project/static/css/style.css.tpl +23 -0
  45. flaskforge/templates/project/templates/base.html.tpl +35 -0
  46. flaskforge/templates/project/templates/errors/error.html.tpl +9 -0
  47. flaskforge/templates/project/tests/__init__.py.tpl +1 -0
  48. flaskforge/templates/project/tests/conftest.py.tpl +21 -0
  49. flaskforge/templates/project/tests/test_main.py.tpl +13 -0
  50. flaskforge/templates/project/wsgi.py.tpl +4 -0
  51. flaskforge_cli-0.1.0.dist-info/METADATA +77 -0
  52. flaskforge_cli-0.1.0.dist-info/RECORD +56 -0
  53. flaskforge_cli-0.1.0.dist-info/WHEEL +5 -0
  54. flaskforge_cli-0.1.0.dist-info/entry_points.txt +2 -0
  55. flaskforge_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
  56. flaskforge_cli-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,13 @@
1
+ {% extends "base.html" %}
2
+ {% block title %}Profile{% endblock %}
3
+
4
+ {% block content %}
5
+ <section class="card">
6
+ <h1>Profile</h1>
7
+ <p>Signed in as <strong>{{ current_user.email }}</strong>{% if current_user.is_admin %} (admin){% endif %}.</p>
8
+ <form method="post" action="{{ url_for('accounts.logout') }}">
9
+ {% include "accounts/_csrf.html" %}
10
+ <button type="submit">Log out</button>
11
+ </form>
12
+ </section>
13
+ {% endblock %}
@@ -0,0 +1,15 @@
1
+ {% extends "base.html" %}
2
+ {% block title %}Register{% endblock %}
3
+
4
+ {% block content %}
5
+ <section class="card">
6
+ <h1>Create account</h1>
7
+ <form method="post" class="stack">
8
+ {% include "accounts/_csrf.html" %}
9
+ <input type="email" name="email" placeholder="Email" required autofocus>
10
+ <input type="password" name="password" placeholder="Password (min. 8 characters)" minlength="8" required>
11
+ <button type="submit">Register</button>
12
+ </form>
13
+ <p class="muted">Already registered? <a href="{{ url_for('accounts.login') }}">Log in</a></p>
14
+ </section>
15
+ {% endblock %}
@@ -0,0 +1,31 @@
1
+ def test_profile_requires_login(client):
2
+ response = client.get("/accounts/profile")
3
+ assert response.status_code == 302
4
+ assert "/accounts/login" in response.headers["Location"]
5
+
6
+
7
+ def test_register_login_logout(client):
8
+ credentials = {"email": "user@example.com", "password": "s3cret-pass"}
9
+
10
+ response = client.post("/accounts/register", data=credentials)
11
+ assert response.status_code == 302 # registered and logged in
12
+ assert client.get("/accounts/profile").status_code == 200
13
+
14
+ client.post("/accounts/logout")
15
+ assert client.get("/accounts/profile").status_code == 302
16
+
17
+ bad = client.post("/accounts/login", data={**credentials, "password": "wrong"})
18
+ assert bad.status_code == 200 # form re-rendered with an error
19
+
20
+ good = client.post("/accounts/login", data=credentials)
21
+ assert good.status_code == 302
22
+ assert client.get("/accounts/profile").status_code == 200
23
+
24
+
25
+ def test_duplicate_email_rejected(client):
26
+ credentials = {"email": "dup@example.com", "password": "s3cret-pass"}
27
+ client.post("/accounts/register", data=credentials)
28
+ client.post("/accounts/logout")
29
+ again = client.post("/accounts/register", data=credentials)
30
+ assert again.status_code == 200
31
+ assert b"already registered" in again.data
@@ -0,0 +1,70 @@
1
+ from flask import Blueprint, flash, redirect, render_template, request, url_for
2
+ from flask_login import current_user, login_required, login_user, logout_user
3
+
4
+ from core.extensions import db
5
+
6
+ from .models import User
7
+
8
+ bp = Blueprint("accounts", __name__, url_prefix="/accounts", template_folder="templates")
9
+
10
+
11
+ def _safe_next(target):
12
+ """Only follow relative redirects (prevents open-redirect attacks)."""
13
+ if target and target.startswith("/") and not target.startswith("//") and "\\" not in target:
14
+ return target
15
+ return "/"
16
+
17
+
18
+ def _find_user(email):
19
+ return db.session.execute(db.select(User).filter_by(email=email)).scalar_one_or_none()
20
+
21
+
22
+ @bp.route("/register", methods=["GET", "POST"])
23
+ def register():
24
+ if request.method == "POST":
25
+ email = request.form.get("email", "").strip().lower()
26
+ password = request.form.get("password", "")
27
+ error = None
28
+ if "@" not in email:
29
+ error = "Enter a valid email address."
30
+ elif len(password) < 8:
31
+ error = "Password must be at least 8 characters."
32
+ elif _find_user(email):
33
+ error = "This email is already registered."
34
+ if error:
35
+ flash(error, "error")
36
+ else:
37
+ user = User(email=email)
38
+ user.set_password(password)
39
+ db.session.add(user)
40
+ db.session.commit()
41
+ login_user(user)
42
+ flash("Welcome! Your account has been created.", "success")
43
+ return redirect(_safe_next(request.args.get("next")))
44
+ return render_template("accounts/register.html")
45
+
46
+
47
+ @bp.route("/login", methods=["GET", "POST"])
48
+ def login():
49
+ if request.method == "POST":
50
+ email = request.form.get("email", "").strip().lower()
51
+ user = _find_user(email)
52
+ if user and user.check_password(request.form.get("password", "")):
53
+ login_user(user)
54
+ return redirect(_safe_next(request.args.get("next")))
55
+ flash("Invalid email or password.", "error")
56
+ return render_template("accounts/login.html")
57
+
58
+
59
+ @bp.post("/logout")
60
+ @login_required
61
+ def logout():
62
+ logout_user()
63
+ flash("You have been logged out.", "success")
64
+ return redirect(url_for("accounts.login"))
65
+
66
+
67
+ @bp.get("/profile")
68
+ @login_required
69
+ def profile():
70
+ return render_template("accounts/profile.html")
@@ -0,0 +1,15 @@
1
+ """Reusable model mixins."""
2
+ from datetime import datetime, timezone
3
+
4
+ from .extensions import db
5
+
6
+
7
+ def _now():
8
+ return datetime.now(timezone.utc)
9
+
10
+
11
+ class TimestampMixin:
12
+ """Adds created_at / updated_at columns: class Post(TimestampMixin, db.Model)"""
13
+
14
+ created_at = db.Column(db.DateTime, default=_now, nullable=False)
15
+ updated_at = db.Column(db.DateTime, default=_now, onupdate=_now, nullable=False)
@@ -0,0 +1,14 @@
1
+ FROM python:3.12-slim
2
+
3
+ ENV PYTHONDONTWRITEBYTECODE=1 \
4
+ PYTHONUNBUFFERED=1 \
5
+ APP_ENV=production
6
+
7
+ WORKDIR /app
8
+ COPY requirements.txt .
9
+ RUN pip install --no-cache-dir -r requirements.txt
10
+ COPY . .
11
+
12
+ EXPOSE 8000
13
+ # SECRET_KEY (and DATABASE_URL etc.) must be provided as environment variables.
14
+ CMD ["gunicorn", "--bind", "0.0.0.0:8000", "wsgi:app"]
@@ -0,0 +1,40 @@
1
+ # [[ project ]]
2
+
3
+ Flask loyihasi (`flaskforge` bilan yaratilgan).
4
+
5
+ ## Ishga tushirish
6
+
7
+ ```bash
8
+ python -m venv .venv && source .venv/bin/activate
9
+ pip install -r requirements-dev.txt
10
+ pip install flaskforge # manage.py uchun
11
+ python manage.py runserver
12
+ ```
13
+
14
+ ## Tuzilma
15
+
16
+ ```
17
+ config/settings.py # sozlamalar (Base/Development/Testing/Production), INSTALLED_APPS
18
+ core/__init__.py # create_app() - application factory
19
+ core/extensions.py # barcha Flask extension obyektlari (db, login_manager, ...)
20
+ apps/<name>/ # har bir app: views.py (bp), models.py, templates/<name>/
21
+ templates/ # umumiy shablonlar (base.html)
22
+ tests/ # pytest
23
+ ```
24
+
25
+ ## Buyruqlar
26
+
27
+ ```bash
28
+ python manage.py startapp blog # yangi app (apps/blog)
29
+ python manage.py startapp posts --api # JSON API app (/api/posts)
30
+ python manage.py add sqlalchemy migrate # extension qo'shish
31
+ python manage.py extensions # mavjud extensionlar
32
+ python manage.py makemigrations -m "msg" # migratsiya yaratish
33
+ python manage.py migrate # migratsiyani qo'llash
34
+ python manage.py routes # URL'lar ro'yxati
35
+ python manage.py shell
36
+ pytest
37
+ ```
38
+
39
+ `config/settings.py` va `core/extensions.py` ichidagi `# forge:...` izohlarini o'chirmang:
40
+ flaskforge kodni aynan shu joylarga qo'shadi.
@@ -0,0 +1 @@
1
+ """Project apps. Create new ones with: python manage.py startapp <name>"""
@@ -0,0 +1 @@
1
+ """Landing page and health check."""
@@ -0,0 +1,15 @@
1
+ {% extends "base.html" %}
2
+
3
+ {% block content %}
4
+ <section class="card">
5
+ <h1>[[ project ]]</h1>
6
+ <p>Your Flask project is up and running.</p>
7
+ <h2>Installed apps</h2>
8
+ <ul>
9
+ {% for app_path in apps %}
10
+ <li><code>{{ app_path }}</code></li>
11
+ {% endfor %}
12
+ </ul>
13
+ <p class="muted">Edit <code>apps/main/views.py</code> to change this page.</p>
14
+ </section>
15
+ {% endblock %}
@@ -0,0 +1,13 @@
1
+ from flask import Blueprint, current_app, jsonify, render_template
2
+
3
+ bp = Blueprint("main", __name__, template_folder="templates")
4
+
5
+
6
+ @bp.get("/")
7
+ def index():
8
+ return render_template("main/index.html", apps=current_app.config["INSTALLED_APPS"])
9
+
10
+
11
+ @bp.get("/health")
12
+ def health():
13
+ return jsonify(status="ok")
@@ -0,0 +1,3 @@
1
+ from .settings import get_config
2
+
3
+ __all__ = ["get_config"]
@@ -0,0 +1,60 @@
1
+ """Project settings (Django-style). Secrets and per-environment values come from .env."""
2
+ import os
3
+ from pathlib import Path
4
+
5
+ from dotenv import load_dotenv
6
+
7
+ BASE_DIR = Path(__file__).resolve().parent.parent
8
+ load_dotenv(BASE_DIR / ".env")
9
+
10
+ INSECURE_KEY = "insecure-dev-key-change-me"
11
+
12
+
13
+ class BaseConfig:
14
+ BASE_DIR = BASE_DIR
15
+ SECRET_KEY = os.getenv("SECRET_KEY", INSECURE_KEY)
16
+ DEBUG = False
17
+ TESTING = False
18
+
19
+ # Blueprint packages under apps/. `manage.py startapp <name>` appends here.
20
+ INSTALLED_APPS = [
21
+ "apps.main",
22
+ # forge:apps
23
+ ]
24
+
25
+ # forge:settings
26
+
27
+
28
+ class DevelopmentConfig(BaseConfig):
29
+ DEBUG = True
30
+
31
+
32
+ class TestingConfig(BaseConfig):
33
+ TESTING = True
34
+ SECRET_KEY = "testing-secret-key"
35
+ WTF_CSRF_ENABLED = False
36
+ RATELIMIT_ENABLED = False
37
+ SQLALCHEMY_DATABASE_URI = "sqlite://"
38
+
39
+
40
+ class ProductionConfig(BaseConfig):
41
+ DEBUG = False
42
+ # forge:prod-settings
43
+
44
+
45
+ CONFIGS = {
46
+ "development": DevelopmentConfig,
47
+ "testing": TestingConfig,
48
+ "production": ProductionConfig,
49
+ }
50
+
51
+
52
+ def get_config(name=None):
53
+ name = name or os.getenv("APP_ENV", "development")
54
+ try:
55
+ config = CONFIGS[name]
56
+ except KeyError:
57
+ raise RuntimeError(f"Unknown APP_ENV '{name}'. Choose one of: {', '.join(CONFIGS)}") from None
58
+ if name == "production" and config.SECRET_KEY == INSECURE_KEY:
59
+ raise RuntimeError("SECRET_KEY must be set in the environment for production.")
60
+ return config
@@ -0,0 +1,53 @@
1
+ """Application factory."""
2
+ import importlib
3
+ import importlib.util
4
+
5
+ from flask import Flask
6
+
7
+ from config import get_config
8
+
9
+ from . import extensions
10
+ from .errors import register_error_handlers
11
+
12
+
13
+ def create_app(config_name=None):
14
+ config = get_config(config_name)
15
+ app = Flask(__name__, root_path=str(config.BASE_DIR), instance_relative_config=True)
16
+ app.config.from_object(config)
17
+
18
+ extensions.init_extensions(app)
19
+ register_apps(app)
20
+ register_error_handlers(app)
21
+ return app
22
+
23
+
24
+ def _has(module: str) -> bool:
25
+ return importlib.util.find_spec(module) is not None
26
+
27
+
28
+ def register_apps(app):
29
+ """Load every entry of INSTALLED_APPS.
30
+
31
+ Per app (all optional except that something must expose a blueprint):
32
+ models.py imported so the ORM / migrations see the models
33
+ events.py imported (e.g. Flask-SocketIO handlers)
34
+ views.py must define `bp` (or a `blueprints` list)
35
+ commands.py `commands = [click commands]` added to the CLI
36
+ """
37
+ csrf = getattr(extensions, "csrf", None)
38
+ for dotted in app.config["INSTALLED_APPS"]:
39
+ for sub in ("models", "events"):
40
+ if _has(f"{dotted}.{sub}"):
41
+ importlib.import_module(f"{dotted}.{sub}")
42
+
43
+ if _has(f"{dotted}.views"):
44
+ views = importlib.import_module(f"{dotted}.views")
45
+ for bp in getattr(views, "blueprints", None) or [views.bp]:
46
+ app.register_blueprint(bp)
47
+ # Token-authenticated JSON APIs don't use CSRF cookies.
48
+ if csrf is not None and (bp.url_prefix or "").startswith("/api"):
49
+ csrf.exempt(bp)
50
+
51
+ if _has(f"{dotted}.commands"):
52
+ for command in importlib.import_module(f"{dotted}.commands").commands:
53
+ app.cli.add_command(command)
@@ -0,0 +1,15 @@
1
+ """Error handlers: JSON for API clients, HTML for browsers."""
2
+ from flask import jsonify, render_template, request
3
+ from werkzeug.exceptions import HTTPException
4
+
5
+
6
+ def register_error_handlers(app):
7
+ @app.errorhandler(HTTPException)
8
+ def handle_http_error(error):
9
+ wants_json = (
10
+ request.path.startswith("/api")
11
+ or request.accept_mimetypes.best == "application/json"
12
+ )
13
+ if wants_json:
14
+ return jsonify(error=error.name, message=error.description), error.code
15
+ return render_template("errors/error.html", error=error), error.code
@@ -0,0 +1,17 @@
1
+ """Flask extension instances.
2
+
3
+ They live here (not inside create_app) so any module can do
4
+ `from core.extensions import db` without circular imports.
5
+
6
+ `python manage.py add <extension>` inserts code at the `# forge:` markers below -
7
+ please keep those comments.
8
+ """
9
+ # forge:imports
10
+
11
+
12
+ # forge:instances
13
+
14
+
15
+ def init_extensions(app):
16
+ """Bind every extension to the application (called by create_app)."""
17
+ # forge:init
@@ -0,0 +1,2 @@
1
+ APP_ENV=development
2
+ SECRET_KEY=change-me
@@ -0,0 +1,2 @@
1
+ APP_ENV=development
2
+ SECRET_KEY=[[ secret_key ]]
@@ -0,0 +1,16 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ venv/
5
+ .env
6
+ instance/
7
+ *.db
8
+ *.sqlite3
9
+ .pytest_cache/
10
+ .coverage
11
+ htmlcov/
12
+ dist/
13
+ build/
14
+ *.egg-info/
15
+ .idea/
16
+ .vscode/
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env python
2
+ """Command-line utility for [[ project ]] (powered by flaskforge)."""
3
+ import sys
4
+
5
+
6
+ def main():
7
+ try:
8
+ from flaskforge.management import execute_from_command_line
9
+ except ImportError as exc:
10
+ raise ImportError(
11
+ "Couldn't import flaskforge. Is it installed in this environment? "
12
+ "(pip install flaskforge)"
13
+ ) from exc
14
+ execute_from_command_line(__file__)
15
+
16
+
17
+ if __name__ == "__main__":
18
+ sys.exit(main())
@@ -0,0 +1,2 @@
1
+ [pytest]
2
+ testpaths = tests
@@ -0,0 +1,3 @@
1
+ -r requirements.txt
2
+ pytest
3
+ # manage.py needs flaskforge itself: pip install flaskforge (or: pip install -e /path/to/flaskforge)
@@ -0,0 +1,3 @@
1
+ Flask
2
+ python-dotenv
3
+ gunicorn
@@ -0,0 +1,23 @@
1
+ :root { --bg:#f6f7f9; --fg:#1d232b; --muted:#667085; --accent:#2563eb; --card:#fff; --border:#e4e7ec; }
2
+ @media (prefers-color-scheme: dark) {
3
+ :root { --bg:#12151a; --fg:#e8ebf0; --muted:#98a2b3; --accent:#6ea0ff; --card:#1b2028; --border:#2a313c; }
4
+ }
5
+ * { box-sizing: border-box; }
6
+ body { margin:0; background:var(--bg); color:var(--fg); font:16px/1.55 system-ui, sans-serif; }
7
+ a { color:var(--accent); }
8
+ .topbar { display:flex; justify-content:space-between; align-items:center; padding:.8rem 1.25rem;
9
+ background:var(--card); border-bottom:1px solid var(--border); }
10
+ .topbar nav a { margin-left:1rem; text-decoration:none; }
11
+ .brand { font-weight:700; text-decoration:none; color:var(--fg); }
12
+ .container { max-width:720px; margin:2rem auto; padding:0 1rem; }
13
+ .card { background:var(--card); border:1px solid var(--border); border-radius:10px; padding:1.5rem; }
14
+ .muted { color:var(--muted); }
15
+ code { background:var(--bg); padding:.1em .35em; border-radius:4px; }
16
+ .flash { padding:.7rem 1rem; border-radius:8px; margin-bottom:1rem; border:1px solid var(--border); background:var(--card); }
17
+ .flash-error, .flash-danger { border-color:#d92d20; }
18
+ .flash-success { border-color:#12b76a; }
19
+ .flash-warning { border-color:#f79009; }
20
+ form.stack { display:grid; gap:.8rem; }
21
+ input[type=email], input[type=password], input[type=text] {
22
+ width:100%; padding:.6rem .7rem; border:1px solid var(--border); border-radius:8px; background:var(--bg); color:var(--fg); }
23
+ button { padding:.6rem 1rem; border:0; border-radius:8px; background:var(--accent); color:#fff; font-weight:600; cursor:pointer; }
@@ -0,0 +1,35 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>{% block title %}[[ project ]]{% endblock %}</title>
7
+ <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
8
+ {% block head %}{% endblock %}
9
+ </head>
10
+ <body>
11
+ <header class="topbar">
12
+ <a class="brand" href="/">[[ project ]]</a>
13
+ <nav>
14
+ {% if current_user is defined %}
15
+ {% if current_user.is_authenticated %}
16
+ <a href="{{ url_for('accounts.profile') }}">{{ current_user.email }}</a>
17
+ {% else %}
18
+ <a href="{{ url_for('accounts.login') }}">Log in</a>
19
+ <a href="{{ url_for('accounts.register') }}">Register</a>
20
+ {% endif %}
21
+ {% endif %}
22
+ {% block nav %}{% endblock %}
23
+ </nav>
24
+ </header>
25
+
26
+ <main class="container">
27
+ {% with messages = get_flashed_messages(with_categories=true) %}
28
+ {% for category, message in messages %}
29
+ <div class="flash flash-{{ category }}">{{ message }}</div>
30
+ {% endfor %}
31
+ {% endwith %}
32
+ {% block content %}{% endblock %}
33
+ </main>
34
+ </body>
35
+ </html>
@@ -0,0 +1,9 @@
1
+ {% extends "base.html" %}
2
+ {% block title %}{{ error.code }} {{ error.name }}{% endblock %}
3
+ {% block content %}
4
+ <section class="card">
5
+ <h1>{{ error.code }} &mdash; {{ error.name }}</h1>
6
+ <p>{{ error.description }}</p>
7
+ <p><a href="/">Back to home</a></p>
8
+ </section>
9
+ {% endblock %}
@@ -0,0 +1 @@
1
+ # tests package
@@ -0,0 +1,21 @@
1
+ import pytest
2
+
3
+ from core import create_app, extensions
4
+
5
+
6
+ @pytest.fixture()
7
+ def app():
8
+ app = create_app("testing")
9
+ db = getattr(extensions, "db", None)
10
+ with app.app_context():
11
+ if db is not None:
12
+ db.create_all()
13
+ yield app
14
+ if db is not None:
15
+ db.session.remove()
16
+ db.drop_all()
17
+
18
+
19
+ @pytest.fixture()
20
+ def client(app):
21
+ return app.test_client()
@@ -0,0 +1,13 @@
1
+ def test_index(client):
2
+ assert client.get("/").status_code == 200
3
+
4
+
5
+ def test_health(client):
6
+ response = client.get("/health")
7
+ assert response.get_json() == {"status": "ok"}
8
+
9
+
10
+ def test_404_json_for_api(client):
11
+ response = client.get("/api/does-not-exist")
12
+ assert response.status_code == 404
13
+ assert response.get_json()["error"] == "Not Found"
@@ -0,0 +1,4 @@
1
+ """WSGI entry point: gunicorn wsgi:app"""
2
+ from core import create_app
3
+
4
+ app = create_app()
@@ -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
+ ```