How to Build a Web App using Flask and SQLite in Python
0 1890
Introduction to Building a Web App Using Flask and SQLite in Python
Flask is a popular micro web framework in Python known for its simplicity and flexibility. When combined with SQLite, a lightweight and serverless database, it becomes easy to build small to medium scale web applications quickly. This guide will walk you through the process of creating a web app using Flask and SQLite, demonstrating how to manage data seamlessly.
Prerequisites
Before starting, ensure you have Python installed on your system. You will also need to install Flask using pip if it’s not already installed:
pip install Flask
SQLite comes pre-installed with Python, so there’s no need for additional installation.
Setting Up the Flask Application
Create a new Python file, for example app.py, and start by importing the necessary modules and initializing the Flask app:
from flask import Flask, render_template, request, redirect, url_for
import sqlite3
app = Flask(__name__)
Creating and Connecting to SQLite Database
We’ll use SQLite to store our data. The database connection can be set up inside a function to keep things clean:
def get_db_connection():
conn = sqlite3.connect('database.db')
conn.row_factory = sqlite3.Row
return conn
This function connects to the SQLite database file named database.db. The row_factory helps to retrieve rows as dictionaries.
Initializing the Database
You need to create a table to hold the data. For this example, let’s create a simple users table:
def init_db():
conn = get_db_connection()
conn.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE
)
''')
conn.commit()
conn.close()
init_db()
Running this will create the table if it doesn’t exist yet.
Creating Routes for the Web Application
Now let’s add routes to display the home page, add a user, and list all users.
@app.route('/')
def index():
conn = get_db_connection()
users = conn.execute('SELECT * FROM users').fetchall()
conn.close()
return render_template('index.html', users=users)
@app.route('/add_user', methods=('GET', 'POST'))
def add_user():
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
if not name or not email:
return 'Name and Email are required!'
conn = get_db_connection()
conn.execute('INSERT INTO users (name, email) VALUES (?, ?)', (name, email))
conn.commit()
conn.close()
return redirect(url_for('index'))
return render_template('add_user.html')
Creating HTML Templates
Create a templates folder in your project directory. Inside it, add two files: index.html and add_user.html.
index.html
<!DOCTYPE html>
<html>
<head>
<title>User List</title>
</head>
<body>
<h1>Users</h1>
<a href="{{ url_for('add_user') }}">Add User</a>
<ul>
{% for user in users %}
<li>{{ user['name'] }} - {{ user['email'] }}</li>
{% endfor %}
</ul>
</body>
</html>
add_user.html
<!DOCTYPE html>
<html>
<head>
<title>Add User</title>
</head>
<body>
<h1>Add New User</h1>
<form method="POST">
<label for="name">Name:</label>
<input type="text" name="name" id="name" required><br>
<label for="email">Email:</label>
<input type="email" name="email" id="email" required><br>
<input type="submit" value="Add User">
</form>
<a href="{{ url_for('index') }}">Back to User List</a>
</body>
</html>
Running the Flask App
Save all files and run your Flask application by executing:
flask run
Visit http://127.0.0.1:5000/ in your browser to see the user list, and navigate to add users.
Conclusion
Using Flask with SQLite is a great way to develop simple and efficient web applications with minimal setup. This tutorial provided a clear path to creating a user management app, including database setup, routing, and template rendering. You can now expand this basic app by adding more features like editing users, deleting records, or incorporating user authentication.
If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!
Share:



Comments
Waiting for your comments