The correct method to initialize a database table with web2py is DAL.define_table ()

I am trying to dynamically create tables called db.blog and db.code with exactly the same SQL definitions. After I define them, I want to fill them with 10 lines of random data and never run this initialization code again.

My problem is that the initialization code is executed every time I click update in the browser, when I look at the appadmin newblog interface for db.code or db.blog : https://172.25.1.1/newblog/appadmin/select/db ? query = db.code.id > 0

I initialize db.blog and db.code in newblog/models/newblog.py :

 from gluon import * from gluon.contrib.populate import populate ## initialize db.blog and db.code: ## At runtime, build TAGGED_TABLES (once) TAGGED_TABLES = set(['blog', 'code']) for tt in TAGGED_TABLES: if not db.get(tt, False): db.define_table(tt, Field('name', length=32, notnull=True), Field('value', length=65535, notnull=True), Field('tags', type='list:reference tag', unique=False, notnull=False), ) populate(db.get(tt), 10) ## cross-reference db.tagged_tables to this one db.tagged_tables.insert(name=tt, database_pointer='reference %s' % tt) db.commit() 

Somehow if not db.get(tt, False): allows you to perform several subroutine executions under it. I do not understand why ... if the table has already been created, then not db.get(tt, False) should be False . However, web2py never misses the initialization code, which means that db.blog and db.code grow by 10 entries with every reboot.

Question: Why not if not db.get(tt, False): preventing multiple executions?

I am running web2py 1.99.4 on Debian 6.0 / sqlite 3.7.3 / Cherokee 1.2.101 / uWSGI 0.9.9.3

Decision

Based on Interrobang answer the correct way to write:

 from gluon import * from gluon.contrib.populate import populate TAGGED_TABLES = set(['blog', 'code']) for tt in TAGGED_TABLES: # db.define_table() must be called on **every page** # this sets things up in memory... db.define_table(tt, Field('name', length=32, notnull=True), Field('value', length=65535, notnull=True), Field('tags', type='list:reference tag', unique=False, notnull=False), ) ## initialize db.blog and db.code: ## At runtime, populate tables named in TAGGED_TABLES (once) if not (db(db.get(tt).id>0).select()): populate(db.get(tt), 10) ## cross-reference db.tagged_tables to this table (named in var tt) db.tagged_tables.insert(name=tt, database_pointer='reference %s' % tt) db.commit() 

Now db.blog and db.code remain constant.

Summary

db.define_tables() should be called for each page rendering; my understanding (that he only needed to write the table definition to disk once) was incorrect.

+8
python database web2py
source share
1 answer

You can add a fixtures file, which basically contains the default data that needs to be inserted once when the table is created.

Here is an example: http://thadeusb.com/weblog/2010/4/21/using_fixtures_in_web2py

+5
source share

All Articles