0
# CLI Tools and Commands
1
2
Command-line interface for user management, database operations, security management, and application maintenance. Flask-AppBuilder provides comprehensive CLI tools through Flask's CLI system for managing applications, users, roles, and database operations.
3
4
## Capabilities
5
6
### Flask CLI Commands
7
8
Complete set of Flask CLI commands available through `flask fab <command>` for managing Flask-AppBuilder applications.
9
10
```python { .api }
11
# All Flask-AppBuilder CLI commands are accessed via:
12
# flask fab <command> [options]
13
14
# User Management Commands
15
flask fab create-admin
16
"""
17
Create application administrator user interactively.
18
19
Options:
20
--username: Admin username (interactive if not provided)
21
--firstname: Admin first name
22
--lastname: Admin last name
23
--email: Admin email address
24
--password: Admin password (secure prompt if not provided)
25
26
Usage:
27
flask fab create-admin
28
flask fab create-admin --username admin --email admin@company.com
29
"""
30
31
flask fab create-user
32
"""
33
Create regular application user interactively.
34
35
Options:
36
--username: Username
37
--firstname: First name
38
--lastname: Last name
39
--email: Email address
40
--password: Password
41
--role: User role name
42
43
Usage:
44
flask fab create-user
45
flask fab create-user --username jdoe --role Public
46
"""
47
48
flask fab reset-password
49
"""
50
Reset user password interactively.
51
52
Options:
53
--username: Username to reset password for
54
55
Usage:
56
flask fab reset-password
57
flask fab reset-password --username jdoe
58
"""
59
60
flask fab list-users
61
"""
62
List all application users with details.
63
64
Options:
65
--verbose: Show detailed user information
66
67
Usage:
68
flask fab list-users
69
flask fab list-users --verbose
70
"""
71
72
# Database Commands
73
flask fab create-db
74
"""
75
Create all database tables and initial data.
76
Equivalent to db.create_all() with Flask-AppBuilder setup.
77
78
Usage:
79
flask fab create-db
80
"""
81
82
# Security Management Commands
83
flask fab create-permissions
84
"""
85
Create all permissions for registered views and menus.
86
Scans all registered views and creates corresponding permissions.
87
88
Usage:
89
flask fab create-permissions
90
"""
91
92
flask fab security-cleanup
93
"""
94
Remove unused permissions and roles from database.
95
Cleans up orphaned permissions that no longer have associated views.
96
97
Options:
98
--dry-run: Show what would be cleaned up without making changes
99
100
Usage:
101
flask fab security-cleanup
102
flask fab security-cleanup --dry-run
103
"""
104
105
flask fab security-converge
106
"""
107
Migrate permissions to new naming conventions.
108
Updates permission names to match current view structure.
109
110
Options:
111
--dry-run: Show migration plan without executing
112
113
Usage:
114
flask fab security-converge
115
flask fab security-converge --dry-run
116
"""
117
118
# Role Management Commands
119
flask fab export-roles
120
"""
121
Export roles and permissions to JSON file.
122
123
Options:
124
--filename: Output filename (default: roles_export.json)
125
126
Usage:
127
flask fab export-roles
128
flask fab export-roles --filename my_roles.json
129
"""
130
131
flask fab import-roles
132
"""
133
Import roles and permissions from JSON file.
134
135
Options:
136
--filename: Input filename (default: roles_export.json)
137
138
Usage:
139
flask fab import-roles
140
flask fab import-roles --filename my_roles.json
141
"""
142
143
# Application Information
144
flask fab version
145
"""
146
Show Flask-AppBuilder version information.
147
148
Usage:
149
flask fab version
150
"""
151
152
flask fab list-views
153
"""
154
List all registered views with details.
155
156
Options:
157
--verbose: Show detailed view information including permissions
158
159
Usage:
160
flask fab list-views
161
flask fab list-views --verbose
162
"""
163
164
# Development Commands
165
flask fab create-app
166
"""
167
Create new Flask-AppBuilder application skeleton.
168
169
Options:
170
--name: Application name
171
--engine: Database engine (SQLAlchemy, MongoEngine)
172
173
Usage:
174
flask fab create-app --name MyApp
175
flask fab create-app --name MyApp --engine SQLAlchemy
176
"""
177
178
flask fab create-addon
179
"""
180
Create Flask-AppBuilder addon skeleton.
181
182
Options:
183
--name: Addon name
184
185
Usage:
186
flask fab create-addon --name MyAddon
187
"""
188
189
# Static Files Management
190
flask fab collect-static
191
"""
192
Copy static files from Flask-AppBuilder to application static folder.
193
194
Options:
195
--target: Target directory for static files
196
197
Usage:
198
flask fab collect-static
199
flask fab collect-static --target /path/to/static
200
"""
201
202
# Internationalization Commands
203
flask fab babel-extract
204
"""
205
Extract translatable strings for internationalization.
206
207
Options:
208
--target: Target directory for translation files
209
--config: Babel configuration file
210
211
Usage:
212
flask fab babel-extract
213
flask fab babel-extract --target translations --config babel.cfg
214
"""
215
216
flask fab babel-compile
217
"""
218
Compile translation files for production use.
219
220
Options:
221
--target: Translation files directory
222
223
Usage:
224
flask fab babel-compile
225
flask fab babel-compile --target translations
226
"""
227
```
228
229
### Command Usage Examples
230
231
Practical examples of using Flask-AppBuilder CLI commands in various scenarios and workflows.
232
233
```python { .api }
234
# Initial application setup workflow
235
"""
236
1. Create database tables
237
2. Create admin user
238
3. Create initial permissions
239
"""
240
241
# Step 1: Create database
242
flask fab create-db
243
244
# Step 2: Create admin user
245
flask fab create-admin --username admin --email admin@company.com
246
247
# Step 3: Create permissions for all views
248
flask fab create-permissions
249
250
# User management workflow
251
"""
252
Adding new users and managing existing ones
253
"""
254
255
# Create new user with specific role
256
flask fab create-user \
257
--username employee1 \
258
--firstname John \
259
--lastname Doe \
260
--email john.doe@company.com \
261
--role Employee
262
263
# List all users to verify
264
flask fab list-users --verbose
265
266
# Reset password for user
267
flask fab reset-password --username employee1
268
269
# Security maintenance workflow
270
"""
271
Regular security cleanup and updates
272
"""
273
274
# Check what permissions would be cleaned up
275
flask fab security-cleanup --dry-run
276
277
# Clean up unused permissions
278
flask fab security-cleanup
279
280
# Update permission names to new format
281
flask fab security-converge --dry-run
282
flask fab security-converge
283
284
# Export current roles for backup
285
flask fab export-roles --filename backup_roles.json
286
287
# Role management workflow
288
"""
289
Backing up and restoring role configurations
290
"""
291
292
# Export roles from production
293
flask fab export-roles --filename prod_roles.json
294
295
# Import roles to development environment
296
flask fab import-roles --filename prod_roles.json
297
298
# Verify roles were imported correctly
299
flask fab list-users --verbose
300
301
# Development workflow
302
"""
303
Setting up new development environment
304
"""
305
306
# Create new application skeleton
307
flask fab create-app --name MyNewApp --engine SQLAlchemy
308
309
# Create addon for custom functionality
310
flask fab create-addon --name MyCustomAddon
311
312
# Collect static files for deployment
313
flask fab collect-static --target /var/www/myapp/static
314
315
# Internationalization workflow
316
"""
317
Managing translations for multi-language support
318
"""
319
320
# Extract translatable strings from templates and code
321
flask fab babel-extract --target translations --config babel.cfg
322
323
# Compile translation files for production
324
flask fab babel-compile --target translations
325
326
# Application information and debugging
327
"""
328
Getting information about application state
329
"""
330
331
# Check Flask-AppBuilder version
332
flask fab version
333
334
# List all registered views and their permissions
335
flask fab list-views --verbose
336
337
# List all users and their roles
338
flask fab list-users --verbose
339
```
340
341
### Custom CLI Commands
342
343
Creating custom CLI commands for application-specific operations and extending Flask-AppBuilder's CLI capabilities.
344
345
```python { .api }
346
# Creating custom CLI commands
347
from flask.cli import with_appcontext
348
from flask_appbuilder.cli import cli
349
import click
350
351
@cli.command()
352
@click.option('--format', default='json', help='Export format (json, csv)')
353
@click.option('--output', help='Output filename')
354
@with_appcontext
355
def export-data(format, output):
356
"""Export application data in specified format."""
357
from flask import current_app
358
359
if format == 'json':
360
export_to_json(output or 'data_export.json')
361
elif format == 'csv':
362
export_to_csv(output or 'data_export.csv')
363
else:
364
click.echo(f"Unsupported format: {format}")
365
366
@cli.command()
367
@click.option('--days', default=30, help='Days of data to keep')
368
@with_appcontext
369
def cleanup-logs(days):
370
"""Clean up old log entries."""
371
from datetime import datetime, timedelta
372
373
cutoff_date = datetime.now() - timedelta(days=days)
374
375
# Custom cleanup logic
376
deleted_count = cleanup_old_logs(cutoff_date)
377
click.echo(f"Deleted {deleted_count} log entries older than {days} days")
378
379
@cli.command()
380
@click.argument('model_name')
381
@click.option('--count', default=10, help='Number of records to generate')
382
@with_appcontext
383
def generate-test-data(model_name, count):
384
"""Generate test data for specified model."""
385
model_class = get_model_by_name(model_name)
386
387
if not model_class:
388
click.echo(f"Model '{model_name}' not found")
389
return
390
391
generated_count = generate_fake_data(model_class, count)
392
click.echo(f"Generated {generated_count} test records for {model_name}")
393
394
@cli.command()
395
@with_appcontext
396
def init-sample-data():
397
"""Initialize application with sample data."""
398
click.echo("Creating sample data...")
399
400
# Create sample departments
401
create_sample_departments()
402
403
# Create sample users
404
create_sample_users()
405
406
# Create sample products
407
create_sample_products()
408
409
click.echo("Sample data created successfully!")
410
411
# Usage of custom commands
412
"""
413
flask fab export-data --format json --output backup.json
414
flask fab cleanup-logs --days 7
415
flask fab generate-test-data Person --count 50
416
flask fab init-sample-data
417
"""
418
419
# Advanced custom command with progress bar
420
@cli.command()
421
@click.option('--batch-size', default=1000, help='Batch size for processing')
422
@with_appcontext
423
def migrate-legacy-data(batch_size):
424
"""Migrate data from legacy system."""
425
import tqdm
426
427
# Get total count for progress bar
428
total_records = get_legacy_record_count()
429
430
with tqdm.tqdm(total=total_records) as pbar:
431
offset = 0
432
433
while offset < total_records:
434
# Process batch of records
435
batch = get_legacy_records(offset, batch_size)
436
process_legacy_batch(batch)
437
438
offset += len(batch)
439
pbar.update(len(batch))
440
441
click.echo(f"Migration completed: {total_records} records processed")
442
443
# Command with confirmation prompt
444
@cli.command()
445
@click.option('--force', is_flag=True, help='Skip confirmation prompt')
446
@with_appcontext
447
def reset-database(force):
448
"""Reset database to initial state (WARNING: destructive)."""
449
if not force:
450
if not click.confirm('This will delete all data. Are you sure?'):
451
click.echo('Operation cancelled.')
452
return
453
454
# Drop all tables
455
db.drop_all()
456
457
# Recreate tables
458
db.create_all()
459
460
# Create default admin user
461
create_default_admin()
462
463
click.echo('Database reset completed.')
464
465
# Command group for related operations
466
@cli.group()
467
def backup():
468
"""Backup and restore operations."""
469
pass
470
471
@backup.command()
472
@click.option('--output-dir', default='backups', help='Backup directory')
473
def create(output_dir):
474
"""Create full application backup."""
475
import os
476
from datetime import datetime
477
478
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
479
backup_path = os.path.join(output_dir, f'backup_{timestamp}')
480
481
create_full_backup(backup_path)
482
click.echo(f'Backup created: {backup_path}')
483
484
@backup.command()
485
@click.argument('backup_path')
486
@click.option('--force', is_flag=True, help='Overwrite existing data')
487
def restore(backup_path, force):
488
"""Restore from backup."""
489
if not force:
490
if not click.confirm('This will overwrite existing data. Continue?'):
491
return
492
493
restore_from_backup(backup_path)
494
click.echo('Restore completed successfully.')
495
496
# Usage:
497
# flask fab backup create --output-dir /path/to/backups
498
# flask fab backup restore backup_20231201_143022 --force
499
```
500
501
### Legacy Console Script (Deprecated)
502
503
Information about the deprecated `fabmanager` console script and migration guidance to Flask CLI commands.
504
505
```python { .api }
506
# DEPRECATED: fabmanager console script
507
# Use 'flask fab' commands instead
508
509
# Old fabmanager commands (DEPRECATED):
510
"""
511
fabmanager create-admin --app myapp
512
fabmanager create-user --app myapp
513
fabmanager create-db --app myapp
514
fabmanager reset-password --app myapp
515
fabmanager list-users --app myapp
516
fabmanager create-permissions --app myapp
517
fabmanager security-cleanup --app myapp
518
fabmanager version --app myapp
519
"""
520
521
# NEW: Flask CLI commands (RECOMMENDED):
522
"""
523
flask fab create-admin
524
flask fab create-user
525
flask fab create-db
526
flask fab reset-password
527
flask fab list-users
528
flask fab create-permissions
529
flask fab security-cleanup
530
flask fab version
531
"""
532
533
# Migration guide from fabmanager to flask fab:
534
"""
535
1. Replace 'fabmanager' with 'flask fab'
536
2. Remove '--app myapp' parameter (use FLASK_APP environment variable)
537
3. Set FLASK_APP environment variable:
538
export FLASK_APP=myapp.py
539
540
4. Run new commands:
541
flask fab create-admin (instead of fabmanager create-admin --app myapp)
542
"""
543
544
# Environment setup for Flask CLI:
545
"""
546
# Linux/Mac:
547
export FLASK_APP=app.py
548
export FLASK_ENV=development
549
550
# Windows:
551
set FLASK_APP=app.py
552
set FLASK_ENV=development
553
554
# Or use .flaskenv file:
555
echo "FLASK_APP=app.py" > .flaskenv
556
echo "FLASK_ENV=development" >> .flaskenv
557
"""
558
559
# Batch migration script example:
560
"""
561
#!/bin/bash
562
# migrate_to_flask_cli.sh
563
564
# Set Flask app
565
export FLASK_APP=myapp.py
566
567
# Old fabmanager commands -> New flask fab commands
568
echo "Migrating CLI commands..."
569
570
# Replace fabmanager calls in scripts:
571
sed -i 's/fabmanager create-admin --app myapp/flask fab create-admin/g' deploy.sh
572
sed -i 's/fabmanager create-db --app myapp/flask fab create-db/g' deploy.sh
573
sed -i 's/fabmanager create-permissions --app myapp/flask fab create-permissions/g' deploy.sh
574
575
echo "Migration completed. Update your documentation and scripts."
576
"""
577
```
578
579
### CLI Integration with Application
580
581
Integrating CLI commands with Flask-AppBuilder applications and accessing application context within commands.
582
583
```python { .api }
584
# Accessing Flask-AppBuilder components in CLI commands
585
from flask.cli import with_appcontext
586
from flask import current_app
587
588
@cli.command()
589
@with_appcontext
590
def sync-users():
591
"""Sync users from external system."""
592
# Access AppBuilder instance
593
appbuilder = current_app.appbuilder
594
595
# Access security manager
596
security_manager = appbuilder.sm
597
598
# Access database session
599
db_session = appbuilder.get_session
600
601
# Sync users from LDAP/Active Directory
602
external_users = get_external_users()
603
604
for ext_user in external_users:
605
# Check if user exists
606
user = security_manager.find_user(username=ext_user['username'])
607
608
if not user:
609
# Create new user
610
user = security_manager.add_user(
611
username=ext_user['username'],
612
first_name=ext_user['first_name'],
613
last_name=ext_user['last_name'],
614
email=ext_user['email'],
615
role=security_manager.find_role('Employee')
616
)
617
click.echo(f"Created user: {user.username}")
618
else:
619
# Update existing user
620
user.email = ext_user['email']
621
security_manager.update_user(user)
622
click.echo(f"Updated user: {user.username}")
623
624
# Command with database operations
625
@cli.command()
626
@click.option('--model', help='Model name to analyze')
627
@with_appcontext
628
def analyze-data(model):
629
"""Analyze application data."""
630
appbuilder = current_app.appbuilder
631
632
if model:
633
# Analyze specific model
634
model_class = get_model_by_name(model)
635
if model_class:
636
analyze_model_data(model_class, appbuilder.get_session)
637
else:
638
# Analyze all models
639
for model_class in get_all_models():
640
analyze_model_data(model_class, appbuilder.get_session)
641
642
# Command with view registration
643
@cli.command()
644
@with_appcontext
645
def register-views():
646
"""Register additional views dynamically."""
647
appbuilder = current_app.appbuilder
648
649
# Register new views
650
appbuilder.add_view(
651
DynamicView,
652
"Dynamic View",
653
icon="fa-cog",
654
category="Dynamic"
655
)
656
657
# Update permissions
658
appbuilder.add_permissions(update_perms=True)
659
660
click.echo("Dynamic views registered successfully")
661
662
# Command with configuration management
663
@cli.command()
664
@click.option('--key', help='Configuration key to show')
665
@with_appcontext
666
def show-config(key):
667
"""Show application configuration."""
668
config = current_app.config
669
670
if key:
671
if key in config:
672
click.echo(f"{key} = {config[key]}")
673
else:
674
click.echo(f"Configuration key '{key}' not found")
675
else:
676
# Show all Flask-AppBuilder related config
677
fab_keys = [k for k in config.keys() if k.startswith(('FAB_', 'AUTH_'))]
678
679
for config_key in sorted(fab_keys):
680
click.echo(f"{config_key} = {config[config_key]}")
681
682
# Command with menu management
683
@cli.command()
684
@with_appcontext
685
def rebuild-menu():
686
"""Rebuild application menu structure."""
687
appbuilder = current_app.appbuilder
688
689
# Clear existing menu
690
appbuilder.menu.clear()
691
692
# Rebuild menu from configuration
693
rebuild_menu_from_config(appbuilder)
694
695
click.echo("Menu structure rebuilt successfully")
696
697
# Usage examples:
698
"""
699
flask fab sync-users
700
flask fab analyze-data --model Person
701
flask fab register-views
702
flask fab show-config --key AUTH_TYPE
703
flask fab rebuild-menu
704
"""
705
```