Bootstrap FreeKB - Flask - Determine if a table exists using SQLAlchemy
Flask - Determine if a table exists using SQLAlchemy

Updated:   |  Flask articles

If you are not familiar with SQLAlchemy, check out my article Getting Started with SQLAlchemy.

Flask uses the MVC (Model View Controller) Framework. Just to make this as obvious as possible, I like my Flask apps to have the following.

  • Model -> models.py
  • View -> views.py
  • Controller -> __init__.py

And let's say your Flask app has the following structure.

├── main.py
├── database (directory)
│   ├── example.db
├── my-project (directory)
│   ├── __init__.py
│   ├── views.py
│   ├── models.py
│   ├── templates (directory)
│   │   ├── base.html
│   │   ├── home.html
│   │   ├── results.html
│   └── static (directory)
│       └── custom.css

 

Often, the logic for the initial setup of the database is placed in __init__.py. Here is how you can determine if SQLite table exists.

  • create_engine and MetaData are used to determine if the SQLite table exists
  • sqlite followed by 3 forward slashes means relative path or present working directory (e.g. sqlite:///example.db). In this scenario, the example.db file would need to be in the same directory as the __init__.py file.
  • sqlite followed by 4 forward slashes means full or absolute path (e.g. sqlite:////usr/local/flask/database/example.db)
  • Let's say you have example.db on a network share and on your Windows PC you map a network drive resulting in something like Z:/example.db. In this scenario, you would use 3 forward slashes followed by the mapped network drive (e.g. sqlite:///Z:/example.db). This would probably only be done on your PC for local testing and development purposes.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine, MetaData
from sqlalchemy import func, exc

db = SQLAlchemy()

def app_obj():
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    db.init_app(app)

    try:
        engine = create_engine("sqlite:///example.db")
    except exc.SQLAlchemyError as sqlalchemyerror:
        print(f"got the following SQLAlchemyError: {sqlalchemyerror}")
    except Exception as exception:
        print(f"got the following Exception: {exception}")

    metadata = MetaData()
    metadata.reflect(bind=engine)
    my_table = metadata.tables['my_table']

    if my_table is None:
        print(f"my_table does not exist")
    else:
        print(f"my_table exists)

    return app

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 75325d in the box below so that we can be sure you are a human.