Creating a Web App CRUD with Flask, SqlAlchemy and SQLite

Flask is a microweb framework for python really useful and easy to implement many times of system, let’s create a webapp using these free useful tools and create our local database.

1- First let’s create a virtual enviroment using Miniconda

2 – Install the dependencies:

3- Creating our Web App

3.1 – Creating our Models:

3.1.1 – Let’s create our __init__.py to start our Flask App and set the configuration for our SQLite:

import osfrom flask import Flaskfrom flask_sqlalchemy import SQLAlchemyapp = Flask(__name__)dir_db = "database.db"app.config["SQLALCHEMY_DATABASE_URI"] = f"sqlite:////data/{dir_db}"app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = Truedb = SQLAlchemy(app)

3.1.2 – Let’s create our class that gonna be translate in our database table in a few minutes:

import osfrom web_app import app, dbfrom uuid import uuid4class Base(db.Model):    __abstract__ = True    id = db.Column(db.String(36), primary_key=True, default=lambda: str(uuid4()))    created_at = db.Column(db.DateTime, default=db.func.current_timestamp())    updated_at = db.Column(        db.DateTime,        default=db.func.current_timestamp(),        onupdate=db.func.current_timestamp(),    )class User(Base):    name = db.Column(db.String(128))    def __repr__(self):        return "<User %r>" % self.name

3.1.3 – Let’s create a function to fake some data using Faker to be a good example 😉

from faker import Fakerfaker = Faker()def get_names(num_exemples = 1):    names = []    for x in range(0,num_exemples):        names.append({"name": faker.name()})    return names

3.1.4 – Now let’s create our app.py to create the RESTUrl’s of our web app to:

  • Home Page;
  • Fake some data to our new database @app.route(“/fake-data”);
  • Truncate our database @app.route(“/truncate-db”);
  • Start a new fresh installation of our database and tables @app.before_first_request
import osfrom web_app import app, db, modelsfrom flask_migrate import Migratefrom data.mock_data import get_names"""    First route to the home app"""@app.route("/")def main():    return "Hello world Web App""""    Get fake data with specific number of exemples and insert it into database"""@app.route("/fake-data")def get_fake_data(numbers=10):    lst_names_fake = get_names(numbers)    for n in lst_names_fake:        print(n["name"])        usr = models.User(name=n["name"])        db.session.add(usr)        db.session.commit()    print(models.User.query.all())    return usr.name"""Truncate database to clean all the tables and data and recreate everything"""@app.route("/truncate-db")def delete_data_db(recreate=True):    db.drop_all()    db.session.commit()    if recreate:        db.create_all()    return "All the database is truncated!""""    Before to start the app we have to create all the database structure"""@app.before_first_requestdef before_first_request():    # from flask_migrate import Migrate    app.logger.info("Creating the Database and all tables necessaries")    db.create_all()

Voila! almost done! let’s try it!

export FLASK_APP=app.py export FLASK_ENV=developmentflask run --reload

After our first run with sucess we can check the path of our database and check our tables:

Done! now we can try our URL’s to check the functions:

http://localhost:5000

http://localhost:5000/fake-data

http://localhost:5000/truncate-db

Let’s see our database with our user table and our gourgeous data 🙂

Good! check the complete code on my GITHUB!

Post a Comment

Previous Post Next Post