Last active
January 12, 2021 12:10
-
-
Save Icebreaker454/e22ca806f4b8427f5560277cc32735b7 to your computer and use it in GitHub Desktop.
SQLAlchemy 1.4 test script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import sqlalchemy as sa | |
from sqlalchemy import select | |
from sqlalchemy.ext.declarative import declarative_base, declared_attr | |
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession | |
postgresql_url = "postgresql+asyncpg://localhost:5432/test_sqlalchemy_db" | |
engine = create_async_engine(postgresql_url, echo=True) | |
class CustomBase: | |
@declared_attr | |
def __tablename__(cls): # noqa | |
return cls.__name__.lower() | |
@declared_attr | |
def id(cls): # noqa | |
return sa.Column(sa.Integer, primary_key=True) | |
Base = declarative_base(cls=CustomBase) | |
class User(Base): | |
username = sa.Column(sa.String) | |
email = sa.Column(sa.String) | |
async def main(): | |
async with engine.begin() as conn: | |
await conn.run_sync(Base.metadata.create_all) | |
async with AsyncSession(engine) as session: | |
async with session.begin(): | |
user = User(username="john_smith") | |
session.add(user) | |
# Here we re-fetch the same user | |
stmt = select(User).filter_by(username="john_smith") | |
cursor = await session.execute(stmt) | |
user = cursor.scalar() | |
# Modify some attrs | |
user.email = "jsmith@gmail.com" | |
await session.commit() | |
# Here goes the greenlet_spawn issue | |
print(user.username) | |
async with engine.begin() as conn: | |
await conn.run_sync(Base.metadata.drop_all) | |
if __name__ == '__main__': | |
asyncio.run(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Traceback after line 52: