flask框架,flask_sqlalchemy连接mysql基础配置时的错误处理

发布时间 2023-08-14 16:47:40作者: future725

一、背景

1.我的环境是py 3.11.4

2.《Flask Web 全栈开发实战>这本书里有错误。也可能是因为针对py2写的

3.从flask_sqlalchemy官网查看了资料

4.也从别的网址进行了借鉴,这里就不写了。避免产生广告。

二、可以运行的代码(py 3.11.4)

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import text

db = SQLAlchemy()

app = Flask(__name__)

hostname = "127.0.0.1"
port = 3306
username = "root"
passwd = "root"
database = "database_learn"
app.config['SQLALCHEMY_DATABASE_URI']=f"mysql+pymysql://{username}:{passwd}@{hostname}:{port}/{database}?charset=utf8"

db.init_app(app) #flask_sqlalchemy官网的写法,在我的书里是db = SQLAlchemy(app),同时没有上面的db = SQLAlchemy()

with app.app_context():  #没有这句话会报错
    with db.engine.connect() as conn:
        rs = conn.execute(text("SELECT VERSION()")) #或者 select 1 。没有text()会报错
        print(rs.fetchone())

三、报错说明

1)第一种

with db.engine.connect() as conn:
^^^^^^^^^
RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
the current application. To solve this, set up an application context
with app.app_context(). See the documentation for more information.

这种需要在代码中加入

with app.app_context(): 

 2)第二种

AttributeError: 'str' object has no attribute '_execute_on_connection'

sqlalchemy.exc.ObjectNotExecutableError: Not an executable object: 'SELECT * from student'

 需要加入text()