You can download this code by clicking the button below.
This code is now available for download.
The function `create_user_table` takes an SQLAlchemy engine as an argument. The function first checks if the database exists, and if not, it creates a new database and uses `Base.metadata.create_all(engine)` to create the table structure.
Technology Stack : SQLAlchemy, SQLAlchemy-Utils, Python
Code Type : Function
Code Difficulty : Intermediate
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from sqlalchemy_utils import database_exists, create_database
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
def create_user_table(engine):
if not database_exists(engine.url):
create_database(engine.url)
Base.metadata.create_all(engine)