1.5.7 Creating Tables by Defining Classes

As well as defining your table by adding columns to a web.database.object.Table object you can define your own class derived from a web.database.object.Table object instead. Here is the same database defined above but created using classes instead:

import web, web.database, web.database.object

connection = web.database.connect(type="mysql", database="MyDatabase")
cursor = connection.cursor()

class Person(web.database.object.Table):
    def setup(self):
        self.addColumn(web.database.object.String(name="firstName"))
        self.addColumn(web.database.object.String(name="surname"))
        self.addMultiple(name="addresses", foreignTable="Address")

class MyDatabase(web.database.object.Database):
    def setup(self):
        self.addTable(Person())
        
myDatabase = MyDatabase()
myDatabase.init(cursor)

Whilst this may look more complicated it is a more object oriented solution and allows you to build complex table objects with increased functionaility by defining your own objects. For example you could override the _relatedTableName() method of both tables to have your own table name created for multiple join tables.