Are you ready to build your first web application with Flask? This quick tutorial will get you up and running in just 3 minutes. We'll create a simple application with routes, templates, and even handle form submissions.
Prerequisites
- Python 3.x installed
- Basic Python knowledge
- A code editor
Step 1: Setup (30 seconds)
First, create a new directory and set up your virtual environment:
mkdir flask_tutorial
cd flask_tutorial
python -m venv venv
source venv/bin/activate # On Windows use: venv\Scripts\activate
pip install flask
Step 2: Create Your First App (1 minute)
Create a new file called app.py.
from flask import Flask, render_template, request
app = Flask(__name__)
# Home route
@app.route('/')
def home():
return 'Hello, Flask!'
# Dynamic route with parameter
@app.route('/greet/<name>')
def greet(name):
return f'Hello, {name}!'
# Route with HTML template
@app.route('/welcome')
def welcome():
return render_template('welcome.html')
# Form handling
@app.route('/submit', methods=['GET', 'POST'])
def submit():
if request.method == 'POST':
name = request.form.get('name')
return f'Form submitted! Hello, {name}!'
return render_template('form.html')
if __name__ == '__main__':
app.run(debug=True)
Step 3: Create Templates (1 minute)
Create templates/welcome.html and templates/form.html.
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<h1>Welcome to Flask!</h1>
<p>This is your first template.</p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Submit Form</title>
</head>
<body>
<form method="POST">
<input type="text" name="name" placeholder="Enter your name">
<button type="submit">Submit</button>
</form>
</body>
</html>
Step 4: Run Your Application (30 seconds)
Run your application with:
python app.py
Visit these URLs to test your routes:
- http://localhost:5000/ - Shows "Hello, Flask!"
- http://localhost:5000/greet/YourName - Shows personalized greeting
- http://localhost:5000/welcome - Shows welcome template
- http://localhost:5000/submit - Shows form with POST handling
What You've Learned
In just 3 minutes, you've created a Flask application that:
- Handles basic routing
- Uses dynamic URL parameters
- Renders HTML templates
- Processes form submissions
- Runs in debug mode for development
Next Steps
- Add database integration with SQLAlchemy
- Implement user authentication
- Style your templates with CSS
- Create RESTful APIs
- Add error handling
Now you're ready to build more complex Flask applications! Happy coding! 🚀
