A quick way to run SQL in your Flask app.
Project description
flask-quick-sql
A quick way to run SQL in your Flask app.
Info
A long time ago, I used the records
library to query a database
with raw SQL. It was great, until it wasn't.
Fast-forward many years and I was working on replacing the code that used records
, but I needed to keep
the existing code working. I also needed to remove records
from my dependencies in order to update
literally everything, but alas, I could not.
Enter this little wrapper code I wrote. It kinda keeps API compat but also kinda not. That wasn't my goal. My goal was to keep enough compatibility so I wouldn't have to change much of my code while also keeping it nice to use.
This Flask extension exists solely because I liked my wrapper code and will almost certainly will have a use for it again, and I didn't want it to just go away when I deleted it from my app.
Usage
- Python 3.10+
- Flask 2.2+
- Flask-SQLAlchemy 3.0+
- SQLAlchemy 2.0+
If a SQLAlchemy instance already exists in your app, it will be used. Otherwise, an instance will be created for you.
from flask import Flask
from flask_quick_sql import QuickSQL
def create_app():
app = Flask(__name__)
# You must set this
app.config["SQLALCHEMY_DATABASE_URI"] = ...
db = QuickSQL(app)
# A very wasteful yet all too common query, especially in PHP land
all_users = db.query("SELECT * FROM users").all()
print(all_users[0]["username"])
return app
The immediate result of query()
isn't very useful. You'll want to chain a call to .all()
, .first()
,
or .one()
. If there's no data, .first()
and .one()
will return None
.
You don't get property and key access like records
gave you. You get one or the other.
By default, you get a dictionary. Breaking API change from records
? Yes. I don't care.
To get a sqlalchemy.engine.Row
(basically collections.namedtuple
) object instead,
pass as_nt=True
as a parameter to any method.
You can also iterate over the whole result set, with each dictionary record being yield
ed
(you cannot get a named tuple when doing this):
[User(**r) for r in quick_sql.query("SELECT * FROM users")]
Because SQLAlchemy is used under the hood, prepared statements work as expected:
sql = "SELECT * FROM users WHERE is_active = :is_active"
[User(**r) for r in db.query(sql, is_active=False)]
Have fun running your SQuirreL queries.
License
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for flask_quick_sql-1.0.2-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 66c155c81acc424d69c8d1347deba4709c4b9edbc3a01eb17c6ea08a80a95340 |
|
MD5 | be2535fb7f3ac733e6991ece4309d328 |
|
BLAKE2b-256 | ef1ddab0d9c94a4a926422620c35f042e815640dd08da1923bf774a5c7ac877c |