Flask web dev: MVC simplicity with SQLAlchemy

Flask web development tip number 2

18 Jun '16

Flask is a web microframework for Python. It’s small, but because it’s so easy to understand it’s also extremely extensible. No more bloat.

I’m hoping to share some tips from developing and deploying several large Flask applications, some which aren’t obvious from the documentation.

Tip 2: How I Learned to Stop Worrying and Love ORM

SQLAlchemy is a great Object Relational Mapper (ORM). Yeah, yeah, SQL and ORM, how 90s. But it works, so stop worrying about SQL and start building websites.

SQLAlchemy works great because it’s very transparent. So it doesn’t replace SQL knowledge, but augments it. That doesn’t mean it doesn’t get you nice features like portability over different SQL implementations, but write terrible models and queries and you’ll still get terrible performance.

SQLAlchemy cuts down on the littering of SQL throughout the codebase and wraps everything in models. When writing a view, which of these approaches would you rather do?

# raw SQL
result = execute('''SELECT
    foo.id,
    foo.name,
    foo.description,
    bar.id,
    bar.name,
    bar.description
FROM foo INNER JOIN bar ON (foo.bar_id = bar.id)
ORDER BY foo.name LIMIT 1''')
foo = Foo(result[0], result[1], result[2])
foo.bar = Bar(result[3], result[4], result[5])

# SQLAlchemy with relationship on model
foo = Foo.query.order_by(Foo.name).first()

We all know MVC is a good idea. Flask and SQLAlchemy make MVC painless. Do it.


Good luck with Flask and SQLAlchemy!

Python, Flask, SQLAlchemy

Newer Older