Implementing Authentication with Databases in Python
Implementing authentication with databases in Python typically involves a combination of:
A Python web framework (e.g., Flask or Django)
A database (e.g., SQLite, PostgreSQL, MySQL)
Password hashing (for secure storage)
Session or token-based authentication (for tracking logged-in users)
Here's a complete beginner-friendly guide using Flask and SQLite:
✅ Step-by-Step: Authentication with Flask & SQLite
🔧 1. Setup Your Environment
Install dependencies:
bash
Copy
Edit
pip install flask flask_sqlalchemy werkzeug
🏗️ 2. Create Project Structure
cpp
Copy
Edit
project/
│
├── app.py
├── models.py
└── templates/
├── login.html
├── register.html
└── dashboard.html
🧱 3. Database & User Model — models.py
python
Copy
Edit
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
db = SQLAlchemy()
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(150), unique=True, nullable=False)
password_hash = db.Column(db.String(256), nullable=False)
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
🚀 4. Flask App Logic — app.py
python
Copy
Edit
from flask import Flask, render_template, request, redirect, session, url_for
from models import db, User
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your_secret_key_here'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'
db.init_app(app)
@app.before_first_request
def create_tables():
db.create_all()
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if User.query.filter_by(username=username).first():
return 'Username already exists.'
user = User(username=username)
user.set_password(password)
db.session.add(user)
db.session.commit()
return redirect(url_for('login'))
return render_template('register.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
user = User.query.filter_by(username=request.form['username']).first()
if user and user.check_password(request.form['password']):
session['user_id'] = user.id
return redirect(url_for('dashboard'))
return 'Invalid credentials'
return render_template('login.html')
@app.route('/dashboard')
def dashboard():
if 'user_id' not in session:
return redirect(url_for('login'))
return render_template('dashboard.html')
@app.route('/logout')
def logout():
session.pop('user_id', None)
return redirect(url_for('login'))
if __name__ == '__main__':
app.run(debug=True)
🧾 5. Example Templates (HTML)
register.html
html
Copy
Edit
<form method="POST">
<input name="username" placeholder="Username" required>
<input name="password" type="password" placeholder="Password" required>
<button type="submit">Register</button>
</form>
login.html
html
Copy
Edit
<form method="POST">
<input name="username" placeholder="Username" required>
<input name="password" type="password" placeholder="Password" required>
<button type="submit">Login</button>
</form>
dashboard.html
html
Copy
Edit
<h1>Welcome to the dashboard!</h1>
<a href="{{ url_for('logout') }}">Logout</a>
🔐 Key Security Tips
Always hash passwords using werkzeug.security or bcrypt.
Use HTTPS in production to protect credentials.
Use session-based or token-based auth (e.g., JWT for APIs).
Set a strong SECRET_KEY in Flask for session protection.
Learn Full Stack Python Course in Hyderabad
Read More
Using Django ORM to Interact with Databases
How to Connect Python with SQL Databases
Setting Up PostgreSQL for Full Stack Python Projects
SQL vs NoSQL: What’s Best for Full Stack Python Development?
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment