Flask is a lightweight and easy-to-use web framework for Python. In this article, we'll walk through the basics of creating a simple web application using Flask. Whether you're a beginner in web development or looking to prototype a project quickly, Flask provides a great starting point.
Installing Flask
Before we start, make sure you have Python installed on your machine. You can install Flask using the following command:
pip install flask
Creating a Simple Flask App
Let's create a minimal Flask application. Create a file named
app.py with the following content:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello, Flask!'
This code defines a basic Flask app with a single route
'/' that returns the string 'Hello, Flask!' when you visit the
home page.
Running the Flask App
To run your Flask app, execute the following commands in your terminal or command prompt:
export FLASK_APP=app.py # For Linux/macOS
set FLASK_APP=app.py # For Windows
flask run
Visit http://127.0.0.1:5000/ in your web browser, and you
should see the 'Hello, Flask!' message.
Adding Dynamic Routes
Flask allows you to create dynamic routes by adding variable parts to the URL. Let's modify our app to greet the user with a custom message:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello, Flask!'
@app.route('/greet/<name>')
def greet(name):
return f'Hello, {name}!'
Now, visiting http://127.0.0.1:5000/greet/John will display
'Hello, John!'
Using Templates for HTML
Flask allows you to render HTML templates for a more sophisticated web
application. Create a folder named templates in the same
directory as your app.py and add a file named
index.html with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flask App</title>
</head>
<body>
<h1>{{ message }}</h1>
</body>
</html>
Modify your Flask app to render this template:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html', message='Hello, Flask!')
This code renders the index.html template with a custom
message.
Conclusion
Congratulations! You've built a simple web application with Flask. This is just the beginning—Flask offers much more for creating robust and feature-rich web applications. As you continue your journey in web development, explore Flask's documentation and build upon this foundation to create more complex projects.
Stay tuned for future articles where we'll explore advanced Flask features and real-world web application development.