杰瑞科技汇

Flask应用如何配置端口号?

Of course! Here's a comprehensive guide to handling ports in Python Flask, from the basics to advanced scenarios.

Flask应用如何配置端口号?-图1
(图片来源网络,侵删)

The Quick Answer: How to Run on a Specific Port

The most common way to specify a port is by using the --port command-line flag when you run your Flask app.

Let's say you have a simple Flask app named app.py:

# app.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
    return "Hello, World! I'm running on a custom port."
if __name__ == '__main__':
    app.run()

To run this application on port 5005, you would use this command in your terminal:

# The basic way (runs on default port 5000)
python app.py
# The specific way (runs on port 5005)
flask run --port=5005
# Or using a space (also works)
flask run --port 5005

Now, if you open your web browser and go to http://127.0.0.1:5005/, you will see your "Hello, World!" message.


How It Works: The app.run() Method

When you run your script directly (python app.py), the app.run() method is executed. This method starts the development server. You can configure the port directly within your Python code using its parameters.

The signature of app.run() is: app.run(host, port, debug, ...)

  • host: The host to listen on. Defaults to 0.0.1 (localhost). Use 0.0.0 to make it accessible from any IP address on your machine.
  • port: The port to listen on. Defaults to 5000.

Example: Setting the Port in Code

You can modify your app.py to specify the port directly:

# app.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
    return "Hello, World! Port is set in the code."
if __name__ == '__main__':
    # Run the app on host 0.0.0.0 and port 8080
    app.run(host='0.0.0.0', port=8080)

Now, when you run python app.py, it will automatically start on port 8080 and be accessible from other devices on your local network (if they can reach your machine's IP).

Note: While setting the port in app.run() is convenient for quick tests, it's generally considered better practice to use command-line arguments or environment variables for configuration. This keeps your code cleaner and separates configuration from logic.


The Recommended Way: Using Environment Variables

For more robust and flexible applications, especially when deploying, you should use environment variables. The FLASK_APP and FLASK_RUN_PORT environment variables are designed for this.

Step 1: Set the Environment Variable

In your terminal, before running the flask run command, set the FLASK_RUN_PORT variable.

On Linux or macOS:

export FLASK_RUN_PORT=3000
flask run

On Windows (Command Prompt):

set FLASK_RUN_PORT=3000
flask run

On Windows (PowerShell):

$env:FLASK_RUN_PORT = "3000"
flask run

Now, your app will run on port 3000 without any other changes to your code.

Step 2: Make Your Script Discoverable (if needed)

If your file is not named app.py or wsgi.py, you need to tell Flask where to find it using the FLASK_APP variable.

export FLASK_APP=my_custom_app.py
export FLASK_RUN_PORT=8888
flask run

Advanced Scenarios

A. Running on 0.0.0 to Access from Other Devices

By default, Flask only listens for connections on localhost (0.0.1). This means you can't access it from other devices (like your phone or another computer) on the same network.

To make your app accessible from other devices, you must bind it to 0.0.0, which means "listen on all available network interfaces."

You can do this in two ways:

Using the --host flag:

flask run --host=0.0.0.0 --port=5000

Using the FLASK_RUN_HOST environment variable:

export FLASK_RUN_HOST=0.0.0.0
export FLASK_RUN_PORT=5000
flask run

Now, if your computer's IP address is, for example, 168.1.15, you can access your Flask app from another device by navigating to http://192.168.1.15:5000/.

B. Handling Port Already in Use

If you try to start Flask on a port that is already being used by another program, you will see an error like:

OSError: [Errno 98] Address already in use

How to fix it:

  1. Find the process using the port:

    • On Linux/macOS:
      lsof -i :5000
      # or
      sudo netstat -tulpn | grep :5000
    • On Windows:
      netstat -ano | findstr :5000

      This will show you the Process ID (PID) of the application using the port.

  2. Kill the process:

    • On Linux/macOS:
      kill <PID>
    • On Windows:
      taskkill /F /PID <PID>

      After killing the process, you can start your Flask app successfully.


Summary Table

Method Command / Code When to Use
Command-Line Flag flask run --port=8080 Quick, one-off testing and running.
app.run() Parameter app.run(port=8080) Simple scripts, quick demos. Good for beginners.
Environment Variable (FLASK_RUN_PORT) export FLASK_RUN_PORT=8080 && flask run Recommended. Clean separation of configuration from code. Essential for deployment and CI/CD.
Host Flag flask run --host=0.0.0.0 --port=5000 When you need to access the Flask app from other devices on your network.
Environment Variable (FLASK_RUN_HOST) export FLASK_RUN_HOST=0.0.0.0 && flask run The recommended way to make your app accessible from other devices.
分享:
扫描分享到社交APP
上一篇
下一篇