Building a Simple Web Application with Flask
🌐 Building a Simple Web Application with Flask
Flask is a lightweight and flexible Python web framework that's great for building web applications and APIs quickly.
🛠️ Prerequisites
Before you start, make sure you have:
Python installed
pip package manager
Install Flask:
bash
Copy
Edit
pip install flask
🧱 Step-by-Step: Build a Simple Flask Web App
1. Create a Flask App File
Create a new file called app.py:
python
Copy
Edit
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
This creates a basic Flask app that serves a homepage at /.
2. Add a Template File
Create a folder named templates, and inside it, create index.html:
html
Copy
Edit
<!-- templates/index.html -->
<!DOCTYPE html>
<html>
<head>
<title>My Flask App</title>
</head>
<body>
<h1>Hello from Flask!</h1>
</body>
</html>
Flask automatically looks for HTML templates in a folder called templates.
3. Run the App
In your terminal:
bash
Copy
Edit
python app.py
Then open your browser and go to:
http://localhost:5000
You should see:
"Hello from Flask!"
🔁 Add More Routes
You can add more pages with additional routes:
python
Copy
Edit
@app.route('/about')
def about():
return '<h2>This is the About Page</h2>'
💬 Handling Forms
Let’s add a basic form:
1. Update index.html:
html
Copy
Edit
<form method="POST" action="/greet">
<input type="text" name="name" placeholder="Enter your name" />
<button type="submit">Greet Me</button>
</form>
2. Add the route in app.py:
python
Copy
Edit
from flask import request
@app.route('/greet', methods=['POST'])
def greet():
name = request.form.get('name')
return f'<h2>Hello, {name}!</h2>'
📁 Project Structure Summary
bash
Copy
Edit
/your-project-folder
│
├── app.py
└── templates/
└── index.html
🧰 Flask Features You Can Add Next
Templates with Jinja2 (loops, conditions)
Static files (CSS, JS)
Routing with URL parameters
Form handling and validation
Connecting to a database (SQLite, PostgreSQL, etc.)
REST API with Flask-RESTful
✅ Final Thoughts
Flask is a perfect tool for:
Rapid prototyping
Personal or small-scale apps
Learning web development basics
Once you're comfortable, you can explore:
Flask Blueprints (for larger apps)
Flask extensions (e.g., for login, databases)
Deploying to cloud platforms (like Heroku or Vercel)
Would you like a downloadable starter template or a tutorial for turning this into a REST API or blog app?
Learn Full Stack Python Course in Hyderabad
Read More
Backend Development with Python
Understanding Flask for Full Stack Development
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment