# Integer,Float,String,DateTime def getColumnObject(dbColumnDict): ctype = dbColumnDict["type"] isIdx = dbColumnDict["index"] if ctype == "String": n = dbColumnDict["length"] value = db.Column(db.String(n),index=isIdx) elif ctype == "Integer": value = db.Column(db.Integer,index=isIdx) elif ctype == "Float": value = db.Column(db.Float,index=isIdx) elif ctype == "DateTime": value = db.Column(db.DateTime,index=isIdx) else: raise Exception("No sucn type{}".format(ctype)) return value def createSetFunction(): def f(self,attributeDict): for key in attributeDict.keys(): self.__setattr__(key,attributeDict[key]) return f # metaDict{"tableName":,attributes:{name:{type:xxxx,index:True},name2:{}} def createTableObject(metaDict): tableName = metaDict["tableName"] attrDict = {} attrDict["id"] = db.Column(db.Integer, primary_key=True) attrDict["timestamp"] = db.Column(db.DateTime, index=True, default=datetime.now) #attrList["user_id"] = db.Column(db.Integer, db.ForeignKey('user.id')) attrNames = [] for name in metaDict['attributes'].keys(): # Integer,Float,String,DateTime value = getColumnObject(metaDict['attributes'][name]) attrDict[name] = value attrNames.append(name) print "type attr dict:",type(attrDict) TableClass = type(tableName,(db.Model,),attrDict) TableClass.setAll = createSetFunction() TableClass.column_name = attrNames # create one table TableClass.__table__.create(db.session.bind) return (tableName,TableClass)@app.route("/test_db",methods=["GET"]) def test_db(): try: metaDict = {"tableName":"test_db","attributes":{"count":{"type":"Integer","index":True}}} name , table_class = createTableObject(metaDict) record = table_class() record.setAll({"count":100,"user_id":current_user.get_id()}) db.session.add(record) db.session.commit() return "add test db finished!" except Exception,e: return "TEST DB Exception {}".format(e)
Flask Sql通过参数创建表
最新推荐文章于 2024-06-14 16:34:22 发布