Python Flask Basics
Introduction
Flask is a lightweight and flexible web framework for Python. Created by Armin Ronacher, Flask is known as a micro-framework because it doesn't require particular tools or libraries, giving developers the freedom to choose components that best suit their projects. Despite its simplicity, Flask is powerful enough to build complex web applications.
In this tutorial, we'll explore the fundamental concepts of Flask and build a simple web application step by step. By the end, you'll understand how to set up routes, handle HTTP requests, render templates, and more.
Prerequisites
Before we start, make sure you have:
- Python 3.6 or newer installed
- Basic knowledge of Python
- Understanding of HTML (helpful but not required)
- A code editor of your choice
What You'll Learn
- Setting up a Flask environment
- Creating your first Flask application
- Handling routes and URL patterns
- Working with templates
- Processing form data
- Managing sessions and cookies
Setting Up Flask
First, let's install Flask using pip:
pip install flask
After installation, you can verify it by checking the version:
python -c "import flask; print(flask.__version__)"
Your First Flask Application
Let's create a simple "Hello, World!" application to understand the basic structure of a Flask app.
Create a new file named app.py
:
from flask import Flask
# Create a Flask application instance
app = Flask(__name__)
# Define a route for the root URL
@app.route('/')
def hello_world():
return 'Hello, World!'
# Run the application if this file is executed
if __name__ == '__main__':
app.run(debug=True)
Run this application:
python app.py
Output:
* Serving Flask app 'app'
* Debug mode: on
* Running on http://127.0.0.1:5000 (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 123-456-789
Now, open your web browser and navigate to http://127.0.0.1:5000/
. You should see "Hello, World!" displayed.