【问题标题】:FASTAPI run in conjunction with Alembic, but autogenerate does not detect the modelsFASTAPI 与 Alembic 一起运行,但自动生成不检测模型
【发布时间】:2022-02-01 21:09:29
【问题描述】:

我对 FASTAPI 比较陌生,但决定使用 Postgres 和 Alembic 建立一个项目。每次我使用自动迁移时,我都设法让迁移创建新版本,但由于某种原因,我没有从我的模型中获得任何更新,因为它们保持空白。我有点不知道出了什么问题。

main.py

from fastapi import FastAPI
import os
app = FastAPI()


@app.get("/")
async def root():
    return {"message": os.getenv("SQLALCHEMY_DATABASE_URL")}


@app.get("/hello/{name}")
async def say_hello(name: str):
    return {"message": f"Hello {name}"}

数据库.py

from sqlalchemy import  create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import os

SQLALCHEMY_DATABASE_URL = os.getenv("SQLALCHEMY_DATABASE_URL")

engine = create_engine("postgresql://postgres:mysuperpassword@localhost/rodney")
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()

def get_db():
    db = SessionLocal()
    try:
        yield db
    except:
        db.close()

目前为止我唯一的模特

from sqlalchemy import Integer, String
from sqlalchemy.sql.schema import Column
from ..db.database import  Base


class CounterParty(Base):
    __tablename__ = "Counterparty"

    id = Column(Integer, primary_key=True)
    Name = Column(String, nullable=False)

env.py (alembic)

from logging.config import fileConfig

from sqlalchemy import engine_from_config
from sqlalchemy import pool

from alembic import context

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config

# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)

# add your model's MetaData object here
# for 'autogenerate' support
from app.db.database import Base
target_metadata = Base.metadata

# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.


def run_migrations_offline():
    """Run migrations in 'offline' mode.

    This configures the context with just a URL
    and not an Engine, though an Engine is acceptable
    here as well.  By skipping the Engine creation
    we don't even need a DBAPI to be available.

    Calls to context.execute() here emit the given string to the
    script output.

    """
    url = config.get_main_option("sqlalchemy.url")
    context.configure(
        url=url,
        target_metadata=target_metadata,
        literal_binds=True,
        dialect_opts={"paramstyle": "named"},
    )

    with context.begin_transaction():
        context.run_migrations()


def run_migrations_online():
    """Run migrations in 'online' mode.

    In this scenario we need to create an Engine
    and associate a connection with the context.

    """
    connectable = engine_from_config(
        config.get_section(config.config_ini_section),
        prefix="sqlalchemy.",
        poolclass=pool.NullPool,
    )

    with connectable.connect() as connection:
        context.configure(
            connection=connection, target_metadata=target_metadata
        )

        with context.begin_transaction():
            context.run_migrations()


if context.is_offline_mode():
    run_migrations_offline()
else:
    run_migrations_online()

现在,当我运行“alembic revision --autogenerate -m “initial setup””时,Alembic 会创建大量迁移

我的文件夹结构

如果有人有任何想法,我会非常感激。干杯!

【问题讨论】:

  • 你没有从模型中得到任何输出,对吧?
  • 不,不知何故无法识别我的模型。虽然我从 db.database 和 env.py 导入 Base 我设置 target_metadata = Base.metadata
  • 是的,对我来说,我也遇到了这个问题。希望我的案例可以帮助您了解您的案例中的问题。我使用 ML 模型通过 FastApi 进行部署。让我解释一下

标签: python fastapi alembic


【解决方案1】:

在我的例子中,我使用 Transformer BERT 模型部署在 FastApi 上,但 fastapi 无法识别我的模型,也无法获取模型输入和输出。 我用于案例的代码:

from fastapi import FastAPI
from pydantic import BaseModel

class Entities(BaseModel):
    text: str

class EntitesOut(BaseModel):
    headings: str
    Probability: str
    Prediction: str

model_load = load_model('BERT_HATESPEECH')
tokenizer = DistilBertTokenizerFast.from_pretrained('BERT_HATESPEECH_TOKENIZER')
file_to_read = open("label_encoder_bert_hatespeech.pkl", "rb")
label_encoder = pickle.load(file_to_read)

app = FastAPI()

@app.post('/predict', response_model=EntitesOut)
def prep_data(text:Entities):
    text = text.text
    tokens = tokenizer(text, max_length=150, truncation=True, 
                       padding='max_length', 
                       add_special_tokens=True, 
                       return_tensors='tf')
    tokens = {'input_ids': tf.cast(tokens['input_ids'], tf.float64), 'attention_mask': tf.cast(tokens['attention_mask'], tf.float64)}
    headings = '''Non-offensive', 'identity_hate', 'neither', 'obscene','offensive', 'sexism'''
    probs = model_load.predict(tokens)[0]
    pred = label_encoder.inverse_transform([np.argmax(probs)])
    return {"headings":headings,
            "Probability":str(np.round(probs,3)),
            "Prediction":str(pred)}

上面的代码使用了 pydantic 的 BaseModel,我为 baseModel 创建了类来获取 text:str as input 和 headings, Probability, and prediction as Outputs in EntitiesOut class 之后它以某种方式被模型识别并保存 200 个状态代码并输出

【讨论】:

  • 感谢您的代码 sn-p。看着你的代码,我意识到也许它可以找到它,因为它在 1 个文件中。我不明白为什么它会突然通过在文件中添加一个 DTO 作为方案来工作。但它确实触发了我在我的 env.py 文件中导入方案和模型。事实证明,我明确需要将模型导入数据库才能识别我的模型。所以你的代码仍然为我指明了正确的方向。谢谢老兄。
  • 这个答案有什么用?我在上面代码的上下文中没有看到 sqlalchemy。
  • 模型无法识别他的输出。这是通过添加类或 json 语法来完成的。
【解决方案2】:

env.py 文件找不到模型,因为您没有导入它们。一种解决方案,您只需将它们立即导入到您的 env.py 文件中:

从 ..models 导入 *

但是,您需要在模型目录中有一个 init.py 文件,并在其中包含所有模型。

另一种方式(不过不推荐):如果你只有一个模型,可以直接导入为:

从 ..models.counterPartyModel 导入

【讨论】:

    猜你喜欢
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    • 2019-03-10
    • 2013-05-25
    • 1970-01-01
    • 2020-09-21
    相关资源
    最近更新 更多