【问题标题】:AWS RDS connection from SQLAlchemy responds with error来自 SQLAlchemy 的 AWS RDS 连接响应错误
【发布时间】:2021-10-20 23:03:21
【问题描述】:

我正在尝试将我的 AWS RDS 数据库实例与 SQLAlchemy DBAPI 连接。

from sqlalchemy import Column, Integer, String, ForeignKey, create_engine, text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.orm.session import Session
from pprint import pprint
# The string form of the URL is dialect[+driver]://user:password@host/dbname[?key=value..]
engine = create_engine('postgresql://postgres:postgres@<AWS-RDS-ENDPOINT>:5432/postgres')

session = Session(engine)

# declarative base class
Base = declarative_base()

# an example mapping using the base

# one to many 

# parent class

class Parent(Base):
    __tablename__ = 'parent'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    surname = Column(String)
    age = Column(Integer)
    sex = Column(String)
    nationality = Column(Integer)

    children = relationship("Child", back_populates="parent")
    
    def __repr__(self):
        return f"id: {self.id} name: {self.name} surname: {self.surname} age: {self.age} sex: {self.sex} nationality: {self.nationality}"

# child class

class Child(Base):
    __tablename__ = 'child'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    surname = Column(String)
    age = Column(Integer)
    sex = Column(String)
    nationality = Column(Integer)

    parent_id = Column(Integer, ForeignKey('parent.id'))

    parent = relationship("Parent", back_populates="children")
    def __repr__(self):
        return f"id: {self.id} name: {self.name} surname: {self.surname} age: {self.age} sex: {self.sex} nationality: {self.nationality} parent_id: {self.parent_id}"


# create all configuration
Base.metadata.create_all(engine)

即使我设置了正确的参数,它也会响应以下错误。

OperationalError: (psycopg2.OperationalError) could not connect to server: No route to host
        Is the server running on host "postgres.cygbp7ngafcu.eu-central-1.rds.amazonaws.com" (172.31.38.121) and accepting
        TCP/IP connections on port 5432?

我对连接一无所知,这个错误可能是什么问题?

【问题讨论】:

  • 什么意思?您还有其他错误吗?
  • 不@Marcin我还有其他比这更重要的任务只是一个试验:)。感谢关注
  • 好的。但是答案已经给出,如果其中任何一个有帮助,接受它是一种很好的做法,即使你只是在做一些试验。

标签: python postgresql amazon-web-services sqlalchemy amazon-rds


【解决方案1】:

您的 RDS 正在使用私有地址空间 (172.31.38.121)。这意味着您必须 Configuring a Lambda function to access resources in a VPC 您的 RDS 所在的位置。

您还需要修改 security groups of your RDS 以允许 lambda 函数在 VPC 中的连接。

或者,您必须公开您的 RDS 并通过互联网访问,但这是不推荐

【讨论】:

    【解决方案2】:

    我假设您正在尝试从本地连接 RDS。

    您需要在安全组中添加您的 IP 才能从本地访问 RDS 数据库。

    查看此文档以获取 Controlling Access With Security Groups

    【讨论】:

      猜你喜欢
      • 2016-07-22
      • 2020-03-10
      • 1970-01-01
      • 2020-05-18
      • 2019-10-08
      • 2020-09-15
      • 1970-01-01
      • 2015-10-14
      • 2019-04-17
      相关资源
      最近更新 更多