0

我是 python 编程的新手,想在pythonanywhere.com上用烧瓶建立一个 MySQL 数据库。我使用Marshmallow-sqlalchemy从/向数据库执行读/写过程。现在,我对以下复杂的阅读过程有点困惑:

@app.route('/getElement')
def getElement():
    idU1=["abc","def","ghi"]
    newTest=Test(idU1=json.dumps(idU1))
    db.session.add(newTest)
    db.session.commit()
    entryString = test_schema.dumps(Test.query.with_entities(Test.idU1).filter_by(idm=1).all())  #Browser views [{"idU1": "[\"abc\", \"def\", \"ghi\"]"}]
    entryList = json.loads(entryString)
    entryDict = entryList[0] #Browser views {"idU1": "[\"abc\", \"def\", \"ghi\"]"}
    valueString = entryDict['idU1']
    valueList = json.loads(valueString)
    result =  valueList[2]
    return json.dumps(result) #Browser views "ghi", which again should be loaded for processing


这就是我设置文件的方式:

app = Flask(__name__)
app.config["DEBUG"] = True

SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://{username}:{password}@{hostname}/{databasename}".format(
    username="Ehrismann",
    password="abcdefgh",
    hostname="Ehrismann.mysql.pythonanywhere-services.com",
    databasename="Ehrismann$default",
)

app.config["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI  # connection specs
app.config["SQLALCHEMY_POOL_RECYCLE"] = 299  # don't care
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

db = SQLAlchemy(app)  # actually make connection
ma = Marshmallow(app)  # instantiate MarshmallowObject


class Test(db.Model):  # new Table: comment

    __tablename__ = "test"
    idm = db.Column(db.Integer, primary_key=True)  # new Column
    idU1=db.Column(db.String(100), nullable=False)

class TestSchema(ma.ModelSchema):
    class Meta:
        model=Test

test_schema = TestSchema(many=True)

那么,关于如何简化我的代码的任何想法?

4

1 回答 1

0

这里有两个明显的改进:

  • 无需序列化查询结果;在函数内部,您使用查询返回的对象,并且仅在必要时序列化为 json,例如当要通过网络发送数据时。
  • 如果只对第一行进行操作,则无需获取查询中的所有行。
@app.route('/getElement')
def getElement():
    idU1=["abc","def","ghi"]
    newTest=Test(idU1=json.dumps(idU1))
    db.session.add(newTest)
    db.session.commit()

    first_result = Test.query.with_entities(Test.idU1).filter_by(idm=1).first()
    entryDict = json.loads(first_result)
    valueString = entry_dict['idU1']
    valueList = json.loads(valueString)
    result =  valueList[2]
    return json.dumps(result)

MySQL 有一个json 列类型;使用它而不是字符串列将避免调用json.loads查询结果的需要。

于 2019-12-14T14:44:02.970 回答