SQLAlchemy Code Generation

If you'd like to start using SQLAlchemy with an existing database, you can have SQLACodeGen connect to your database and write the declarative classes for you. It's a huge time saver.

On Ubuntu, you can install both of the above (for Python 3) as follows:

pip3 install sqlalchemy
pip3 install sqlacodegen

Then, you can generate your Python code by running:

sqlacodegen postgresql://postgres:mydbpassword@localhost/mydb --outfile db.py

Here's an example of sample output:

# coding: utf-8
from sqlalchemy import Column, DateTime, Integer, String, text
from sqlalchemy.ext.declarative import declarative_base


Base = declarative_base()
metadata = Base.metadata


class Link(Base):
    __tablename__ = 'links'

    id = Column(Integer, primary_key=True, server_default=text("nextval('links_id_seq'::regclass)"))
    parent_id = Column(Integer)
    url = Column(String, nullable=False)
    html = Column(String)
    date_entered = Column(DateTime(True), nullable=False, server_default=text("now()"))
    status = Column(Integer, nullable=False, default=0)
    error_code = Column(Integer)

Now you can write some Python to use SQLAlchemy with the code above:

from sqladb import Link
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

engine = create_engine('postgresql://postgres:mypassword@localhost:5432/mydb')
engine.connect()
Session = sessionmaker(bind=engine)
session = Session()

link = Link()
link.url = "https://duckduckgo.com"

session.add(link)
session.commit()

This will create an instance of the Link class and insert a record into the database.

Comments

Leave a comment

What color are green eyes? (spam prevention)
Submit
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.