blueFast
blueFast

Reputation: 44411

How to use define_tables from outside web2py

For maintenance chores, I would like to call define_tables outside of web2py proper. Can this be done? Can I do something like:

from gluon.tools import Auth
from pydal import DAL

db = DAL(...)
auth = Auth(db)
auth.define_tables()

I think not, because Auth needs access to a signup controller too ... Is there an alternate method for this?

Upvotes: 1

Views: 271

Answers (1)

Anthony
Anthony

Reputation: 25536

The problem you will run into is not the lack of controller for the Auth actions but that Auth initialization requires request and session objects (attached to the current object), which you would have to mock (this is doable, but other solutions might be simpler).

If you must run the code entirely outside the context of a web2py application, you might get by with the DAL auto import feature:

db = DAL(...,folder='path/to/app/databases', auto_import=True)

The above will automatically define all of the database table models based on the metadata stored in the migration files. However, the table definitions will lack many of the web2py-specific attributes, such as field validators, labels, etc. (the metadata files include only the information needed to manage database migrations, such as field names and types, constraints, etc.). Depending on what you need to do with the Auth tables, this may be sufficient for you.

Alternatively, you might consider running your Python code in the context of the relevant web2py application. There are several ways to achieve this.

First, you could use web2py command line options to run a Python script:

>> python web2py.py -S myapp -M -R /path/to/script.py

The above will generate a web2py environment, run the app's models, and then execute the script in that environment (so auth, db, and the Auth table definitions will all be available to the script).

Second, you could put your code in a controller or module within the application, and then call a particular action in the controller to trigger the code to run. You could run the action either through the browser interface or via a programmatic call using curl or from another Python script.

Finally, you could use the web2py scheduler to run one-time or periodic tasks in the context of the app (most of the code could go in a module that gets imported).

Note, for code in a module that needs to access the web2py app environment, see the documentation on using the current object.

Upvotes: 1

Related Questions