Wrestling Flask and SQLAlchemy

February 27, 2021

This January, I spent two weeks wrestling with Flask and SQLAlchemy. In order for them to play nice together, you have to follow specific rules - rules that I spent two weeks figuring out and experimenting with. Fortunately, going down the rabbit hole was well worth it and I emerged a stronger, more confident programmer. I also emerged with two projects that I’m rather proud of. Let me tell you about them:

1. My First Python Package

First, I published a Python project called Flask-SQLAlchemy-bind. It’s kind of a knock-off much simpler version of Flask-SQLAlchemy. The key is it works and follows all the specifications of both Flask and SQLAlchemy. Check it out on PyPi or install it using `pip install flask-sqlalchemy-bind`.

2. A Blog Post Explaining it All

Second, I published a blog post on Medium titled “Under the Hood of Flask-SQLAlchemy.” The blog post explains how to add support for SQLAlchemy to your Flask app without the use of a third-party plugin. There aren’t many (if any?) tutorials out there so this is my attempt to bridge the gap and save the next man in line some effort and confusion.

Here’s an overview of what you’ll find in the post:

  1. A simplified explanation of the different parts of SQLAlchemy that you’ll need to set up in order for it to function properly in a web setting, such as how to scope a session and tie it to the lifespan of a request.
  2. Step by step walkthrough of how to write the code.
  3. Link to GitHub repository with an example flask site to show usage.
  4. Explanations of some tests I used to make sure everything was functioning properly.
  5. Answers to confusing questions such as whether to involve Flask’s G object

I’m extremely proud of this post—it took a lot of effort to distill my new-found knowledge into something readable. Figuring out how to pull an explanation from my brain and get it down on paper in a concise manner felt like pulling taffy.

Feedback is appreciated, I know I still have a lot to learn.