SQLAlchemy 1.4 / 2.0 support for aiohttp.
Project description
SQLAlchemy 1.4 / 2.0 support for aiohttp.
The library provides the next features:
forwarding SQLAlchemy asynchronous sessions for function handlers, class organized handlers, and class based view methods;
a middleware factory sa_middleware(key: str = 'sa_main')' for forwarding sessions as request[key] for all your request handlers;
a decorator sa_decorator(key: str = 'sa_main') for forwarding sessions as request[key] for your chosen handlers;
a parent class SAView for forwarding sessions as SAView.sa_session(key: str = 'sa_main') method.
Documentation
Installation
pip install aiohttp-sqlalchemy
Simple example
Install aiosqlite for work with sqlite3:
pip install aiosqlite
Copy and paste this code in a file and run:
from aiohttp import web
import aiohttp_sqlalchemy
from aiohttp_sqlalchemy import sa_bind
from datetime import datetime
import sqlalchemy as sa
from sqlalchemy import orm
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
metadata = sa.MetaData()
Base = orm.declarative_base(metadata=metadata)
class MyModel(Base):
__tablename__ = 'my_table'
id = sa.Column(sa.Integer, primary_key=True)
timestamp = sa.Column(sa.DateTime(), default=datetime.now)
async def main(request):
async with request['sa_main'].bind.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
async with request['sa_main'].begin():
request['sa_main'].add_all([MyModel()])
result = await request['sa_main'].execute(sa.select(MyModel))
data = {r.id: r.timestamp.isoformat() for r in result.scalars()}
return web.json_response(data)
app = web.Application()
engine = create_async_engine('sqlite+aiosqlite:///')
Session = orm.sessionmaker(engine, AsyncSession)
aiohttp_sqlalchemy.setup(app, [sa_bind(Session)])
app.add_routes([web.get('/', main)])
if __name__ == '__main__':
web.run_app(app)
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 aiohttp_sqlalchemy-0.9.3-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 38076511a2f62b3e63e445bbf35df06bb13aa3453e91e344b53e4603b94f6943 |
|
MD5 | 4e6230baad81a8873dd7b824a5757d74 |
|
BLAKE2b-256 | 48c0463c58e65cbf0650a53409b9a83a5c20a2bd01d481b257418be2566a0f13 |