Creating Web Applications with Flask
Posted on June 1, 2024 (Last modified on June 8, 2024) • 2 min read • 293 wordsGet started with web development in Python using the Flask framework, including routing, templates, and handling forms.
Flask is a lightweight web framework for Python. This guide covers the basics of web development using Flask, including routing, templates, and handling forms.
First, install Flask.
pip install flask
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, Flask!"
if __name__ == '__main__':
app.run(debug=True)
A basic Flask application setup.
@app.route('/about')
def about():
return "About Page"
Define routes to handle different endpoints.
@app.route('/user/<name>')
def user(name):
return f"Hello, {name}!"
Handling URL parameters in routes.
from flask import render_template
@app.route('/')
def home():
return render_template('home.html')
# home.html
<!doctype html>
<html>
<head><title>Home</title></head>
<body>
<h1>Hello, Flask!</h1>
</body>
</html>
Rendering templates using Jinja2.
# base.html
<!doctype html>
<html>
<head><title>{% block title %}{% endblock %}</title></head>
<body>
{% block content %}{% endblock %}
</body>
</html>
# home.html
{% extends 'base.html' %}
{% block title %}Home{% endblock %}
{% block content %}
<h1>Hello, Flask!</h1>
{% endblock %}
Using template inheritance to create a base template.
from flask import request
@app.route('/submit', methods=['GET', 'POST'])
def submit():
if request.method == 'POST':
name = request.form['name']
return f"Hello, {name}!"
return '''
<form method="post">
Name: <input type="text" name="name">
<input type="submit">
</form>
'''
Handling form submissions in Flask.
@app.route('/submit', methods=['GET', 'POST'])
def submit():
if request.method == 'POST':
name = request.form['name']
if not name:
return "Name is required!"
return f"Hello, {name}!"
return '''
<form method="post">
Name: <input type="text" name="name">
<input type="submit">
</form>
'''
Adding validation to form data.
Flask is a powerful yet lightweight framework for web development in Python. Practice setting up routes, using templates, and handling forms to build web applications with Flask.