Gardening App: Change to SQLAlchemy ORM

I am switching to the SQLAlchemy ORM from SQLAlchemy Core. This will be my second change as I started with SQL statements. The main reason is to connect the Gardens and Plants tables in the database. I would like for the user to be able to delete a garden and be given the option to delete all plants in that garden. It is also easier to filter results using the ORM, however, I had to make some changes in order to format the data for json. Here is some sample code:

from flask import Flask, request
from sqlalchemy import create_engine, Column, String, Integer, and_
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
import json
engine = create_engine("postgresql+psycopg2://, echo=True)

Base = declarative_base()

app = Flask(__name__)


class Plants(Base):
__tablename__ = "plants"

id = Column(Integer, primary_key=True)
name = Column(String(length=50))
common_name = Column(String(length=50))
category = Column(String(length=50))
location = Column(String(length=50))
year = Column(Integer)
notes = Column(String(length=500))


class Gardens(Base):
__tablename__ = "gardens"

id = Column(Integer, primary_key=True)
name = Column(String(length=50))
notes = Column(String(length=500))


Base.metadata.create_all(engine)

Session = sessionmaker(bind=engine)
session = Session()


@app.route("/gardens", methods=["GET"])
def all_gardens():
results = session.query(Gardens).all()
garden_list = []
for result in results:
garden = {"id": result.id, "name": result.name, "notes": result.notes}
garden_list.append(garden)
return json.dumps(garden_list)


@app.route("/gardens/create", methods=["POST"])
def create_garden():
garden_name = request.form['name']
garden_notes = request.form['notes']
new_garden = Gardens(name=garden_name, notes=garden_notes)
session.add(new_garden)
session.commit()
return ''

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store