Creating websites with Flask
What is Flask?
Flask is a lightweight “micro” web framework for Python that makes building web applications straightforward with minimal boilerplate, offering simple routing via decorators, dynamic HTML templating with Jinja2, a built-in development server with interactive debugger, and an extensible ecosystem of optional extensions for tasks like database integration, form handling, and authentication; its unopinionated nature means you’re free to structure your project however you like, making Flask ideal for everything from small prototypes to full-scale, production-ready services.
Step 1. Install Flask
Make sure you have Python 3.7+ installed.
In your project directory, create and activate a virtual environment:
python3 -m venv venv
source venv/bin/activate # Linux/macOS
venv\Scripts\activate.bat # Windows
Install Flask:
pip install Flask
Step 2: Create Your App File
Create a file named app.py in your project directory with the following contents:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return '<h1>Hello, Flask on port 3000!</h1>'
if __name__ == '__main__':
# Listen on all network interfaces, port 3000
app.run(host='0.0.0.0', port=3000, debug=True)
-
host='0.0.0.0' Makes your server accessible from other machines on your network.
-
debug=True Enables auto-reload and more informative error messages during development.
Step 3: Run Your App
From your project directory:
python app.py
You should see something like:
- Serving Flask app "app.py"
- Running on http://0.0.0.0:3000/ (Press CTRL+C to quit)
Open your browser to http://localhost:3000/ to see your “Hello, Flask” message.
Step 4: Next Steps
- Add More Routes
@app.route('/about')
def about():
return '<h2>About Us</h2>'
- Use Templates Create a templates/ folder and render HTML with Jinja2:
from flask import render_template
@app.route('/hello/<name>')
def hello(name):
return render_template('hello.html', name=name)
-
Serve Static Files Put CSS, JavaScript, or images in a static/ folder.
-
Prepare for Production When ready to deploy, use a WSGI server (e.g., Gunicorn) and optionally front it with Nginx, still listening on port 3000 or proxying from 80/443.