FastAPI如何访问接受用户输入并返回字符串的PostgreSQL自定义函数?

huangapple go评论77阅读模式
英文:

How does FastAPI access a PostgreSQL custom function which accepts a user input and returns a string

问题

I am getting a response at my api endpoint that I don't understand:
{
"_row_getter": {},
"_memoized_keys": [
"_row_getter"
]
}

The FastAPI code:

from typing import Generator
from fastapi import APIRouter, Depends
from sqlalchemy import create_engine
from sqlalchemy.orm import Session, sessionmaker
from sqlalchemy.sql import select, func

from backend.core.config import settings

SQLALCHEMY_DATABASE_URL = settings.DATABASE_URL
engine = create_engine(SQLALCHEMY_DATABASE_URL)

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

def get_db() -> Generator:
    try:
        db = SessionLocal()
        yield db
    finally:
        db.close()

def check_trc(ist: int, db: Session):
    chk_func = func.chktracer(ist)
    chk_stmt = select(chk_func)
    chk_result = db.execute(chk_stmt)
    db.commit()
    return chk_result

router = APIRouter()

@router.get("/chk/{ist}", response_description=str)
def read_trc(ist: int, db: Session = Depends(get_db)):
    chk = check_trc(ist=ist, db=db)
    return chk

My PostgreSQL function runs the following SQL:

-- Upsert user request
INSERT INTO
	trc_log (id)
VALUES
	(p_id)
ON CONFLICT ON CONSTRAINT trc_log_pkey
DO UPDATE
SET req_cnt = EXCLUDED.req_cnt + 1;

-- return status of long running query
SELECT CASE
	WHEN finish_tm IS NULL
	THEN 'inprocess'
	ELSE 'processed'
	END
FROM trc_log
WHERE trc_log.pid = p_ist;

The resulting output string is either 'processed' or 'inprocess' which appears to be expressed in a single-row, single-column table in pgAdmin.

I've tried accessing it as a table but have only run into errors that don't have much explanation online (I searched for each kind of error, many involving the keyword 'anon' which is what the sql table appears to be named). The code I show here at least doesn't give errors, but neither does it give the simple string response I seek. It just returns:
{
"_row_getter": {},
"_memoized_keys": [
"_row_getter"
]
}

Instead, I want a string that indicates 'processed' or 'inprocess'. This value should be based on whether the finish_tm has been posted to the trc_log table yet.

英文:

I am getting a response at my api endpoint that I don't understand:
{
"_row_getter": {},
"_memoized_keys": [
"_row_getter"
]
}

The FastAPI code:

from typing import Generator
from fastapi import APIRouter, Depends
from sqlalchemy import create_engine
from sqlalchemy.orm import Session, sessionmaker
from sqlalchemy.sql import select, func #, column, table

from backend.core.config import settings


SQLALCHEMY_DATABASE_URL = settings.DATABASE_URL
engine = create_engine(SQLALCHEMY_DATABASE_URL)

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

def get_db() -> Generator:
    try:
        db = SessionLocal()
        yield db
    finally:
        db.close()

def check_trc(ist: int, db: Session):
    chk_func = func.chktracer(ist)
    chk_stmt = select(chk_func)
    chk_result = db.execute(chk_stmt)
    db.commit()
    return chk_result

router = APIRouter()

@router.get("/chk/{ist}", response_description=str)
def read_trc(ist: int, db: Session= Depends(get_db)):
    chk = check_trc(ist= ist, db= db)
    return chk

My PostgreSQL function runs the following SQL:

-- Upsert user request
INSERT INTO
	trc_log (id)
VALUES
	(p_id)
ON CONFLICT ON CONSTRAINT trc_log_pkey
DO UPDATE
SET req_cnt = EXCLUDED.req_cnt + 1;

-- return status of long running query
SELECT CASE
	WHEN finish_tm IS NULL
	THEN 'inprocess'
	ELSE 'processed'
	END
FROM trc_log
WHERE trc_log.pid = p_ist;

The resulting output string is either 'processed' or 'inprocess' which appears to be expressed in a single-row, single-column table in pgAdmin.

I've tried accessing it as a table but have only run into errors that don't have much explanation online (I searched for each kind of error, many involving the keyword 'anon' which is what the sql table appears to be named). The code I show here at least doesn't give errors, but neither does it give the simple string response I seek. It just return:
{
"_row_getter": {},
"_memoized_keys": [
"_row_getter"
]
}

Instead, I want a string that indicates 'processed' or 'inprocess'. This value should be based on whether the finish_tm has been posted to the trc_log table yet.

答案1

得分: 0

将代码部分翻译如下:

我通过更改发现了一个解决方案:

chk_result = db.execute(chk_stmt).scalar()
英文:

I found a solution by changing:

chk_result = db.execute(chk_stmt)

to:

chk_result = db.execute(chk_stmt).scalar()

huangapple
  • 本文由 发表于 2023年6月15日 04:36:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76477358.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定