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

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


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,但在我见过的所有示例中,它们都创建了一个类作为客户端和数据库之间的“缓冲区”,以首先创建表,然后执行 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 查询?


谢谢 :)


ITMISS
浏览 237回答 1
1回答

长风秋雁

SQLAlchemy 使用它的engine类来控制与数据库的交互。首先,您创建一个引擎,指定您要如何连接:db = sqlalchemy.create_engine(&nbsp; &nbsp; # Equivalent URL:&nbsp; &nbsp; # mysql+pymysql://<db_user>:<db_pass>@/<db_name>?unix_socket=/cloudsql/<cloud_sql_instance_name>&nbsp; &nbsp; sqlalchemy.engine.url.URL(&nbsp; &nbsp; &nbsp; &nbsp; drivername='mysql+pymysql',&nbsp; &nbsp; &nbsp; &nbsp; username=db_user,&nbsp; &nbsp; &nbsp; &nbsp; password=db_pass,&nbsp; &nbsp; &nbsp; &nbsp; database=db_name,&nbsp; &nbsp; &nbsp; &nbsp; query={&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'unix_socket': '/cloudsql/{}'.format(cloud_sql_instance_name)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; )}其次,您使用引擎检索与实例的连接并执行您的操作:with db.connect() as conn:&nbsp; &nbsp; &nbsp;recent_votes = conn.execute(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "SELECT candidate, time_cast FROM votes "&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "ORDER BY time_cast DESC LIMIT 5"&nbsp; &nbsp; &nbsp;).fetchall()这允许 SQLAlchemy 以更有效的方式管理您的连接。如果您想在应用程序的上下文中查看这些片段,请查看此示例应用程序。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python