Virtual Environments & First Flask Application
Virtual Environments & First Flask Application
Before building web applications with Flask, establishing an isolated virtual environment is critical. Virtual environments guarantee that your project's dependencies never conflict with system-wide Python packages or other projects on the same machine.
1. Setting Up an Isolated Virtual Environment
Python 3 provides the built-in venv module. Follow these commands in your project terminal:
On Windows (PowerShell / Command Prompt):
On macOS / Linux:
When activated, your terminal prompt will display (.venv).
2. Installing Flask 3.x
Install the latest version of Flask using pip:
To verify the installation and view installed dependencies:
You will notice that installing flask automatically installs its key dependencies:
Werkzeug: WSGI utilities and routingJinja2: Template engineMarkupSafe: HTML string escapingclick: Command Line Interface frameworkitsdangerous: Cryptographic signing for session cookiesblinker: Signal dispatching (in modern Flask 3.x)
3. Creating Your First Minimal Flask Application
Create a file named app.py in your project root:
4. Dissecting the Code Line by Line
- 1
from flask import Flask: Imports the central application class. - 2
app = Flask(__name__):
- An instance of the
Flaskclass is created. __name__is a Python special variable representing the current module's name ("__main__"when run directly).- Flask uses
__name__to locate templates, static assets, and resource folders relative to this file.
- 1
@app.route("/"):
- A Python decorator that registers a URL path mapping. When an incoming HTTP GET request matches
"/", Flask invokes the decoratedhome()function.
- 1
return "<h1>...</h1>":
- Returns an HTML string. Flask automatically converts string returns into an HTTP
200 OKresponse withContent-Type: text/html; charset=utf-8.
- 1
return {"status": "success", ...}:
- In modern Flask, returning a Python dictionary automatically serializes to a JSON response with
Content-Type: application/json.
- 1
app.run(debug=True, port=5000):
- Starts Werkzeug's local development server on
http://127.0.0.1:5000.
5. Running the Application
Execute app.py directly:
Console Output:
Open http://127.0.0.1:5000 in your web browser to view your live web application!
Practice Quiz
__name__ passed into app = Flask(__name__)?debug=True flag in app.run() during development?app.run() development server explicitly not recommended for production deployments?Flask CLI & Environment Configuration
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| What is Flask & WSGI Architecture | Flask CLI & Environment Configuration |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.