Extension for BlackSheep to use SQLAlchemy
Project description
BlackSheep-SQLAlchemy
Extension for BlackSheep that simplifies the use of SQLAlchemy in the web framework.
pip install blacksheep-sqlalchemy
How to use
from blacksheep.server import Application
from blacksheepsqlalchemy import use_sqlalchemy
app = Application()
use_sqlalchemy(app, connection_string="<CONNECTION_STRING>")
After registering SQLAlchemy, services are configured in the application, so they are automatically resolved in any request handler requiring a SQLAlchemy db connections or db sessions; for example:
@get("/api/countries")
async def get_countries(db_connection) -> List[CountryData]:
"""
Fetches the countries using a database connection.
"""
result = []
async with db_connection:
items = await db_connection.execute(text("SELECT * FROM country"))
for item in items.fetchall():
result.append(CountryData(item["id"], item["name"]))
return result
Services can be injected at any level of the resolution graph, so BlackSheep
and rodi
support out of the box the scenario of db connections or db sessions
referenced in the business logic but not directly by the front-end layer
(depending on programmers' preference and their notion of best practices when
building web apps).
Services can be injected in the following ways:
By alias | By type annotation | Value |
---|---|---|
db_connection | AsyncConnection | instance of AsyncConnection (scoped to web request) |
db_session | AsyncSession | instance of AsyncSession (scoped to web request) |
db_engine | AsyncEngine | instance of AsyncEngine (singleton) |
For example, using SQLite:
- requires driver:
pip install aiosqlite
- connection string:
sqlite+aiosqlite:///example.db
See the tests
folder for a working example using database migrations applied
with Alembic
, and a documented API that offers methods to fetch, create,
delete countries objects.
Note
BlackSheep is designed to be used in async
way, therefore this library
requires the use of an asynchronous driver.
References
Documentation
Please refer to the documentation website.
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 blacksheep-sqlalchemy-0.0.1a0.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | 1d1c1be73962c2b58cc626c30efa557bf038253f41c50403e8f2b6297b1ef9af |
|
MD5 | f93ffef1025046d2ea474c3570846320 |
|
BLAKE2b-256 | 50024b41f29e7c960d3adab8eb12ace9d8051642ae00705c4bcf01a063635a3c |
Hashes for blacksheep_sqlalchemy-0.0.1a0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 48e1281d70f6662da27a56b47aded99a4da8ef4e68acdb2aab3789f53f0b0018 |
|
MD5 | e131dd3bd88be9b632fd5845095d8e50 |
|
BLAKE2b-256 | 5b6d9da38f94177e30829c6e230d4cc4e59b1e9b8104d3d01c046d3cd656c662 |