Как лучше всего вставить несколько строк в postgres из многопоточного приложения Python с помощью SQLAlchemy?Python

Программы на Python
Гость
Как лучше всего вставить несколько строк в postgres из многопоточного приложения Python с помощью SQLAlchemy?

Сообщение Гость »


Я использую SQLAlchemy для взаимодействия с postgres. Иногда (при самой высокой частоте запросов) исключение UniqueViolation возникает, когда я пытаюсь вставить строки в таблицу.
Вот часть моего кода:
< бр />

Код: Выделить всё

class Prediction(Base):
__tablename__ = "predictions"

id = Column(Integer, primary_key=True, index=True, unique=True, autoincrement=True)
# and much more columns

# ...

db = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# ...

def predict(image_id: int, image_key: str):
result = detector.detect(image_key, classes)

for i in result:
db_prediction = models.Prediction(
# pass all params except id
)
db.add(db_prediction)
db.commit()  # exception raising at this line
I understand that problem is in non-unique value of id column in rows I'm trying to insert. I'm trying to figure out what's the best way to catch exceptions like this and insert row(s), not loosing function results.
I know about rollback(), but how to use it with try ... catch and insert row with correct id?


Источник: https://stackoverflow.com/questions/781 ... aded-pytho

Вернуться в «Python»