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, result, result) foo.bar = Bar(result, result, result) # 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!