本文介绍了重写Flask-Alchemy中的表名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有下面的类访问一个表: class price_table(db.Model): id = db.Column(db.Integer,primary_key = True) trans_id = db .Column(db.Integer) timestamp = db.Column(db.Integer) order_type = db.Column(db.String(25)) price = db.Column(db。数字(15,8)) quantity = db.Column(db.Numeric(25,8)) def __repr __(self): return'id' $ b对于'price_table'这个表,这个工作非常出色,但问题是我有几个表'price_table'我只知道在运行时的名称。 我想重用上面的类,所以我想我可以改变 tablename 为我需要阅读的表,但这是行不通的,程序一直在阅读'价格表' 何我是否在运行时重写表名?解决方案基于jbub留下的评论,我找到了下面的解决方案 from app import db class ClassFactory(name): tabledict = {'id':db.Column(db.Integer,primary_key = True),'trans_id':db.Column(db.Integer),'timestamp':db.Column(db .Bench),'order_type':db.Column(db.String(25)),'price':db.Column(db.Numeric(25,8)), 'quantity':db.Column(db.Numeric(25,8)),} newclass = type(name,(db.Model,),tabledict) return newclass I am creating a Flask application and accessing the MySQL database using Flask-Alchemy.I have following Class to access a table:class price_table(db.Model): id = db.Column(db.Integer, primary_key = True) trans_id = db.Column(db.Integer) timestamp = db.Column(db.Integer) order_type = db.Column(db.String(25)) price = db.Column(db.Numeric(15,8)) quantity = db.Column(db.Numeric(25,8)) def __repr__(self): return 'id'For the table 'price_table' this works brilliantly, but problem is I have a few tables with the same columns as 'price_table' from which I only know the name at runtime.I want to reuse the class above so I thought I could change tablename to the name of the table I need to read, but that does not work, the program keeps reading the 'price-table'How do I override the tablename at runtime? 解决方案 Based on the comment left by jbub I found the following solution that does the trick just as needed.from app import dbdef ClassFactory(name): tabledict={'id':db.Column(db.Integer, primary_key = True), 'trans_id':db.Column(db.Integer), 'timestamp':db.Column(db.Integer), 'order_type':db.Column(db.String(25)), 'price':db.Column(db.Numeric(25,8)), 'quantity':db.Column(db.Numeric(25,8)),} newclass = type(name, (db.Model,), tabledict) return newclass 这篇关于重写Flask-Alchemy中的表名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-30 22:17