Fastapi 从 postgreSQL 中的现有数据库表中读取

发布于 2025-01-09 10:02:45 字数 1026 浏览 1 评论 0原文

我正在尝试创建一个 FAST Api,它从 PostgreSQL 数据库中现有的表中读取数据,但它给了我一个内部服务器错误。希望您能指导代码可能出现的问题

现有的表如下所示:

schema : testSchema
表:test_api

idemail
1test@***.com
2test2@***.com
engine = sqlalchemy.create_engine("my_database_connection")
Base = declarative_base()
database = databases.Database("my_database_connection")

metadata = sqlalchemy.MetaData()
metadata.reflect(bind=engine, schema='testSchema')
test_api_tb = metadata.tables['testSchema.test_api']
   


class testAPI(Base):
    __tablename__ = test_api_tb
    id = Column(Integer, primary_key=True)
    email = Column(String(256))

app = FastAPI()


@app.get("/testing_api/")
def read_users():
     query = test_api_tb.select()
     return  database.execute(query)

我从日志中得到的错误

RecursionError: maximum recursion depth exceeded in comparison

I am trying to create a FAST Api that is reading from an already existing table in PostgreSQL database but it is giving me an internal server error. Would appreciate your direction on what might be wrong with the code

The existing table looks like this:

schema : testSchema
table : test_api

idemail
1test@***.com
2test2@***.com
engine = sqlalchemy.create_engine("my_database_connection")
Base = declarative_base()
database = databases.Database("my_database_connection")

metadata = sqlalchemy.MetaData()
metadata.reflect(bind=engine, schema='testSchema')
test_api_tb = metadata.tables['testSchema.test_api']
   


class testAPI(Base):
    __tablename__ = test_api_tb
    id = Column(Integer, primary_key=True)
    email = Column(String(256))

app = FastAPI()


@app.get("/testing_api/")
def read_users():
     query = test_api_tb.select()
     return  database.execute(query)

The error I am getting from the logs

RecursionError: maximum recursion depth exceeded in comparison

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

千柳 2025-01-16 10:02:45

你能做的最好的事情就是阅读 fastapi.tiangolo.com 的官方文档,它非常棒并且解释了所有内容非常详细地介绍基础知识。

SQL 关系数据库经常与 FastAPI 一起使用,并且在此处文档中也提到了,您可以找到有关如何将 postgresql 与 sqlalchemy 和 FastAPI 一起使用的分步教程。

有几个部分可以完成这项工作。第一部分是连接到数据库:

engine = create_engine(my_database_connection)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

我们像您一样使用连接字符串创建引擎,然后我们需要创建一个会话才能连接到数据库。最后,我们创建一个基类,它将帮助我们创建模型和模式。

现在我们需要使用基类创建模型,就像上面所做的那样。
我们需要确保__tablename__与数据库中表的名称相同

class testAPIModel(Base):
    __tablename__ = "test_api"
    id = Column(Integer, primary_key=True)
    email = Column(String(256))

现在是主要部分。我们需要确保将数据库引擎绑定到基类,

Base.metadata.create_all(bind=engine)

现在我们将创建一个函数来帮助我们创建一个数据库会话实例,并在完成查询后关闭连接。

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

现在我们可以创建 FastAPI 应用程序实例并从数据库中获取数据。

@app.get("/testing_api/")
def read_users(db:Session = Depends(get_db)):
     users = db.query(testAPIModel).all()
     return users

我们使用 Depends(get_db) 从上面编写的函数注入数据库会话。

完整代码:

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session

from fastapi import Depends, FastAPI
from sqlalchemy import Column, Integer, String

my_database_connection = "postgresql://user:password@server_ip/db_name"

engine = create_engine(my_database_connection)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

class testAPIModel(Base):
    __tablename__ = "test_api"
    id = Column(Integer, primary_key=True)
    email = Column(String(256))


Base.metadata.create_all(bind=engine)
app = FastAPI()

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

@app.get("/testing_api/")
def read_users(db:Session = Depends(get_db)):
    users = db.query(testAPIModel).all()
    return users

祝你好运!

The best thing you can do is to read the official documentation at fastapi.tiangolo.com, it is amazing and explains all the basics in a very detailed way.

SQL Relational Databases are used very often with FastAPI and are also mentioned in the documentation here, you can find step by step tutorial about how to use postgresql with sqlalchemy and FastAPI.

There are a few parts to make this work. The first part is to connect to the database:

engine = create_engine(my_database_connection)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

we create the engine with the connection string as you did, then we need to create a session in order to connect to the database. At the end we are creating a Base class which will help us to create the models and schemas.

Now we need to create the model using the base class just as you did above.
we need to make sure that the __tablename__ is the same as the name of the table in the database

class testAPIModel(Base):
    __tablename__ = "test_api"
    id = Column(Integer, primary_key=True)
    email = Column(String(256))

Now comes the main part. We need to make sure we bind the engine of the database to the base class using

Base.metadata.create_all(bind=engine)

Now we will create a function that will help us and create a db session instance and will close the connection when we done with the query.

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

Now we can create the FastAPI app instance and get the data from the database.

@app.get("/testing_api/")
def read_users(db:Session = Depends(get_db)):
     users = db.query(testAPIModel).all()
     return users

We are using the Depends(get_db) to inject the db session from the function we wrote above.

The full code:

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session

from fastapi import Depends, FastAPI
from sqlalchemy import Column, Integer, String

my_database_connection = "postgresql://user:password@server_ip/db_name"

engine = create_engine(my_database_connection)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

class testAPIModel(Base):
    __tablename__ = "test_api"
    id = Column(Integer, primary_key=True)
    email = Column(String(256))


Base.metadata.create_all(bind=engine)
app = FastAPI()

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

@app.get("/testing_api/")
def read_users(db:Session = Depends(get_db)):
    users = db.query(testAPIModel).all()
    return users

Good Luck!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文