我是 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)
那么,关于如何简化我的代码的任何想法?