杰瑞科技汇

python flaskscript

Of course! Let's dive into flask-script. It's a fantastic tool that was the standard for adding custom commands to Flask applications before Flask 2.2.

python flaskscript-图1
(图片来源网络,侵删)

What is Flask-Script?

Flask-Script is an extension for Flask that provides support for writing external scripts, or more commonly, adding custom commands to the flask command-line interface (CLI).

Think of it as a way to run administrative tasks, database migrations, or any other utility function for your Flask app directly from your terminal.


The Problem Flask-Script Solves

Before Flask 2.2, the built-in flask run command was very basic. It could only start the development server. If you wanted to:

  • Initialize your database.
  • Create a superuser.
  • Run a data import script.
  • Perform maintenance tasks.

You had to write separate Python scripts and manually import your Flask application, which was clunky and error-prone. Flask-Script solved this by providing a structured way to add these commands.

python flaskscript-图2
(图片来源网络,侵删)

How to Use Flask-Script (Step-by-Step)

Here’s a complete guide to setting up and using Flask-Script.

Step 1: Installation

First, you need to install the library.

pip install Flask-Script

Step 2: Basic Setup

In your main application file (e.g., app.py or run.py), you need to do three things:

  1. Import Flask and Manager.
  2. Create a Flask app instance.
  3. Create a Manager instance, passing your app to it.

The Manager is the core object that will handle your custom commands.

# app.py
from flask import Flask
from flask_script import Manager
# 1. Create the Flask application
app = Flask(__name__)
# 2. Create a Manager instance
manager = Manager(app)
# A simple route to show the app is working
@app.route('/')
def index():
    return "Hello, World!"
if __name__ == '__main__':
    # The manager will handle the command-line arguments
    manager.run()

Step 3: Running the Default Server

Now, instead of running python app.py, you use the manager object. By default, it provides a run command to start the development server.

# Use the manager to run the app
python app.py runserver
# Or with host and port
python app.py runserver --host=0.0.0.0 --port=8080

You'll see output similar to this, confirming it's working:

 * Serving Flask app "app" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Step 4: Creating Custom Commands

This is where Flask-Script shines. You can easily create your own commands using Python functions or classes.

Method 1: Using a Function (Simple Commands)

This is the easiest way to create a command. You just decorate a function with @manager.command.

# app.py (continued from above)
@manager.command
def hello(name):
    """Prints a greeting to the console."""
    print(f"Hello, {name}!")

Now you can run this new command from your terminal:

python app.py hello Alice

Output:

Hello, Alice!

The function name (hello) becomes the command name. The docstring ("""Prints a greeting...""") is used as the help message for the command.

Method 2: Using a Class (Complex Commands with Arguments)

For commands that need more structure, arguments, or options, a class-based approach is better. You inherit from Command and define a run method.

# app.py (continued from above)
from flask_script import Command
class CreateUserCommand(Command):
    """Creates a new user in the database."""
    # 'capture_all_args=True' allows the command to accept any arguments
    capture_all_args = True
    def run(self, remaining_args):
        if len(remaining_args) != 2:
            print("Error: Please provide a username and an email.")
            print("Usage: python app.py create-user <username> <email>")
            return
        username = remaining_args[0]
        email = remaining_args[1]
        # In a real app, you would save this to your database here
        # For example: db.session.add(User(username=username, email=email))
        # db.session.commit()
        print(f"User '{username}' with email '{email}' has been created (not really).")
# Add the command to the manager
manager.add_command('create-user', CreateUserCommand())

Now you can run this command:

# Correct usage
python app.py create-user john_doe john@example.com
# Incorrect usage (shows help)
python app.py create-user john_doe

Correct Usage Output:

User 'john_doe' with email 'john@example.com' has been created (not really).

Incorrect Usage Output:

Error: Please provide a username and an email.
Usage: python app.py create-user <username> <email>

The Modern Alternative: Flask's Built-in CLI

It's important to know that Flask 2.2 and later has a built-in CLI that is much more powerful and is now the recommended way to handle this. Flask-Script is now considered legacy.

If you're starting a new project with a recent version of Flask, you should use the built-in CLI.

How the Modern Flask CLI Works

  1. No flask-script needed. It's part of Flask core.
  2. No Manager needed. You register commands directly with the app.cli object.

Here's how you'd rewrite the previous examples using the modern approach.

Example 1: Function-based command

# app.py (modern)
from flask import Flask
app = Flask(__name__)
@app.cli.command("hello")
def hello_command(name):
    """Prints a greeting to the console."""
    print(f"Hello, {name}!")
if __name__ == '__main__':
    # The built-in CLI is automatically registered
    app.run()

Running it is slightly different:

# Use 'flask' command, not 'python app.py'
flask hello Alice

Note: For this to work, you need to set the FLASK_APP environment variable: export FLASK_APP=app.py (on Linux/macOS) or $env:FLASK_APP = "app.py" (on PowerShell).

Example 2: Class-based command

# app.py (modern)
from flask import Flask
from flask.cli import AppGroup
app = Flask(__name__)
# Create a custom command group for better organization
user_cli = AppGroup('user')
# Register the group with the app
app.cli.add_command(user_cli)
@user_cli.command("create")
def create_user(username, email):
    """Creates a new user in the database."""
    print(f"User '{username}' with email '{email}' has been created (not really).")
if __name__ == '__main__':
    app.run()

Running this command:

flask user create john_doe john@example.com

Summary: Flask-Script vs. Modern Flask CLI

Feature Flask-Script (Legacy) Modern Flask CLI (Flask >= 2.2)
Status Legacy, not recommended for new projects. Recommended, built-in, actively developed.
Installation pip install Flask-Script pip install Flask (included)
Core Object Manager(app) app.cli or app.cli.group()
Command Syntax python app.py <command> flask <command> (requires FLASK_APP)
Function Decorator @manager.command @app.cli.command("name")
Class-based class Command class Group or direct functions with click integration

Conclusion:

While Flask-Script was the go-to solution for many years, you should use Flask's built-in CLI for any new project. It's more integrated, powerful, and doesn't require an extra dependency. However, you will still encounter Flask-Script in many older tutorials and existing applications, so understanding how it works is still very valuable.

分享:
扫描分享到社交APP
上一篇
下一篇