Before starting to learn Flask, let’s briefly understand what it is. Flask is a lightweight Python Web framework, as flexible as building blocks, making it suitable for beginners to quickly develop simple websites or web applications. It doesn’t require much complex configuration to create pages accessible in browsers, making it an excellent entry tool for web development.
一、Prepare the Python Environment¶
To use Flask, you first need to install Python. Python is the foundation for running Flask, similar to a foundation for building a house.
1. Download and Install Python¶
- Official Download: Open your browser, visit the Python official website (https://www.python.org/), click “Downloads”, and select the Python version suitable for your system (Python 3.x series is recommended, e.g., Python 3.9 or later).
- Installation Steps:
- Windows Users: During installation, be sure to check “Add Python to PATH” (add to system environment variables). This allows you to use the
pythoncommand directly in the command line, avoiding subsequent configuration issues. - Mac/Linux Users: Python may already be pre-installed, but it might be an older version. It is recommended to upgrade to Python 3.x using official guides (e.g.,
brew install python3or system-provided installation tools).
2. Verify Python Installation¶
After installation, open the command line (Windows: press Win+R, type “cmd”; Mac/Linux: open Terminal directly), and enter the following command:
python --version
If a version number like Python 3.9.7 is displayed, Python has been successfully installed!
二、Install Flask¶
Once Python is installed, you can use pip (Python’s “App Store”) to install Flask. pip is Python’s built-in package management tool for downloading and installing third-party libraries.
1. Install Flask¶
In the command line, enter:
pip install flask
If the installation is slow (due to overseas servers), you can use a domestic mirror for acceleration:
pip install flask -i https://pypi.tuna.tsinghua.edu.cn/simple
Wait a moment, and Flask will automatically download and install into your Python environment.
2. Verify Flask Installation¶
After installation, check the version with:
flask --version
If version information like Flask 2.3.3 is displayed, Flask has been successfully installed!
三、(Optional but Recommended) Use a Virtual Environment¶
If you’re new to programming, virtual environments might seem complex, but they help isolate dependencies between different projects, preventing issues like “one project using an old library version causing another project to crash”. It’s like keeping different furniture in separate rooms without interference.
1. Create a Virtual Environment¶
In the command line, first create a project folder (e.g., my_flask_project), then navigate into it and execute:
python -m venv venv
This will generate a venv folder in the current directory, containing your virtual environment.
2. Activate the Virtual Environment¶
- Windows Users:
venv\Scripts\activate
After activation, the command line prefix will show (venv), indicating you’re in the virtual environment.
- Mac/Linux Users:
source venv/bin/activate
3. Deactivate the Virtual Environment¶
When you finish development in the virtual environment, simply enter deactivate to exit.
四、Create Your First Flask Application¶
Now, let’s write a simple Flask program that displays “Hello, Flask!” in the browser.
1. Create a Project File¶
In your project folder (e.g., my_flask_project), create a new text file and rename it to app.py (Python files must use the .py extension).
2. Write the Code¶
Open app.py with Notepad or a simple editor (e.g., VS Code) and enter the following code:
# Import the Flask class (like hiring a "Web Construction Expert")
from flask import Flask
# Create a Flask application instance (app is the core object; __name__ refers to the current file name)
app = Flask(__name__)
# Define a "route": When accessing the website root directory (http://127.0.0.1:5000/), the following function is executed
@app.route('/')
def hello():
# Content returned to the browser (like plating a dish after cooking)
return 'Hello, Flask! This is my first web page~'
# Main program entry: When app.py is run directly, start the Flask server
if __name__ == '__main__':
# Start the server with debug=True to enable "debug mode" (automatically restarts when code changes, no manual restart needed)
app.run(debug=True)
3. Run the Flask Application¶
In the command line, ensure the virtual environment is activated (prefix shows (venv)), navigate to the project folder, and execute:
python app.py
If you see output like:
* Serving Flask app 'app'
* Debug mode: on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
the server has started successfully.
4. Access the Application¶
Open your browser and visit http://127.0.0.1:5000/ (or http://localhost:5000/). You’ll see “Hello, Flask! This is my first web page~”. Congratulations! Your first Flask application is running successfully!
五、Common Issues and Solutions¶
1. Installation Failure?¶
- Reason:
pipmay not be updated, or there could be network issues. - Solution: First upgrade
pip:
python -m pip install --upgrade pip
Then reinstall Flask.
2. Port Already Occupied?¶
- Reason: Flask defaults to port 5000, which may be occupied by another program (e.g., another running Flask project).
- Solution: Modify the port in
app.run()in the code (e.g., change to 8080):
app.run(port=8080, debug=True) # Access via http://127.0.0.1:8080/
3. Code Changes Not Taking Effect?¶
- Reason: Without
debug=True, you need to manually restart the server after modifying code, which is inconvenient. - Solution: Ensure
app.run(debug=True)hasdebug=Trueso the server restarts automatically when code changes.
六、Summary¶
Now you’ve set up the Flask development environment and created your first accessible web page. Next, try modifying the code: add another route (e.g., @app.route('/about')) under @app.route('/'), write a new view function to return different content, and see if you can access it at the new URL (http://127.0.0.1:5000/about).
Remember, the most important part of learning programming is hands-on practice. Even modifying a single line of code and seeing the result counts as growth. Flask’s flexibility allows you to explore more complex features later, such as route parameters, template rendering, and database connections, laying the foundation for your web development journey!