通过 Flask/SQLAlchemy 使用 Python3 灵活引擎连接到 google-sql

Connecting to google-sql with Python3 flexible engine through Flask/SQLAlchemy

我已将我的应用程序引擎升级到 flexible,现在正在重构代码。除了 standard 之外,我没有使用过 Flask,也没有使用过 SQLAlchemy。我已经设置了我的数据库,并且之前在 standard 环境中建立了有效的、正常运行的连接。我现在正在尝试在 Python3 flexible environment:

中执行一个简单的 SQL
SELECT id, latitude, longitude FROM weatherData

我现在通过以下方式与数据库建立了有效连接:

    app = Flask(__name__)
    app.config['WEATHER_DATABASE_URI'] = os.environ['WEATHER_DATABASE_URI']
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    db = SQLAlchemy(app)

各自的环境变量在我的app.yaml文件中。

我知道 SQLAlchemy 使用 ORM,但在我看到的所有示例中,他们在客户端和数据库之间创建了 class 作为 'buffer' 首先创建 table,然后进行CRUD操作。例如

engine = create_engine('sqlite:///student.db', echo=True)
Base = declarative_base()

class Student(Base):
""""""
__tablename__ = "student"

id = Column(Integer, primary_key=True)
username = Column(String)
firstname = Column(String)
lastname = Column(String)
university = Column(String)

#----------------------------------------------------------------------
def __init__(self, username, firstname, lastname, university):
    """"""
    self.username = username
    self.firstname = firstname
    self.lastname = lastname
    self.university = university

 # create tables
 Base.metadata.create_all(engine)

我注意到在这种情况下,他们使用的是 engine,这似乎与我无关。简而言之,如何执行上述 SQL 查询?

谢谢:)

SQLAlchemy 使用它的 engine class 来控制与数据库的交互。首先,您创建一个指定连接方式的引擎:

db = sqlalchemy.create_engine(
    # Equivalent URL:
    # mysql+pymysql://<db_user>:<db_pass>@/<db_name>?unix_socket=/cloudsql/<cloud_sql_instance_name>
    sqlalchemy.engine.url.URL(
        drivername='mysql+pymysql',
        username=db_user,
        password=db_pass,
        database=db_name,
        query={
            'unix_socket': '/cloudsql/{}'.format(cloud_sql_instance_name)
        }
    )
}

其次,您使用引擎检索到实例的连接并执行您的操作:

with db.connect() as conn:
     recent_votes = conn.execute(
            "SELECT candidate, time_cast FROM votes "
            "ORDER BY time_cast DESC LIMIT 5"
     ).fetchall()

这允许 SQLAlchemy 以更有效的方式管理您的连接。如果您想在应用程序上下文中查看这些片段,请查看此 example application