You can download this code by clicking the button below.
This code is now available for download.
The code includes functions for creating a database model, adding a user, retrieving a user by email, updating a user's email, and deleting a user. It is suitable for developers with some experience in Flask and SQLAlchemy.
Technology Stack : Flask, SQLAlchemy, SQLite
Code Type : The type of code
Code Difficulty : Intermediate
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
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 add_user(username, email):
new_user = User(username=username, email=email)
db.session.add(new_user)
db.session.commit()
def get_user_by_email(email):
return User.query.filter_by(email=email).first()
def update_user_email(user_id, new_email):
user = User.query.get(user_id)
if user:
user.email = new_email
db.session.commit()
def delete_user(user_id):
user = User.query.get(user_id)
if user:
db.session.delete(user)
db.session.commit()