Web development in Python is usually facilitated by web frameworks, and one of the most popular frameworks is Flask. In this tutorial, we’ll walk through creating a simple web application using Flask.
Prerequisites
- Basic knowledge of Python
- Familiarity with HTML
- Python installed on your system
Steps to Follow
Step 1: Install Flask
First, you need to install Flask. Open your terminal and run:
pip install Flask
Step 2: Create a New Project Directory
Create a new folder for your project:
mkdir my_flask_app
cd my_flask_app
Step 3: Create a New Python File
Create a new Python file in the project folder. You can name it app.py
.
Step 4: Initialize Flask App
Inside app.py
, write the following code to create a basic Flask app.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello, Flask!'
if __name__ == '__main__':
app.run()
Step 5: Run Your App
Save the file and run it using:
python app.py
You should see output indicating that the server is running. Open your web browser and go to http://localhost:5000/
. You should see “Hello, Flask!” displayed.
Step 6: Create HTML Template
Create a new folder named templates
in your project directory. Inside templates
, create an HTML file named index.html
.
<!DOCTYPE html>
<html>
<head>
<title>My Flask App</title>
</head>
<body>
<h1>Hello, Flask!</h1>
</body>
</html>
Step 7: Render HTML Template
Modify the home()
function in your app.py
to render the index.html
template.
from flask import render_template
@app.route('/')
def home():
return render_template('index.html')
Step 8: Using Variables in Templates
You can pass variables from your Flask app to your templates. Update your home()
function as follows:
@app.route('/')
def home():
name = "John"
return render_template('index.html', name=name)
In your index.html
, you can then use this variable like this:
<h1>Hello, {{ name }}!</h1>
Step 9: Handling Form Data
To handle form submissions, you’ll need to import request
from Flask.
Here is how you can handle a simple form submission:
In index.html
:
<form action="/submit" method="post">
<input type="text" name="name">
<input type="submit">
</form>
In app.py
:
from flask import request
@app.route('/submit', methods=['POST'])
def submit():
name = request.form.get('name')
return f'Hello, {name}!'
Step 10: Final Touches and Further Steps
As you get more comfortable, you can explore Flask’s documentation to find more functionalities like:
- URL converters
- File uploads
- Session management
- Database integration
- Error