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.
- flaskforge/__init__.py +3 -0
- flaskforge/__main__.py +4 -0
- flaskforge/cli.py +23 -0
- flaskforge/commands.py +70 -0
- flaskforge/generators.py +235 -0
- flaskforge/management.py +110 -0
- flaskforge/registry.py +311 -0
- flaskforge/scaffold.py +156 -0
- flaskforge/templates/app/__init__.py.tpl +1 -0
- flaskforge/templates/app/forms.py.tpl +7 -0
- flaskforge/templates/app/index.html.tpl +9 -0
- flaskforge/templates/app/models.py.tpl +17 -0
- flaskforge/templates/app/schemas.py.tpl +9 -0
- flaskforge/templates/app/test_app.py.tpl +20 -0
- flaskforge/templates/app/views.py.tpl +61 -0
- flaskforge/templates/ext/login/__init__.py.tpl +1 -0
- flaskforge/templates/ext/login/_csrf.html.tpl +2 -0
- flaskforge/templates/ext/login/commands.py.tpl +24 -0
- flaskforge/templates/ext/login/login.html.tpl +15 -0
- flaskforge/templates/ext/login/models.py.tpl +28 -0
- flaskforge/templates/ext/login/profile.html.tpl +13 -0
- flaskforge/templates/ext/login/register.html.tpl +15 -0
- flaskforge/templates/ext/login/test_accounts.py.tpl +31 -0
- flaskforge/templates/ext/login/views.py.tpl +70 -0
- flaskforge/templates/ext/sqlalchemy/mixins.py.tpl +15 -0
- flaskforge/templates/project/Dockerfile.tpl +14 -0
- flaskforge/templates/project/README.md.tpl +40 -0
- flaskforge/templates/project/apps/__init__.py.tpl +1 -0
- flaskforge/templates/project/apps/main/__init__.py.tpl +1 -0
- flaskforge/templates/project/apps/main/templates/main/index.html.tpl +15 -0
- flaskforge/templates/project/apps/main/views.py.tpl +13 -0
- flaskforge/templates/project/config/__init__.py.tpl +3 -0
- flaskforge/templates/project/config/settings.py.tpl +60 -0
- flaskforge/templates/project/core/__init__.py.tpl +53 -0
- flaskforge/templates/project/core/errors.py.tpl +15 -0
- flaskforge/templates/project/core/extensions.py.tpl +17 -0
- flaskforge/templates/project/dot_env.example.tpl +2 -0
- flaskforge/templates/project/dot_env.tpl +2 -0
- flaskforge/templates/project/dot_gitignore.tpl +16 -0
- flaskforge/templates/project/manage.py.tpl +18 -0
- flaskforge/templates/project/pytest.ini.tpl +2 -0
- flaskforge/templates/project/requirements-dev.txt.tpl +3 -0
- flaskforge/templates/project/requirements.txt.tpl +3 -0
- flaskforge/templates/project/static/css/style.css.tpl +23 -0
- flaskforge/templates/project/templates/base.html.tpl +35 -0
- flaskforge/templates/project/templates/errors/error.html.tpl +9 -0
- flaskforge/templates/project/tests/__init__.py.tpl +1 -0
- flaskforge/templates/project/tests/conftest.py.tpl +21 -0
- flaskforge/templates/project/tests/test_main.py.tpl +13 -0
- flaskforge/templates/project/wsgi.py.tpl +4 -0
- flaskforge_cli-0.1.0.dist-info/METADATA +77 -0
- flaskforge_cli-0.1.0.dist-info/RECORD +56 -0
- flaskforge_cli-0.1.0.dist-info/WHEEL +5 -0
- flaskforge_cli-0.1.0.dist-info/entry_points.txt +2 -0
- flaskforge_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
- flaskforge_cli-0.1.0.dist-info/top_level.txt +1 -0
flaskforge/registry.py
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
"""Catalogue of supported Flask extensions.
|
|
2
|
+
|
|
3
|
+
Every entry describes *what* has to be changed in a generated project when the
|
|
4
|
+
extension is added (`python manage.py add <key>`):
|
|
5
|
+
|
|
6
|
+
* ``imports`` / ``instances`` / ``init`` -> injected into ``core/extensions.py``
|
|
7
|
+
* ``settings`` / ``prod_settings`` -> injected into ``config/settings.py``
|
|
8
|
+
* ``env`` -> appended to ``.env`` and ``.env.example``
|
|
9
|
+
* ``files`` -> rendered templates (template, destination)
|
|
10
|
+
* ``apps`` -> appended to ``INSTALLED_APPS``
|
|
11
|
+
|
|
12
|
+
To support a new extension, add one ``Extension(...)`` entry below.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import difflib
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True)
|
|
22
|
+
class Extension:
|
|
23
|
+
key: str
|
|
24
|
+
title: str
|
|
25
|
+
description: str
|
|
26
|
+
packages: tuple = ()
|
|
27
|
+
imports: tuple = ()
|
|
28
|
+
instances: tuple = ()
|
|
29
|
+
init: tuple = ()
|
|
30
|
+
settings: tuple = ()
|
|
31
|
+
prod_settings: tuple = ()
|
|
32
|
+
env: tuple = () # ((KEY, value), ...)
|
|
33
|
+
requires: tuple = ()
|
|
34
|
+
files: tuple = () # ((template, destination), ...)
|
|
35
|
+
apps: tuple = ()
|
|
36
|
+
dev: bool = False # packages go to requirements-dev.txt
|
|
37
|
+
notes: str = ""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
_ALL = [
|
|
41
|
+
Extension(
|
|
42
|
+
key="sqlalchemy",
|
|
43
|
+
title="Flask-SQLAlchemy",
|
|
44
|
+
description="ORM + database session (db), TimestampMixin in core/mixins.py",
|
|
45
|
+
packages=("Flask-SQLAlchemy",),
|
|
46
|
+
imports=("from flask_sqlalchemy import SQLAlchemy",),
|
|
47
|
+
instances=("db = SQLAlchemy()",),
|
|
48
|
+
init=("db.init_app(app)",),
|
|
49
|
+
settings=(
|
|
50
|
+
'SQLALCHEMY_DATABASE_URI = os.getenv("DATABASE_URL", "sqlite:///app.db")',
|
|
51
|
+
"SQLALCHEMY_TRACK_MODIFICATIONS = False",
|
|
52
|
+
),
|
|
53
|
+
env=(("DATABASE_URL", "sqlite:///app.db"),),
|
|
54
|
+
files=(("ext/sqlalchemy/mixins.py.tpl", "core/mixins.py"),),
|
|
55
|
+
notes="Define models in apps/<name>/models.py - they are auto-imported.",
|
|
56
|
+
),
|
|
57
|
+
Extension(
|
|
58
|
+
key="migrate",
|
|
59
|
+
title="Flask-Migrate",
|
|
60
|
+
description="Alembic migrations: manage.py makemigrations / migrate",
|
|
61
|
+
packages=("Flask-Migrate",),
|
|
62
|
+
imports=("from flask_migrate import Migrate",),
|
|
63
|
+
instances=("migrate = Migrate()",),
|
|
64
|
+
init=("migrate.init_app(app, db)",),
|
|
65
|
+
requires=("sqlalchemy",),
|
|
66
|
+
notes="Use: python manage.py makemigrations -m 'msg' && python manage.py migrate",
|
|
67
|
+
),
|
|
68
|
+
Extension(
|
|
69
|
+
key="login",
|
|
70
|
+
title="Flask-Login",
|
|
71
|
+
description="Session auth: scaffolds apps/accounts (User, login, register, createsuperuser)",
|
|
72
|
+
packages=("Flask-Login",),
|
|
73
|
+
imports=("from flask_login import LoginManager",),
|
|
74
|
+
instances=("login_manager = LoginManager()",),
|
|
75
|
+
init=(
|
|
76
|
+
"login_manager.init_app(app)",
|
|
77
|
+
'login_manager.login_view = "accounts.login"',
|
|
78
|
+
'login_manager.login_message_category = "warning"',
|
|
79
|
+
),
|
|
80
|
+
requires=("sqlalchemy",),
|
|
81
|
+
files=(
|
|
82
|
+
("ext/login/__init__.py.tpl", "apps/accounts/__init__.py"),
|
|
83
|
+
("ext/login/models.py.tpl", "apps/accounts/models.py"),
|
|
84
|
+
("ext/login/views.py.tpl", "apps/accounts/views.py"),
|
|
85
|
+
("ext/login/commands.py.tpl", "apps/accounts/commands.py"),
|
|
86
|
+
("ext/login/_csrf.html.tpl", "apps/accounts/templates/accounts/_csrf.html"),
|
|
87
|
+
("ext/login/login.html.tpl", "apps/accounts/templates/accounts/login.html"),
|
|
88
|
+
("ext/login/register.html.tpl", "apps/accounts/templates/accounts/register.html"),
|
|
89
|
+
("ext/login/profile.html.tpl", "apps/accounts/templates/accounts/profile.html"),
|
|
90
|
+
("ext/login/test_accounts.py.tpl", "tests/test_accounts.py"),
|
|
91
|
+
),
|
|
92
|
+
apps=("apps.accounts",),
|
|
93
|
+
notes="Create an admin user: python manage.py createsuperuser",
|
|
94
|
+
),
|
|
95
|
+
Extension(
|
|
96
|
+
key="wtf",
|
|
97
|
+
title="Flask-WTF",
|
|
98
|
+
description="Forms + global CSRF protection (csrf). /api/* blueprints are exempt",
|
|
99
|
+
packages=("Flask-WTF",),
|
|
100
|
+
imports=("from flask_wtf.csrf import CSRFProtect",),
|
|
101
|
+
instances=("csrf = CSRFProtect()",),
|
|
102
|
+
init=("csrf.init_app(app)",),
|
|
103
|
+
notes='In HTML forms add: <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">',
|
|
104
|
+
),
|
|
105
|
+
Extension(
|
|
106
|
+
key="mail",
|
|
107
|
+
title="Flask-Mail",
|
|
108
|
+
description="Send e-mail (mail)",
|
|
109
|
+
packages=("Flask-Mail",),
|
|
110
|
+
imports=("from flask_mail import Mail",),
|
|
111
|
+
instances=("mail = Mail()",),
|
|
112
|
+
init=("mail.init_app(app)",),
|
|
113
|
+
settings=(
|
|
114
|
+
'MAIL_SERVER = os.getenv("MAIL_SERVER", "localhost")',
|
|
115
|
+
'MAIL_PORT = int(os.getenv("MAIL_PORT", "25"))',
|
|
116
|
+
'MAIL_USE_TLS = os.getenv("MAIL_USE_TLS", "0") == "1"',
|
|
117
|
+
'MAIL_USERNAME = os.getenv("MAIL_USERNAME")',
|
|
118
|
+
'MAIL_PASSWORD = os.getenv("MAIL_PASSWORD")',
|
|
119
|
+
'MAIL_DEFAULT_SENDER = os.getenv("MAIL_DEFAULT_SENDER", "noreply@example.com")',
|
|
120
|
+
),
|
|
121
|
+
env=(
|
|
122
|
+
("MAIL_SERVER", "localhost"),
|
|
123
|
+
("MAIL_PORT", "25"),
|
|
124
|
+
("MAIL_USE_TLS", "0"),
|
|
125
|
+
("MAIL_USERNAME", ""),
|
|
126
|
+
("MAIL_PASSWORD", ""),
|
|
127
|
+
("MAIL_DEFAULT_SENDER", "noreply@example.com"),
|
|
128
|
+
),
|
|
129
|
+
),
|
|
130
|
+
Extension(
|
|
131
|
+
key="cors",
|
|
132
|
+
title="Flask-CORS",
|
|
133
|
+
description="Cross-origin requests for /api/* (CORS_ORIGINS)",
|
|
134
|
+
packages=("Flask-Cors",),
|
|
135
|
+
imports=("from flask_cors import CORS",),
|
|
136
|
+
instances=("cors = CORS()",),
|
|
137
|
+
init=('cors.init_app(app, resources={r"/api/*": {"origins": app.config["CORS_ORIGINS"]}})',),
|
|
138
|
+
settings=('CORS_ORIGINS = os.getenv("CORS_ORIGINS", "*").split(",")',),
|
|
139
|
+
env=(("CORS_ORIGINS", "*"),),
|
|
140
|
+
),
|
|
141
|
+
Extension(
|
|
142
|
+
key="jwt",
|
|
143
|
+
title="Flask-JWT-Extended",
|
|
144
|
+
description="JWT token authentication for APIs (jwt)",
|
|
145
|
+
packages=("Flask-JWT-Extended",),
|
|
146
|
+
imports=("from flask_jwt_extended import JWTManager",),
|
|
147
|
+
instances=("jwt = JWTManager()",),
|
|
148
|
+
init=("jwt.init_app(app)",),
|
|
149
|
+
settings=(
|
|
150
|
+
'JWT_SECRET_KEY = os.getenv("JWT_SECRET_KEY", SECRET_KEY)',
|
|
151
|
+
'JWT_ACCESS_TOKEN_EXPIRES = int(os.getenv("JWT_ACCESS_TOKEN_EXPIRES", "3600"))',
|
|
152
|
+
),
|
|
153
|
+
env=(("JWT_ACCESS_TOKEN_EXPIRES", "3600"),),
|
|
154
|
+
),
|
|
155
|
+
Extension(
|
|
156
|
+
key="cache",
|
|
157
|
+
title="Flask-Caching",
|
|
158
|
+
description="Response / function caching (cache)",
|
|
159
|
+
packages=("Flask-Caching",),
|
|
160
|
+
imports=("from flask_caching import Cache",),
|
|
161
|
+
instances=("cache = Cache()",),
|
|
162
|
+
init=("cache.init_app(app)",),
|
|
163
|
+
settings=(
|
|
164
|
+
'CACHE_TYPE = os.getenv("CACHE_TYPE", "SimpleCache")',
|
|
165
|
+
'CACHE_DEFAULT_TIMEOUT = int(os.getenv("CACHE_DEFAULT_TIMEOUT", "300"))',
|
|
166
|
+
),
|
|
167
|
+
env=(("CACHE_TYPE", "SimpleCache"),),
|
|
168
|
+
),
|
|
169
|
+
Extension(
|
|
170
|
+
key="limiter",
|
|
171
|
+
title="Flask-Limiter",
|
|
172
|
+
description="Rate limiting (limiter)",
|
|
173
|
+
packages=("Flask-Limiter",),
|
|
174
|
+
imports=(
|
|
175
|
+
"from flask_limiter import Limiter",
|
|
176
|
+
"from flask_limiter.util import get_remote_address",
|
|
177
|
+
),
|
|
178
|
+
instances=("limiter = Limiter(key_func=get_remote_address)",),
|
|
179
|
+
init=("limiter.init_app(app)",),
|
|
180
|
+
settings=(
|
|
181
|
+
'RATELIMIT_DEFAULT = os.getenv("RATELIMIT_DEFAULT", "200 per day;50 per hour")',
|
|
182
|
+
'RATELIMIT_STORAGE_URI = os.getenv("RATELIMIT_STORAGE_URI", "memory://")',
|
|
183
|
+
),
|
|
184
|
+
env=(("RATELIMIT_STORAGE_URI", "memory://"),),
|
|
185
|
+
),
|
|
186
|
+
Extension(
|
|
187
|
+
key="babel",
|
|
188
|
+
title="Flask-Babel",
|
|
189
|
+
description="i18n / l10n (babel)",
|
|
190
|
+
packages=("Flask-Babel",),
|
|
191
|
+
imports=("from flask_babel import Babel",),
|
|
192
|
+
instances=("babel = Babel()",),
|
|
193
|
+
init=("babel.init_app(app)",),
|
|
194
|
+
settings=(
|
|
195
|
+
'BABEL_DEFAULT_LOCALE = os.getenv("BABEL_DEFAULT_LOCALE", "en")',
|
|
196
|
+
'BABEL_DEFAULT_TIMEZONE = "UTC"',
|
|
197
|
+
),
|
|
198
|
+
env=(("BABEL_DEFAULT_LOCALE", "en"),),
|
|
199
|
+
),
|
|
200
|
+
Extension(
|
|
201
|
+
key="marshmallow",
|
|
202
|
+
title="Flask-Marshmallow",
|
|
203
|
+
description="Serialization / validation schemas (ma) + marshmallow-sqlalchemy",
|
|
204
|
+
packages=("Flask-Marshmallow", "marshmallow-sqlalchemy"),
|
|
205
|
+
imports=("from flask_marshmallow import Marshmallow",),
|
|
206
|
+
instances=("ma = Marshmallow()",),
|
|
207
|
+
init=("ma.init_app(app)",),
|
|
208
|
+
requires=("sqlalchemy",),
|
|
209
|
+
),
|
|
210
|
+
Extension(
|
|
211
|
+
key="socketio",
|
|
212
|
+
title="Flask-SocketIO",
|
|
213
|
+
description="WebSockets (socketio). Put handlers in apps/<name>/events.py",
|
|
214
|
+
packages=("Flask-SocketIO",),
|
|
215
|
+
imports=("from flask_socketio import SocketIO",),
|
|
216
|
+
instances=("socketio = SocketIO()",),
|
|
217
|
+
init=('socketio.init_app(app, cors_allowed_origins=app.config["SOCKETIO_CORS_ORIGINS"])',),
|
|
218
|
+
settings=('SOCKETIO_CORS_ORIGINS = os.getenv("SOCKETIO_CORS_ORIGINS", "*")',),
|
|
219
|
+
env=(("SOCKETIO_CORS_ORIGINS", "*"),),
|
|
220
|
+
notes="manage.py runserver automatically uses socketio.run().",
|
|
221
|
+
),
|
|
222
|
+
Extension(
|
|
223
|
+
key="admin",
|
|
224
|
+
title="Flask-Admin",
|
|
225
|
+
description="Auto-generated admin panel at /admin (admin)",
|
|
226
|
+
packages=("Flask-Admin",),
|
|
227
|
+
imports=("from flask_admin import Admin",),
|
|
228
|
+
instances=('admin = Admin(name="Admin")',),
|
|
229
|
+
init=("admin.init_app(app)",),
|
|
230
|
+
notes="Register model views: admin.add_view(ModelView(Model, db.session))",
|
|
231
|
+
),
|
|
232
|
+
Extension(
|
|
233
|
+
key="debugtoolbar",
|
|
234
|
+
title="Flask-DebugToolbar",
|
|
235
|
+
description="Debug toolbar, active only when DEBUG=True (dev dependency)",
|
|
236
|
+
packages=("Flask-DebugToolbar",),
|
|
237
|
+
imports=(
|
|
238
|
+
"try:",
|
|
239
|
+
" from flask_debugtoolbar import DebugToolbarExtension",
|
|
240
|
+
"except ImportError: # dev-only dependency",
|
|
241
|
+
" DebugToolbarExtension = None",
|
|
242
|
+
),
|
|
243
|
+
instances=("toolbar = DebugToolbarExtension() if DebugToolbarExtension else None",),
|
|
244
|
+
init=("if toolbar is not None and app.debug:", " toolbar.init_app(app)"),
|
|
245
|
+
dev=True,
|
|
246
|
+
),
|
|
247
|
+
Extension(
|
|
248
|
+
key="talisman",
|
|
249
|
+
title="Flask-Talisman",
|
|
250
|
+
description="Security headers + HTTPS redirect (HTTPS forced in production)",
|
|
251
|
+
packages=("Flask-Talisman",),
|
|
252
|
+
imports=("from flask_talisman import Talisman",),
|
|
253
|
+
instances=("talisman = Talisman()",),
|
|
254
|
+
init=(
|
|
255
|
+
"talisman.init_app(",
|
|
256
|
+
" app,",
|
|
257
|
+
' force_https=app.config["FORCE_HTTPS"],',
|
|
258
|
+
" content_security_policy=None,",
|
|
259
|
+
")",
|
|
260
|
+
),
|
|
261
|
+
settings=("FORCE_HTTPS = False",),
|
|
262
|
+
prod_settings=('FORCE_HTTPS = os.getenv("FORCE_HTTPS", "1") == "1"',),
|
|
263
|
+
notes="Tune the Content-Security-Policy in core/extensions.py before going live.",
|
|
264
|
+
),
|
|
265
|
+
Extension(
|
|
266
|
+
key="compress",
|
|
267
|
+
title="Flask-Compress",
|
|
268
|
+
description="gzip / brotli response compression (compress)",
|
|
269
|
+
packages=("Flask-Compress",),
|
|
270
|
+
imports=("from flask_compress import Compress",),
|
|
271
|
+
instances=("compress = Compress()",),
|
|
272
|
+
init=("compress.init_app(app)",),
|
|
273
|
+
),
|
|
274
|
+
]
|
|
275
|
+
|
|
276
|
+
EXTENSIONS = {e.key: e for e in _ALL}
|
|
277
|
+
|
|
278
|
+
PRESETS = {
|
|
279
|
+
"minimal": [],
|
|
280
|
+
"web": ["sqlalchemy", "migrate", "login", "wtf"],
|
|
281
|
+
"api": ["sqlalchemy", "migrate", "marshmallow", "cors", "jwt", "limiter"],
|
|
282
|
+
"full": [
|
|
283
|
+
"sqlalchemy", "migrate", "login", "wtf", "mail", "cors", "jwt", "cache",
|
|
284
|
+
"limiter", "babel", "marshmallow", "admin", "compress", "debugtoolbar",
|
|
285
|
+
],
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
_ALIASES = {
|
|
289
|
+
"sql": "sqlalchemy", "db": "sqlalchemy", "database": "sqlalchemy", "orm": "sqlalchemy",
|
|
290
|
+
"migrations": "migrate", "alembic": "migrate",
|
|
291
|
+
"auth": "login", "csrf": "wtf", "forms": "wtf", "wtforms": "wtf", "email": "mail",
|
|
292
|
+
"jwt-extended": "jwt", "caching": "cache", "ratelimit": "limiter",
|
|
293
|
+
"i18n": "babel", "ma": "marshmallow", "ws": "socketio", "websocket": "socketio",
|
|
294
|
+
"gzip": "compress", "toolbar": "debugtoolbar", "https": "talisman",
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def resolve_key(name: str) -> str:
|
|
299
|
+
"""Map user input ('Flask-SQLAlchemy', 'flask_login', 'db') to a registry key."""
|
|
300
|
+
n = name.strip().lower().replace("_", "-")
|
|
301
|
+
if n.startswith("flask-"):
|
|
302
|
+
n = n[len("flask-"):]
|
|
303
|
+
n = _ALIASES.get(n, n)
|
|
304
|
+
if n in EXTENSIONS:
|
|
305
|
+
return n
|
|
306
|
+
hint = difflib.get_close_matches(n, list(EXTENSIONS) + list(_ALIASES), n=1)
|
|
307
|
+
msg = f"Unknown extension '{name}'."
|
|
308
|
+
if hint:
|
|
309
|
+
msg += f" Did you mean '{hint[0]}'?"
|
|
310
|
+
msg += " Run `flaskforge extensions` to see the list."
|
|
311
|
+
raise KeyError(msg)
|
flaskforge/scaffold.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""Low-level helpers: template rendering, safe file writing, marker injection."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Iterable, Sequence
|
|
10
|
+
|
|
11
|
+
import click
|
|
12
|
+
from jinja2 import Environment, FileSystemLoader, StrictUndefined
|
|
13
|
+
|
|
14
|
+
TEMPLATES_DIR = Path(__file__).parent / "templates"
|
|
15
|
+
MANIFEST = ".flaskforge.json"
|
|
16
|
+
|
|
17
|
+
# Custom delimiters so generated HTML (which uses {{ }} / {% %}) passes through untouched.
|
|
18
|
+
_env = Environment(
|
|
19
|
+
loader=FileSystemLoader(str(TEMPLATES_DIR)),
|
|
20
|
+
block_start_string="[%",
|
|
21
|
+
block_end_string="%]",
|
|
22
|
+
variable_start_string="[[",
|
|
23
|
+
variable_end_string="]]",
|
|
24
|
+
comment_start_string="[#",
|
|
25
|
+
comment_end_string="#]",
|
|
26
|
+
keep_trailing_newline=True,
|
|
27
|
+
trim_blocks=True,
|
|
28
|
+
lstrip_blocks=True,
|
|
29
|
+
undefined=StrictUndefined,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def render(template: str, ctx: dict) -> str:
|
|
34
|
+
return _env.get_template(template).render(**ctx)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
# --------------------------------------------------------------------------- project
|
|
38
|
+
@dataclass
|
|
39
|
+
class Project:
|
|
40
|
+
root: Path
|
|
41
|
+
data: dict
|
|
42
|
+
|
|
43
|
+
@classmethod
|
|
44
|
+
def find(cls, start: Path | None = None) -> "Project":
|
|
45
|
+
cur = (start or Path.cwd()).resolve()
|
|
46
|
+
for directory in (cur, *cur.parents):
|
|
47
|
+
manifest = directory / MANIFEST
|
|
48
|
+
if manifest.is_file():
|
|
49
|
+
return cls(directory, json.loads(manifest.read_text(encoding="utf-8")))
|
|
50
|
+
raise click.ClickException(
|
|
51
|
+
f"Not inside a flaskforge project ({MANIFEST} not found). "
|
|
52
|
+
"Run `flaskforge startproject <name>` first."
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def name(self) -> str:
|
|
57
|
+
return self.data["project"]
|
|
58
|
+
|
|
59
|
+
@property
|
|
60
|
+
def slug(self) -> str:
|
|
61
|
+
return re.sub(r"[^a-z0-9_]+", "_", self.name.lower()).strip("_")
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def extensions(self) -> list:
|
|
65
|
+
return self.data.setdefault("extensions", [])
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def apps(self) -> list:
|
|
69
|
+
return self.data.setdefault("apps", [])
|
|
70
|
+
|
|
71
|
+
def save(self) -> None:
|
|
72
|
+
(self.root / MANIFEST).write_text(
|
|
73
|
+
json.dumps(self.data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
def rel(self, path: Path) -> str:
|
|
77
|
+
try:
|
|
78
|
+
return path.resolve().relative_to(self.root).as_posix()
|
|
79
|
+
except ValueError:
|
|
80
|
+
return str(path)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
# --------------------------------------------------------------------------- files
|
|
84
|
+
def write_file(target: Path, content: str, *, root: Path, force: bool = False) -> str:
|
|
85
|
+
"""Write a file, never clobbering existing work unless ``force`` is given."""
|
|
86
|
+
rel = target.resolve().relative_to(root.resolve()).as_posix()
|
|
87
|
+
existed = target.exists()
|
|
88
|
+
if existed and not force:
|
|
89
|
+
click.secho(f" skip {rel} (already exists, use --force to overwrite)", fg="yellow")
|
|
90
|
+
return "skipped"
|
|
91
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
92
|
+
target.write_text(content, encoding="utf-8")
|
|
93
|
+
click.secho(f" {'update' if existed else 'create'} {rel}", fg="green")
|
|
94
|
+
return "updated" if existed else "created"
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def inject(path: Path, marker: str, lines: Sequence[str]) -> bool:
|
|
98
|
+
"""Insert ``lines`` just above the ``marker`` comment, keeping its indentation.
|
|
99
|
+
|
|
100
|
+
Idempotent: nothing happens if the exact block is already in the file.
|
|
101
|
+
"""
|
|
102
|
+
lines = [l for l in lines]
|
|
103
|
+
if not lines:
|
|
104
|
+
return False
|
|
105
|
+
text = path.read_text(encoding="utf-8")
|
|
106
|
+
src = text.splitlines()
|
|
107
|
+
for idx, line in enumerate(src):
|
|
108
|
+
if line.strip() == marker:
|
|
109
|
+
indent = line[: len(line) - len(line.lstrip())]
|
|
110
|
+
break
|
|
111
|
+
else:
|
|
112
|
+
raise click.ClickException(
|
|
113
|
+
f"Marker '{marker}' not found in {path.name}. Re-add the marker comment "
|
|
114
|
+
"(it tells flaskforge where to insert code) and run the command again."
|
|
115
|
+
)
|
|
116
|
+
block = [(indent + l) if l else "" for l in lines]
|
|
117
|
+
if "\n".join(block) in text:
|
|
118
|
+
return False
|
|
119
|
+
src[idx:idx] = block
|
|
120
|
+
path.write_text("\n".join(src) + "\n", encoding="utf-8")
|
|
121
|
+
return True
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def set_env(path: Path, pairs: Iterable[tuple]) -> None:
|
|
125
|
+
"""Append KEY=value lines that are not defined yet."""
|
|
126
|
+
existing = path.read_text(encoding="utf-8") if path.exists() else ""
|
|
127
|
+
keys = {
|
|
128
|
+
l.split("=", 1)[0].strip()
|
|
129
|
+
for l in existing.splitlines()
|
|
130
|
+
if "=" in l and not l.lstrip().startswith("#")
|
|
131
|
+
}
|
|
132
|
+
new = [f"{k}={v}" for k, v in pairs if k not in keys]
|
|
133
|
+
if not new:
|
|
134
|
+
return
|
|
135
|
+
if existing and not existing.endswith("\n"):
|
|
136
|
+
existing += "\n"
|
|
137
|
+
path.write_text(existing + "\n".join(new) + "\n", encoding="utf-8")
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _norm(pkg: str) -> str:
|
|
141
|
+
return re.split(r"[<>=!~\[; ]", pkg.strip(), maxsplit=1)[0].lower().replace("_", "-")
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def add_requirements(path: Path, packages: Iterable[str]) -> None:
|
|
145
|
+
text = path.read_text(encoding="utf-8") if path.exists() else ""
|
|
146
|
+
have = {
|
|
147
|
+
_norm(l)
|
|
148
|
+
for l in text.splitlines()
|
|
149
|
+
if l.strip() and not l.lstrip().startswith(("#", "-"))
|
|
150
|
+
}
|
|
151
|
+
new = [p for p in packages if _norm(p) not in have]
|
|
152
|
+
if not new:
|
|
153
|
+
return
|
|
154
|
+
if text and not text.endswith("\n"):
|
|
155
|
+
text += "\n"
|
|
156
|
+
path.write_text(text + "\n".join(new) + "\n", encoding="utf-8")
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""[[ app_name ]] app."""
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
{% extends "base.html" %}
|
|
2
|
+
{% block title %}[[ class_name ]]{% endblock %}
|
|
3
|
+
|
|
4
|
+
{% block content %}
|
|
5
|
+
<section class="card">
|
|
6
|
+
<h1>[[ class_name ]]</h1>
|
|
7
|
+
<p>The <code>[[ app_name ]]</code> app works. Edit <code>apps/[[ app_name ]]/templates/[[ app_name ]]/index.html</code>.</p>
|
|
8
|
+
</section>
|
|
9
|
+
{% endblock %}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
[% if "sqlalchemy" in ext %]
|
|
2
|
+
from core.extensions import db
|
|
3
|
+
from core.mixins import TimestampMixin
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class [[ class_name ]](TimestampMixin, db.Model):
|
|
7
|
+
id = db.Column(db.Integer, primary_key=True)
|
|
8
|
+
name = db.Column(db.String(120), nullable=False)
|
|
9
|
+
|
|
10
|
+
def __repr__(self):
|
|
11
|
+
return f"<[[ class_name ]] {self.id} {self.name!r}>"
|
|
12
|
+
[% else %]
|
|
13
|
+
"""Models of the [[ app_name ]] app.
|
|
14
|
+
|
|
15
|
+
Run `python manage.py add sqlalchemy` to enable the ORM, then define models here.
|
|
16
|
+
"""
|
|
17
|
+
[% endif %]
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
[% if api %]
|
|
2
|
+
def test_[[ app_name ]]_list(client):
|
|
3
|
+
response = client.get("/api/[[ app_name ]]/")
|
|
4
|
+
assert response.status_code == 200
|
|
5
|
+
assert response.get_json() == []
|
|
6
|
+
[% if "sqlalchemy" in ext %]
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def test_[[ app_name ]]_create_and_get(client):
|
|
10
|
+
created = client.post("/api/[[ app_name ]]/", json={"name": "first"})
|
|
11
|
+
assert created.status_code == 201
|
|
12
|
+
item_id = created.get_json()["id"]
|
|
13
|
+
assert client.get(f"/api/[[ app_name ]]/{item_id}").get_json()["name"] == "first"
|
|
14
|
+
assert client.delete(f"/api/[[ app_name ]]/{item_id}").status_code == 204
|
|
15
|
+
assert client.get(f"/api/[[ app_name ]]/{item_id}").status_code == 404
|
|
16
|
+
[% endif %]
|
|
17
|
+
[% else %]
|
|
18
|
+
def test_[[ app_name ]]_index(client):
|
|
19
|
+
assert client.get("/[[ app_name ]]/").status_code == 200
|
|
20
|
+
[% endif %]
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
[% if api %]
|
|
2
|
+
from flask import Blueprint, jsonify, request
|
|
3
|
+
[% if "sqlalchemy" in ext %]
|
|
4
|
+
from core.extensions import db
|
|
5
|
+
|
|
6
|
+
from .models import [[ class_name ]]
|
|
7
|
+
[% endif %]
|
|
8
|
+
|
|
9
|
+
bp = Blueprint("[[ app_name ]]", __name__, url_prefix="/api/[[ app_name ]]")
|
|
10
|
+
[% if "sqlalchemy" in ext %]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _serialize(obj):
|
|
14
|
+
return {"id": obj.id, "name": obj.name}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@bp.get("/")
|
|
18
|
+
def list_items():
|
|
19
|
+
items = db.session.scalars(db.select([[ class_name ]]).order_by([[ class_name ]].id)).all()
|
|
20
|
+
return jsonify([_serialize(i) for i in items])
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@bp.post("/")
|
|
24
|
+
def create_item():
|
|
25
|
+
payload = request.get_json(silent=True) or {}
|
|
26
|
+
name = (payload.get("name") or "").strip()
|
|
27
|
+
if not name:
|
|
28
|
+
return jsonify(error="Bad Request", message="'name' is required"), 400
|
|
29
|
+
obj = [[ class_name ]](name=name)
|
|
30
|
+
db.session.add(obj)
|
|
31
|
+
db.session.commit()
|
|
32
|
+
return jsonify(_serialize(obj)), 201
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@bp.get("/<int:item_id>")
|
|
36
|
+
def get_item(item_id):
|
|
37
|
+
return jsonify(_serialize(db.get_or_404([[ class_name ]], item_id)))
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@bp.delete("/<int:item_id>")
|
|
41
|
+
def delete_item(item_id):
|
|
42
|
+
db.session.delete(db.get_or_404([[ class_name ]], item_id))
|
|
43
|
+
db.session.commit()
|
|
44
|
+
return "", 204
|
|
45
|
+
[% else %]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@bp.get("/")
|
|
49
|
+
def list_items():
|
|
50
|
+
return jsonify([])
|
|
51
|
+
[% endif %]
|
|
52
|
+
[% else %]
|
|
53
|
+
from flask import Blueprint, render_template
|
|
54
|
+
|
|
55
|
+
bp = Blueprint("[[ app_name ]]", __name__, url_prefix="/[[ app_name ]]", template_folder="templates")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@bp.get("/")
|
|
59
|
+
def index():
|
|
60
|
+
return render_template("[[ app_name ]]/index.html")
|
|
61
|
+
[% endif %]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Accounts: registration, login/logout, profile. Generated by `manage.py add login`."""
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import click
|
|
2
|
+
from flask.cli import with_appcontext
|
|
3
|
+
|
|
4
|
+
from core.extensions import db
|
|
5
|
+
|
|
6
|
+
from .models import User
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@click.command("createsuperuser", help="Create an administrator account.")
|
|
10
|
+
@click.option("--email", prompt=True)
|
|
11
|
+
@click.password_option()
|
|
12
|
+
@with_appcontext
|
|
13
|
+
def createsuperuser(email, password):
|
|
14
|
+
email = email.strip().lower()
|
|
15
|
+
if db.session.execute(db.select(User).filter_by(email=email)).scalar_one_or_none():
|
|
16
|
+
raise click.ClickException(f"User {email} already exists.")
|
|
17
|
+
user = User(email=email, is_admin=True)
|
|
18
|
+
user.set_password(password)
|
|
19
|
+
db.session.add(user)
|
|
20
|
+
db.session.commit()
|
|
21
|
+
click.secho(f"Superuser {email} created.", fg="green")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
commands = [createsuperuser]
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{% extends "base.html" %}
|
|
2
|
+
{% block title %}Log in{% endblock %}
|
|
3
|
+
|
|
4
|
+
{% block content %}
|
|
5
|
+
<section class="card">
|
|
6
|
+
<h1>Log in</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" required>
|
|
11
|
+
<button type="submit">Log in</button>
|
|
12
|
+
</form>
|
|
13
|
+
<p class="muted">No account? <a href="{{ url_for('accounts.register') }}">Register</a></p>
|
|
14
|
+
</section>
|
|
15
|
+
{% endblock %}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from flask_login import UserMixin
|
|
2
|
+
from werkzeug.security import check_password_hash, generate_password_hash
|
|
3
|
+
|
|
4
|
+
from core.extensions import db, login_manager
|
|
5
|
+
from core.mixins import TimestampMixin
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class User(UserMixin, TimestampMixin, db.Model):
|
|
9
|
+
__tablename__ = "users"
|
|
10
|
+
|
|
11
|
+
id = db.Column(db.Integer, primary_key=True)
|
|
12
|
+
email = db.Column(db.String(255), unique=True, nullable=False, index=True)
|
|
13
|
+
password_hash = db.Column(db.String(255), nullable=False)
|
|
14
|
+
is_admin = db.Column(db.Boolean, default=False, nullable=False)
|
|
15
|
+
|
|
16
|
+
def set_password(self, password: str) -> None:
|
|
17
|
+
self.password_hash = generate_password_hash(password)
|
|
18
|
+
|
|
19
|
+
def check_password(self, password: str) -> bool:
|
|
20
|
+
return check_password_hash(self.password_hash, password)
|
|
21
|
+
|
|
22
|
+
def __repr__(self):
|
|
23
|
+
return f"<User {self.email}>"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@login_manager.user_loader
|
|
27
|
+
def load_user(user_id):
|
|
28
|
+
return db.session.get(User, int(user_id))
|