Flask is a lightweight Python web framework that helps you build web applications quickly. Known for its simplicity and flexibility, Flask is perfect for beginners as well as experienced developers.
What is Flask?
Flask is called a micro web framework because it doesn’t include certain features like a database layer, form validation, or authentication by default. Instead, you can add what you need with external libraries. This makes Flask lightweight, easy to understand, and highly flexible.
Setting Up Flask
Before we start, ensure Python is installed on your system. Then, install Flask via pip:
pip install flask
Your First Flask Application
Create a file called app.py and add the following code:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True, port=5000)
-
Save and run the file with
python app.py. -
Open your browser and go to http://127.0.0.1:5000/ to see "Hello, World!"
Understanding the Code
-
Importing Flask:
from flask import Flask
Imports the Flask class to create your app.
-
Creating an App Instance:
app = Flask(__name__)
__name__ helps Flask locate resources like templates.
-
Route Decorator:
@app.route('/')
Defines the URL path that triggers a function.
-
View Function:
def hello_world():
return 'Hello, World!'
The function returns content to display in the browser.
-
Running the App:
app.run(debug=True, port=5000)
-
debug=Trueenables auto-reload and helpful error messages. -
port=5000specifies the port number.
Custom Host and Port
You can run Flask on a different host and port:
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug=True)
-
host='0.0.0.0'→ makes it accessible on your network. -
port=8080→ changes the default port from 5000.
Adding More Routes
You can define multiple routes:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 'Home Page'
@app.route('/user/<username>')
def show_user_profile(username):
return f'User: {username}'
@app.route('/post/<int:post_id>')
def show_post(post_id):
return f'Post {post_id}'
if __name__ == '__main__':
app.run(debug=True, port=3000)
-
/user/<username>→ captures a string variable from URL. -
/post/<int:post_id>→ captures an integer. Non-integer values return a 404.
Rendering HTML Templates
Flask uses Jinja2 to render HTML templates.
-
Create a folder called
templatesand a fileindex.html:
<!DOCTYPE html>
<html>
<head>
<title>My Flask App</title>
</head>
<body>
<h1>Hello, {{ name }}!</h1>
<p>Welcome to my Flask application.</p>
</body>
</html>
-
Update your Flask code:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html', name='Visitor')
@app.route('/user/<username>')
def show_user_profile(username):
return render_template('index.html', name=username)
if __name__ == '__main__':
app.run(debug=True, port=5001)
-
Pass variables from Flask to the template with
{{ variable_name }}. -
Flask automatically looks for HTML files in the
templatesfolder.
Handling HTTP Methods
Flask can handle GET and POST requests:
from flask import Flask, request
app = Flask(__name__)
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
return f'Logged in as {username}'
return '''
<form method="post">
<p><input type="text" name="username" placeholder="Username"></p>
<p><input type="password" name="password" placeholder="Password"></p>
<p><input type="submit" value="Login"></p>
</form>
'''
if __name__ == '__main__':
app.run(debug=True, port=8000)
Redirects and URLs
from flask import Flask, redirect, url_for
app = Flask(__name__)
@app.route('/')
def index():
return 'Home Page'
@app.route('/admin')
def admin():
return 'Admin Page'
@app.route('/user/<username>')
def profile(username):
return f'Hello {username}'
@app.route('/login/<name>')
def login(name):
if name == 'admin':
return redirect(url_for('admin'))
return redirect(url_for('profile', username=name))
if __name__ == '__main__':
app.run(debug=True, port=9000)
-
redirect()→ redirects the user. -
url_for()→ generates URLs dynamically.
Handling Errors
Create custom error pages:
from flask import Flask, render_template
app = Flask(__name__)
@app.errorhandler(404)
def page_not_found(error):
return render_template('404.html'), 404
@app.errorhandler(500)
def internal_error(error):
return render_template('500.html'), 500
if __name__ == '__main__':
app.run(debug=True, port=5002)
templates/404.html:
<!DOCTYPE html>
<html>
<head>
<title>Page Not Found</title>
</head>
<body>
<h1>Oops! Page not found.</h1>
<p>The page you're looking for doesn't exist.</p>
</body>
</html>
Using Static Files
Project structure:
/myapp
/templates
/static
/css
/js
/images
app.py
Reference static files in templates:
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<script src="{{ url_for('static', filename='js/script.js') }}"></script>
<img src="{{ url_for('static', filename='images/logo.png') }}" alt="Logo">
Cookies and Sessions
from flask import Flask, request, make_response, session
app = Flask(__name__)
app.secret_key = 'your-secret-key'
@app.route('/set-cookie')
def set_cookie():
resp = make_response('Cookie set!')
resp.set_cookie('username', 'john-doe', max_age=60*60*24)
return resp
@app.route('/login-session')
def login_session():
session['username'] = 'john-doe'
return 'Logged in!'
@app.route('/get-session')
def get_session():
username = session.get('username', 'Guest')
return f'Hello {username}'
if __name__ == '__main__':
app.run(debug=True, port=5003)
Database Integration with Flask-SQLAlchemy
Install the extension:
pip install flask-sqlalchemy
Example usage:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
def __repr__(self):
return f'<User {self.username}>'
@app.route('/')
def index():
users = User.query.all()
return f'There are {len(users)} users in the database.'
if __name__ == '__main__':
with app.app_context():
db.create_all()
app.run(debug=True, port=5004)
Running Flask via Command Line
export FLASK_APP=app.py # Windows: set FLASK_APP=app.py
export FLASK_ENV=development
flask run --host=0.0.0.0 --port=8080
Conclusion
Flask is lightweight, simple, and flexible, making it perfect for building small to medium web applications.
Next steps for advanced learning:
-
Flask-WTF → Form handling
-
Flask-Login → Authentication
-
Flask-Mail → Sending emails
-
Flask-RESTful → APIs
🔹 9. Try it Yourself!
You can run the codes here and practice:
Happy coding with Flask! 🚀
No comments:
Post a Comment