Я пытаюсь установить значение ключа в формате JSON, хранящемся в столбце базы данных (MySql).
Пример кода:
import json
from sqlmodel import Field, JSON
from fastapi.middleware.cors import CORSMiddleware
from settings import settings
from typing import Annotated
from sqlmodel import Session, create_engine, SQLModel
from fastapi import Depends, FastAPI
class Organization(SQLModel, table=True):
__tablename__ = "organizations"
id: int | None = Field(default=None, primary_key=True)
name: str = Field()
meta: dict = Field(sa_type=JSON)
class MyService:
def __init__(self, session: Session):
self.session = session
def update(self, value: str, organization_id: str):
organization = self.session.get(Organization, organization_id)
print(organization)
organization.meta['custom_key'] = value
self.session.add(organization)
self.session.commit()
def get_session():
with Session(engine) as session:
yield session
engine = create_engine(settings.db_connection_string, echo=True)
SessionDep = Annotated[Session, Depends(get_session)]
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.on_event("startup")
def on_startup():
SQLModel.metadata.create_all(engine)
@app.post("/update/{organization_id}")
def update(organization_id: str, value: str, session: SessionDep):
service = MyService(session)
service.update(value, organization_id)
return {"message": "success"}
Организация правильно считывается из базы данных, и значение мета правильное. Но я не вижу никаких операторов обновления, когда я нажимаю функцию update.
Журналы:
INFO: Uvicorn running on http://127.0.0.1:8001 (Press CTRL+C to quit)
INFO: Started reloader process [28024] using WatchFiles
INFO: Started server process [39612]
INFO: Waiting for application startup.
2024-10-15 15:03:16,139 INFO sqlalchemy.engine.Engine SELECT DATABASE()
2024-10-15 15:03:16,140 INFO sqlalchemy.engine.Engine [raw sql] {}
2024-10-15 15:03:16,141 INFO sqlalchemy.engine.Engine SELECT @@sql_mode
2024-10-15 15:03:16,141 INFO sqlalchemy.engine.Engine [raw sql] {}
2024-10-15 15:03:16,142 INFO sqlalchemy.engine.Engine SELECT @@lower_case_table_names
2024-10-15 15:03:16,142 INFO sqlalchemy.engine.Engine [raw sql] {}
2024-10-15 15:03:16,143 INFO sqlalchemy.engine.Engine BEGIN (implicit)
2024-10-15 15:03:16,143 INFO sqlalchemy.engine.Engine DESCRIBE `kraya_local`.`organizations`
2024-10-15 15:03:16,144 INFO sqlalchemy.engine.Engine [raw sql] {}
2024-10-15 15:03:16,146 INFO sqlalchemy.engine.Engine COMMIT
INFO: Application startup complete.
2024-10-15 15:03:18,441 INFO sqlalchemy.engine.Engine BEGIN (implicit)
2024-10-15 15:03:18,444 INFO sqlalchemy.engine.Engine SELECT organizations.id AS organizations_id, organizations.name AS organizations_name, organizations.meta AS organizations_meta
FROM organizations
WHERE organizations.id = %(pk_1)s
2024-10-15 15:03:18,444 INFO sqlalchemy.engine.Engine [generated in 0.00030s] {'pk_1': '9befc383-4db8-413e-934a-2e2f6dce51ed'}
name='Tripper Trails' meta={'custom_key': 'test'} id='9befc383-4db8-413e-934a-2e2f6dce51ed'
2024-10-15 15:03:18,457 INFO sqlalchemy.engine.Engine COMMIT
INFO: 127.0.0.1:52204 - "POST /update/9befc383-4db8-413e-934a-2e2f6dce51ed?value=test HTTP/1.1" 200 OK
Альтернативно, если я задам модель как
class Organization(SQLModel, table=True):
__tablename__ = "organizations"
id: int | None = Field(default=None, primary_key=True)
name: str = Field()
meta: str = Field()
и сделайте это в функции:
def update(self, value: str, organization_id: str):
organization = self.session.get(Organization, organization_id)
print(organization)
# organization.meta['custom_key'] = value
organization_metadata = json.loads(organization.meta)
organization_metadata['custom_key'] = value
organization.meta = json.dumps(organization_metadata)
self.session.add(organization)
self.session.commit()
Для этого я вижу запуск оператора обновления в журналах
INFO: Uvicorn running on http://127.0.0.1:8001 (Press CTRL+C to quit)
INFO: Started reloader process [20320] using WatchFiles
INFO: Started server process [23168]
INFO: Waiting for application startup.
2024-10-15 15:05:50,857 INFO sqlalchemy.engine.Engine SELECT DATABASE()
2024-10-15 15:05:50,857 INFO sqlalchemy.engine.Engine [raw sql] {}
2024-10-15 15:05:50,858 INFO sqlalchemy.engine.Engine SELECT @@sql_mode
2024-10-15 15:05:50,858 INFO sqlalchemy.engine.Engine [raw sql] {}
2024-10-15 15:05:50,859 INFO sqlalchemy.engine.Engine SELECT @@lower_case_table_names
2024-10-15 15:05:50,859 INFO sqlalchemy.engine.Engine [raw sql] {}
2024-10-15 15:05:50,860 INFO sqlalchemy.engine.Engine BEGIN (implicit)
2024-10-15 15:05:50,861 INFO sqlalchemy.engine.Engine DESCRIBE `kraya_local`.`organizations`
2024-10-15 15:05:50,861 INFO sqlalchemy.engine.Engine [raw sql] {}
2024-10-15 15:05:50,877 INFO sqlalchemy.engine.Engine COMMIT
INFO: Application startup complete.
2024-10-15 15:05:54,774 INFO sqlalchemy.engine.Engine BEGIN (implicit)
2024-10-15 15:05:54,778 INFO sqlalchemy.engine.Engine SELECT organizations.id AS organizations_id, organizations.name AS organizations_name, organizations.meta AS organizations_meta
FROM organizations
WHERE organizations.id = %(pk_1)s
2024-10-15 15:05:54,779 INFO sqlalchemy.engine.Engine [generated in 0.00082s] {'pk_1': '9befc383-4db8-413e-934a-2e2f6dce51ed'}
name='Tripper Trails' meta='{}' id='9befc383-4db8-413e-934a-2e2f6dce51ed'
2024-10-15 15:05:54,784 INFO sqlalchemy.engine.Engine UPDATE organizations SET meta=%(meta)s WHERE organizations.id = %(organizations_id)s
2024-10-15 15:05:54,785 INFO sqlalchemy.engine.Engine [generated in 0.00078s] {'meta': '{"custom_key": "test"}', 'organizations_id': '9befc383-4db8-413e-934a-2e2f6dce51ed'}
2024-10-15 15:05:54,790 INFO sqlalchemy.engine.Engine COMMIT
INFO: 127.0.0.1:52267 - "POST /update/9befc383-4db8-413e-934a-2e2f6dce51ed?value=test HTTP/1.1" 200 OK
Подробнее здесь: https://stackoverflow.com/questions/790 ... in-fastapi
Как обновить столбцы JSON в FastAPI ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Ошибка FastAPI: невозможно импортировать имя «FastApi» из «fastapi» [закрыто]
Anonymous » » в форуме Python - 0 Ответы
- 8 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Как я могу суммировать ежемесячные столбцы в квартальные и годовые столбцы?
Anonymous » » в форуме Python - 0 Ответы
- 52 Просмотры
-
Последнее сообщение Anonymous
-