standalone use of DAL in web2py

我是研究僧i 提交于 2019-12-02 04:06:14

问题


I have sqlite database from web2py application. I want to use gluon library to work with data. I've read this post, but I got error DAL object has no attribute 'user. As I understand I need to use definitions of tables (in myapp/models/tables.py). How can I use DAL with existing database outside of web2py (using only gluon library).

Here is my code:

from gluon.sql import DAL, Field
from gluon.validators import *

module_path = os.path.abspath(os.path.dirname(__file__))
print module_path
dbpath = module_path + '/../databases/'

db_name = "storage.sqlite"

db = DAL('sqlite://' + db_name, folder=dbpath)
rows = db(db.user).select()

My question is how to import all definition of tables I have in myapp/models/tables.py ?


回答1:


You can use pydal

pip install pydal

and then:

from pydal import DAL, Field
...



回答2:


Your code refers to db.user, but you have not defined a "user" table in your code. You cannot import the table definitions from an app model file, as it is not a Python module. One solution might be the following:

db = DAL('sqlite://' + db_name, folder=dbpath, auto_import=True)

That will read the table metadata from the *.table files and create table definitions, though the definitions will not includes some of the web2py-specific model attributes, such as field validators, labels, etc. If you need full DAL table definitions with all the field attributes, you will have to include them directly in your external code. For more details, see here.

Also, do import gluon.dal, not gluon.sql, which was deprecated a long time ago (it simply refers to gluon.dal).




回答3:


You have to install pydal seperately from the pydal/dal version you receive from the web2py enviroment. (Also check the pydal version in your copy of web2py and install the same version into python)

pip install pydal==some_version_number

Note: You have to use an explicit path to the folder where the db tables are located.

from pydal import DAL

db = DAL("some_db_uri", folder="/some/full_path_to/database", auto_import=True)


来源:https://stackoverflow.com/questions/15512342/standalone-use-of-dal-in-web2py

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!