🐛 fix(api_key/crud.py): fix session concurrency issue when updating total uses and last used at fields
This commit is contained in:
parent
8faad70917
commit
54cfca3dd6
1 changed files with 11 additions and 5 deletions
|
|
@ -3,6 +3,8 @@ import secrets
|
||||||
import threading
|
import threading
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
from typing import List, Optional
|
from typing import List, Optional
|
||||||
|
from langflow.services.database.utils import session_getter
|
||||||
|
from langflow.services.utils import get_db_manager
|
||||||
from sqlmodel import Session, select
|
from sqlmodel import Session, select
|
||||||
from langflow.services.database.models.api_key import (
|
from langflow.services.database.models.api_key import (
|
||||||
ApiKey,
|
ApiKey,
|
||||||
|
|
@ -63,9 +65,13 @@ def check_key(session: Session, api_key: str) -> Optional[ApiKey]:
|
||||||
|
|
||||||
def update_total_uses(session, api_key: ApiKey):
|
def update_total_uses(session, api_key: ApiKey):
|
||||||
"""Update the total uses and last used at."""
|
"""Update the total uses and last used at."""
|
||||||
api_key.total_uses += 1
|
# This is running in a separate thread to avoid slowing down the request
|
||||||
api_key.last_used_at = datetime.datetime.now(datetime.timezone.utc)
|
# but session is not thread safe so we need to create a new session
|
||||||
session.add(api_key)
|
db_manager = get_db_manager()
|
||||||
session.commit()
|
with session_getter(db_manager) as new_session:
|
||||||
session.refresh(api_key)
|
api_key = new_session.get(ApiKey, api_key.id)
|
||||||
|
api_key.total_uses += 1
|
||||||
|
api_key.last_used_at = datetime.datetime.now(datetime.timezone.utc)
|
||||||
|
new_session.add(api_key)
|
||||||
|
new_session.commit()
|
||||||
return api_key
|
return api_key
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue