py4web defining tables

79 views
Skip to first unread message

Maurice Waka

unread,
Feb 27, 2020, 6:55:23 AM2/27/20
to web2py-users
Hello, from this code, I have already defined my table in models as follows:

import os
import datetime as dt
from datetime import datetime, timedelta, date
from py4web import action, request, DAL, Field, Session, Cache, user_in
from py4web.utils.auth import Auth
from py4web import action, request, abort, redirect, URL, Field
from py4web.utils.form import Form, FormStyleBulma
from py4web.utils.publisher import Publisher, ALLOW_ALL_POLICY
from pydal.validators import * #IS_NOT_EMPTY, IS_INT_IN_RANGE, IS_IN_SET, IS_IN_DB, IS_EMAIL, IS_MATCH
from pydal.validators import *
from . common import db, session, T, cache, authenticated, unauthenticated, Field
from pydal.validators import *


### Define your table below


# exposes services necessary to access the db.thing via ajax
publisher
= Publisher(db, policy=ALLOW_ALL_POLICY)
# define session and cache objects
session
= Session(secret="some secret")
cache
= Cache(size=1000)


# define database and tables
#connection = sqlite.connect('cache.db', timeout=10)
db
= DAL("sqlite://xstorage.db", folder=os.path.join(os.path.dirname(__file__), "databases"))#db = DAL("sqlite://storage.db", folder=os.path.join(os.path.dirname(__file__), "databases"))
#db = DAL( "postgres://mauricewaka:b3th32dau2a##@localhost:5432/py4db", migrate=False)
auth
= Auth(session, db)
# (configure here)
auth
.enable()


db
.define_table('answers',
               
Field('author', 'reference auth_user', default=auth.user_id, writable=False, readable=False),
               
Field("message", 'text', requires=IS_NOT_EMPTY(), notnull=False),
                auth
.signature
               
)




In the controllers, this is my code:

@authenticated()
@action.uses(auth.user)
def index():

   
...some code...
    yesterday
= dt.datetime.utcnow() - dt.timedelta(days=1)

    db
(db.answers.modified_on < yesterday).delete()
   
...some more code....



But I get this errors:
Traceback (most recent call last):
 
File "/home/maurice/py4web/py4web/core.py", line 551, in wrapper
 ret
= func(*func_args, **func_kwargs)
 
File "/home/maurice/py4web/py4web/core.py", line 512, in wrapper
 ret
= func(*args, **kwargs)
 
File "/home/maurice/py4web/py4web/core.py", line 512, in wrapper
 ret
= func(*args, **kwargs)
 
File "apps/scaffoldx/controllers.py", line 571, in index
 db
(db.answers.modified_on < yesterday).delete()
 
File "/home/maurice/.local/lib/python3.6/site-packages/pydal/base.py", line 763, in __getattr__
 
return BasicStorage.__getattribute__(self, key)
AttributeError: 'DAL' object has no attribute 'answers'


What could be wrong here and how can I solve it?
N/B
I have tried to define the table inside the controller code with an error coming as : 'table already defined'. When I remove the definition then the above error comes.
Regards

Jim S

unread,
Feb 27, 2020, 8:35:25 AM2/27/20
to web2py-users
Where is db being defined in your controller?  Are you importing it from common?

In my controller I have

from ..common import db, session, T, cache, auth, logger

and later

@action.uses("applications/index.html", session, db, T, auth.user)
def index():
    page
['sub_title'] = A('MENU', _href=URL('index'))
   
return dict(page=page)

Does that help?  If not, can you post a minimal common.py, models.py and your controller?

-Jim

Maurice Waka

unread,
Feb 27, 2020, 11:05:28 AM2/27/20
to web2py-users
I already have that, see above code second last line on imports

Jim S

unread,
Feb 27, 2020, 12:09:00 PM2/27/20
to web2py-users
Yes, I am aware of that, but what file is that in?  You didn't specify.  Is that in the same controller the other snippet is in?  If so, then you're redfining db and the table in your controller which in your second to last line of your post you say you're not doing.  

I'm confused...  I'd like to help, but need a clear picture of a minimal common.py, models.py and your controller that reproduces this error.

-Jim

Maurice Waka

unread,
Feb 27, 2020, 12:29:39 PM2/27/20
to web2py-users
In my models, I have:

import os
import datetime as dt
from datetime import datetime, timedelta, date
from py4web import action, request, DAL, Field, Session, Cache, user_in
from py4web.utils.auth import Auth
from py4web import action, request, abort, redirect, URL, Field
from py4web.utils.form import Form, FormStyleBulma
from py4web.utils.publisher import Publisher, ALLOW_ALL_POLICY
from pydal.validators import * #IS_NOT_EMPTY, IS_INT_IN_RANGE, IS_IN_SET, IS_IN_DB, IS_EMAIL, IS_MATCH
from pydal.validators import *
from . common import db, session, T, cache, authenticated, unauthenticated, Field
from pydal.validators import *

# exposes services necessary to access the db.thing via ajax
publisher
= Publisher(db, policy=ALLOW_ALL_POLICY)
# define session and cache objects
session
= Session(secret="some secret")
cache
= Cache(size=1000)

# define database and tables

db
= DAL("sqlite://xstorage.db", folder=os.path.join(os.path.dirname(__file__), "databases"))


auth
= Auth(session, db)

# (configure here)
auth
.enable()

db
.define_table('answers',
               
Field('author', 'reference auth_user', default=auth.user_id, writable=False, readable=False),
               
Field("message", 'text', requires=IS_NOT_EMPTY(), notnull=False),
                auth
.signature
               
)



In the controller:


from pydal.validators import *
from datetime import datetime, timedelta, date
from py4web.utils.auth import Auth
from py4web.utils.form import Form, FormStyleBulma
from py4web.utils.publisher import Publisher, ALLOW_ALL_POLICY
from .common import db, session, T, cache, auth, logger, authenticated, unauthenticated
from py4web import action, request, DAL, Field, Session, Cache, user_in, abort, redirect, URL, Translator
from pydal.validators import IS_NOT_EMPTY, IS_INT_IN_RANGE, IS_IN_SET, IS_IN_DB, IS_EMAIL, IS_MATCH
from yatl.helpers import A, TEXTAREA, INPUT, TR, TD, TABLE, DIV, LABEL, FORM, SELECT, OPTION, P, H1, H2, H3, H4, H5, HTML, BODY
from . wellness_main import report
from . r_image import img_report

auth = Auth(session, db)
# (configure here)
auth.enable()


@authenticated()
@action.uses(session, db, T, auth.user)
def index():
    yesterday = dt.datetime.utcnow() - dt.timedelta(days=1)
    db(db.answers.modified_on < yesterday).delete()
    """Avoid an empty table"""
    user = db(db.posts.author== auth.user_id).select(db.posts.id, db.posts.author, orderby=~db.posts.id, limitby=(0,1)).first()
    if user.author if user else None == auth.user_id:
        pass
    ....more code..
    return dict(...)

Regards

Val K

unread,
Feb 27, 2020, 12:43:37 PM2/27/20
to web2py-users
There is import db from common, but later there is db = DAL(...) in the same file!

Jim S

unread,
Feb 27, 2020, 12:46:00 PM2/27/20
to web2py-users
Try commenting out 

db = DAL("sqlite://xstorage.db", folder=os.path.join(os.path.dirname(__file__), "databases"))

in models.py

Do you already have that in common.py?

In your controller you're importing db from common, but the instance in common doesn't have any tables defined.  You redefined db in models.py and added the table to that instance of it.

I think the solution is to move the statement above from models.py to common.py

-Jim

Maurice Waka

unread,
Feb 27, 2020, 12:52:47 PM2/27/20
to web...@googlegroups.com
I get it.
Let me work it out in the next hour. 
Kind regards

--
Resources:
- http://web2py.com
- http://web2py.com/book (Documentation)
- http://github.com/web2py/web2py (Source code)
- https://code.google.com/p/web2py/issues/list (Report Issues)
---
You received this message because you are subscribed to a topic in the Google Groups "web2py-users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/web2py/wn6mmXVPlC0/unsubscribe.
To unsubscribe from this group and all its topics, send an email to web2py+un...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/web2py/95f5b7fa-e68e-4f7b-9174-d5eea3448456%40googlegroups.com.

Maurice Waka

unread,
Feb 27, 2020, 2:44:10 PM2/27/20
to web2py-users
Thanks a lot.
It worked.
Regards
Reply all
Reply to author
Forward
0 new messages