Building a simple web application involves creating a project structure, defining routes, creating views, and rendering templates. For this example, we’ll use the Flask web framework to build a basic web application that displays a homepage.
Step 1: Set Up the Project
Create a new directory for your project and set up a virtual environment:
mkdir mywebapp
cd mywebapp
python -m venv venv
Activate the virtual environment:
- On Windows:
venv\Scripts\activate
- On macOS/Linux:
source venv/bin/activate
Step 2: Install Flask
Install Flask using pip
:
pip install Flask
Step 3: Create the Flask Application
Create a file named app.py
for your Flask application:
# app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html', title='Home', content='Welcome to My Web App!')
if __name__ == '__main__':
app.run(debug=True)
Step 4: Create Templates Folder
Inside your project directory, create a folder named templates
. This is where Flask will look for HTML templates.
Step 5: Create HTML Template
Inside the templates
folder, create a file named index.html
:
<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ title }}</title>
</head>
<body>
<h1>{{ content }}</h1>
</body>
</html>
Step 6: Run the Application
Back in the terminal, run your Flask application:
python app.py
Visit http://localhost:5000
in your web browser, and you should see your simple web application displaying the welcome message.
Step 7: Deactivate Virtual Environment
When you’re done working on your project, deactivate the virtual environment:
deactivate
Congratulations! You’ve built a simple web application using Flask. This example serves as a starting point, and you can expand and customize it by adding more routes, views, and templates based on your application’s requirements. Additionally, you can explore integrating databases, handling forms, and incorporating more advanced features as you progress in your web development journey.