英文:
How can I fix 'greenlet_spawn has not been called' error when using async_sessionmaker with FastAPI and SQLAlchemy?
问题
FastAPI + SQLAlchemy + Alembic + async_sessionmaker 不工作
当运行 "alembic revision --autogenerate" 时,我收到一个错误消息 'sqlalchemy.exc.MissingGreenlet: greenlet_spawn has not been called; can't call await_only() here. Was IO attempted in an unexpected place?'
为什么这不起作用?
db.py:
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from core.config import config
Base = declarative_base()
engine = create_async_engine(config.DB_URL)
async_session = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
model - user.py:
from sqlalchemy import String
from sqlalchemy.orm import Mapped, mapped_column
from core.db.session import Base
class User(Base):
__tablename__ = 'users'
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String)
env.py
from core.config import config as app_config
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
config = context.config
context.config.set_main_option('sqlalchemy.url', app_config.DB_URL)
if config.config_file_name is not None:
fileConfig(config.config_file_name)
from app.user.models.user import *
from core.db.session import Base
target_metadata = Base.metadata
...
英文:
FastAPI + SQLAlchemy + Alembic + async_sessionmaker not working
When "alembic revision --autogenerate' I get an error 'sqlalchemy.exc.MissingGreenlet: greenlet_spawn has not been called; can't call await_only() here. Was IO attempted in an unexpected place?'
why doesn't this work?
db.py:
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from core.config import config
Base = declarative_base()
engine = create_async_engine(config.DB_URL)
async_session = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
model - user.py:
from sqlalchemy import String
from sqlalchemy.orm import Mapped, mapped_column
from core.db.session import Base
class User(Base):
__tablename__ = 'users'
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String)
env.py
from core.config import config as app_config
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
config = context.config
context.config.set_main_option('sqlalchemy.url', app_config.DB_URL)
if config.config_file_name is not None:
fileConfig(config.config_file_name)
from app.user.models.user import *
from core.db.session import Base
target_metadata = Base.metadata
...
答案1
得分: 0
初始化 Alembic 并使用异步迁移解决此问题。
英文:
alembic init -t async migrations
resolve this problem
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论