def test_holiday_add(client, web2py): ''' Can we add a holiday? ''' populate(web2py.db.school_locations, 2) url = '/schedule/holiday_add' client.get(url) assert client.status == 200 assert 'New holiday' in client.text data = dict(Description='Kerstvakantie', Startdate='2014-12-20', Enddate='2014-12-25', Classes=True) client.post(url, data=data) assert client.status == 200 assert 'To which locations does this holiday apply?' in client.text # verify redirection url = '/schedule/holiday_edit_locations?shID=1' client.get(url) loc_data = {'1': 'on'} client.post(url, data=loc_data) assert client.status == 200 assert 'Holidays' in client.text assert data['Description'] in client.text # verify redirection assert web2py.db(web2py.db.school_holidays).count() == 1 assert web2py.db(web2py.db.school_holidays_locations).count() == 1
def test_get_person_by_creation_date(client, web2py): '''Is my filter working? ''' from gluon.contrib.populate import populate populate(web2py.db.people, 3) # insert 3 persons with random data web2py.db.commit() assert web2py.db(web2py.db.people).count() == 3 data = dict( name='John Smith', phone='3322-4455', created_at='1999-04-03 18:00:00') web2py.db.people.insert(**data) # insert my controlled person web2py.db.commit() client.get('/people/get_by_creation_date.json/' + data['created_at'].split()[0]) assert client.status == 200 assert 'application/json' in client.headers['content-type'] import json person = json.loads(client.text) assert person['name'] == data['name']
def test_get_person_by_creation_date(web2py): '''Is my filter working? ''' from gluon.contrib.populate import populate populate(web2py.db.people, 3) # insert 3 persons with random data assert web2py.db(web2py.db.people).count() == 3 data = dict( name='John Smith', phone='3322-4455', created_at='1999-04-03 18:00:00') web2py.db.people.insert(**data) # insert my controlled person web2py.db.commit() web2py.request.args.append(data['created_at'].split()[0]) result = web2py.run('people', 'get_by_creation_date', web2py) # test controller result assert result['name'] == data['name'] # test controller result rendered as json by a view web2py.request.extension = 'json' html = web2py.response.render('people/get_by_creation_date.json', result) import json person = json.loads(html) assert person['name'] == data['name'] assert person['created_at'] == data['created_at']
def test_schedule_school_holidays_delete(client, web2py): """ Is the delete permission for a school holiday working? """ setup_permission_tests(web2py) populate(web2py.db.school_locations, 1) populate(web2py.db.school_holidays, 1) web2py.auth.add_permission(200, 'read', 'school_holidays', 0) web2py.db.commit() url = '/schedule/holidays' client.get(url) assert client.status == 200 assert not 'fa-times' in client.text # grant permission and check again web2py.auth.add_permission(200, 'delete', 'school_holidays', 0) web2py.db.commit() client.get(url) assert client.status == 200 assert 'fa-times' in client.text
def test_event_add(client, web2py): """ Can we add a event? """ populate(web2py.db.school_locations, 1) url = '/events/event_add' client.get(url) assert client.status == 200 data = dict(Name="Mysore_week", Startdate='2014-01-01', Enddate='2014-01-31', school_locations_id=1 ) client.post(url, data=data) assert client.status == 200 assert 'Price incl. VAT' in client.text # verify redirection assert web2py.db(web2py.db.workshops).count() == 1 # Check event_add_onaccept assert web2py.db(web2py.db.workshops_products).count() == 1 fws_product = web2py.db.workshops_products(1) assert fws_product.FullWorkshop assert not fws_product.Deletable
def define_from_schema(db, tablename, schemas=None): from gluon.utils import web2py_uuid schemas = schemas or get_schemas() PROPERTIES = schemas['properties'] # label, comment, ranges TABLENAMES = schemas['types'].keys() datatypes = {'DataType':('string',None), 'Text':('string',None), 'Float':('double',None), 'Number':('double',None), 'DateTime':('datetime',None), 'URL':('string',None), 'Boolean':('boolean',None), 'Time':('time',None), 'Date':('date',None), 'Integer':('integer',None)} if tablename in schemas['types']: #print tablename, schemas['types'][tablename]['properties'] properties = schemas['types'][tablename]['properties'] fields = [Field('uuid','string',default=lambda:web2py_uuid(),writable=False)] for property in properties: info = PROPERTIES[property] label = info['label'] comment = info['comment'] ranges = info['ranges'] if len(ranges)==1 and ranges[0] in datatypes: ftype = datatypes[ranges[0]][0] else: ftype = 'list:string' fields.append(Field('f'+property,ftype,label=label)) table = db.define_table('t'+tablename,*fields) if db(table).isempty(): from gluon.contrib.populate import populate populate(table,120) return table return None
def test_get_person_by_creation_date(web2py): '''Is my filter working? ''' from gluon.contrib.populate import populate populate(web2py.db.people, 3) # insert 3 persons with random data assert web2py.db(web2py.db.people).count() == 3 data = dict(name='John Smith', phone='3322-4455', created_at='1999-04-03 18:00:00') web2py.db.people.insert(**data) # insert my controlled person web2py.db.commit() web2py.request.args.append(data['created_at'].split()[0]) result = web2py.run('people', 'get_by_creation_date', web2py) # test controller result assert result['name'] == data['name'] # test controller result rendered as json by a view web2py.request.extension = 'json' html = web2py.response.render('people/get_by_creation_date.json', result) import json person = json.loads(html) assert person['name'] == data['name'] assert person['created_at'] == data['created_at']
def populate(): query = table set = db(query) # rows = set.select() set.delete() from gluon.contrib.populate import populate populate(table, 15) redirect(URL('list'))
def populate(table): query = table set = db(query) # rows = set.select() set.delete() from gluon.contrib.populate import populate populate(table, 15) return
def reset(): """Reset the data in tables.""" db.category.truncate() db.things.truncate() populate(db.category, 40) populate(db.things, 1000) # Set a few thing records with active=False. disables = [x for x in random.sample(xrange(1000), 10) if x > 0] db(db.things.id.belongs(tuple(disables))).update(active=False) redirect("index")
def test_selfcheckin_index(client, web2py): ''' Is the page that lists locations working? ''' populate(web2py.db.school_locations, 1) url = '/selfcheckin/index' client.get(url) assert client.status == 200 location = web2py.db.school_locations(1) assert location.Name in client.text
def test_ticket_delete(client, web2py): """ Test if we can delete a regular ticket """ populate_workshops_with_activity(web2py) populate(web2py.db.workshops_products, 1) url = '/events/ticket_delete?wsID=1&wspID=2' client.get(url) assert client.status == 200 # we inserted an extra product, so now there should only be one assert web2py.db(web2py.db.workshops_products).count() == 1
def reset(): """ Will truncate all tables and populates again with dummy data. """ from gluon.contrib.populate import populate for table in tables: db[table].truncate() count = request.args(0) or 100 my_tables = ['users', 'products', 'purchases', 'dogs', 'survey'] for table in my_tables: populate(db[table],int(count)) db.commit() redirect(URL('welcome'))
def reset(): """ Will truncate all tables and populates again with dummy data. """ from gluon.contrib.populate import populate for table in tables: db[table].truncate() count = request.args(0) or 100 my_tables = ['users', 'products', 'purchases', 'dogs', 'survey'] for table in my_tables: populate(db[table], int(count)) db.commit() redirect(URL('welcome'))
def populate_fresh_db(): db.categories.insert(title='katės') db.categories.insert(title='kompai') db.categories.insert(title='dovanoja') from gluon.contrib.populate import populate populate(db.auth_user, 3) populate(db.posts, 10) return dict( categories=db(db.categories).select(), authors=db(db.auth_user).select(), posts=db(db.posts).select(), )
def populate_me(): from gluon.contrib.populate import populate if request.args(0): form = SQLFORM.factory(Field('quantity', 'integer')) if form.process().accepted: qtd = abs(int(form.vars.quantity or 1)) populate(db[request.args(0)], qtd) response.flash = 'Populated with ' + str(qtd) + ' data!' elif form.errors: response.flash = 'oh nooos' rows = db(db[request.args(0)]).select() else: grid = UL(*[LI(A(t, _href=URL(args=t))) for t in db.tables]) return locals()
def test_db(): """ rows: ### consider all people who have dogs db(db.dog.owner==db.person.id).select() input: ### and people meeting these conditions db.person.age>20 db.person.name.like('C%') out: ### what is the probability that row.dog.name # dog names row.dog.age>5 # and the dog is older than 5 """ from gluon.contrib.populate import populate db=DAL() db.define_table('person',Field('name'),Field('age','integer',requires=IS_INT_IN_RANGE(1,80))) db.define_table('dog',Field('name'),Field('owner',db.person),Field('age','integer',requires=IS_INT_IN_RANGE(1,20))) populate(db.person,20) db.commit() populate(db.dog,20) db.commit() rows=db(db.dog.owner==db.person.id).select() input = { 'person mature':True, 'person name with C':True } output = { 'person mature':(lambda row: row.person.age>10), 'person name with C':(lambda row: row.person.name.startswith('C')), 'dog name':(lambda row: row.dog.name), 'dog old':(lambda row: row.dog.age>5) } records=[] for row in rows: d={} records.append(d) for key,f in output.items(): d[key]=f(row) print '%s:%s\t' % (key,d[key]), print bi = NeuralBusinessIntelligence() bi.load_records(records) for key,value in input.items(): try: bi.touch("%s:%s" % (key,value), weight=0.8) except: print 'no data for %s:%s' % (key,value) bi.run()
def test_db(): """ rows: ### consider all people who have dogs db(db.dog.owner==db.person.id).select() input: ### and people meeting these conditions db.person.age>20 db.person.name.like('C%') out: ### what is the probability that row.dog.name # dog names row.dog.age>5 # and the dog is older than 5 """ from gluon.contrib.populate import populate db = DAL() db.define_table('person', Field('name'), Field('age', 'integer', requires=IS_INT_IN_RANGE(1, 80))) db.define_table('dog', Field('name'), Field('owner', db.person), Field('age', 'integer', requires=IS_INT_IN_RANGE(1, 20))) populate(db.person, 20) db.commit() populate(db.dog, 20) db.commit() rows = db(db.dog.owner == db.person.id).select() input = {'person mature': True, 'person name with C': True} output = { 'person mature': (lambda row: row.person.age > 10), 'person name with C': (lambda row: row.person.name.startswith('C')), 'dog name': (lambda row: row.dog.name), 'dog old': (lambda row: row.dog.age > 5) } records = [] for row in rows: d = {} records.append(d) for key, f in output.items(): d[key] = f(row) print '%s:%s\t' % (key, d[key]), print bi = NeuralBusinessIntelligence() bi.load_records(records) for key, value in input.items(): try: bi.touch("%s:%s" % (key, value), weight=0.8) except: print 'no data for %s:%s' % (key, value) bi.run()
def test_financial_dd_category_archive(client, web2py): """ Can we archive a direct debit category? """ # add one to archive populate(web2py.db.payment_categories, 1) assert web2py.db(web2py.db.payment_categories).count() == 1 web2py.db.commit() url = '/settings/financial_dd_category_archive?pcID=1' client.get(url) assert client.status == 200 assert 'Direct debit categories' in client.text # count archived payment methods: should be one now assert web2py.db( web2py.db.payment_categories.Archived == True).count() == 1
def populate_database(): from model import DataBase DataBase(db=db, auth=auth, request=request, tables=['all']) from gluon.contrib.populate import populate skip = ['auth_group', 'auth_permission', 'auth_cas', 'auth_event'] import time try: for table in db.tables(): if table not in skip: print 'populating ' + table populate(db.__getattr__(table), 50) #population is done in a transaction, we need to commit to get the references db.commit() time.sleep(1) except Exception as e: print str(e) return "Done"
def populate(): if not request.is_local: #apsauga, kad viešai pahost'inus negalėtų nieks generuot fake duomenų return "localhost only" from gluon.contrib.populate import populate # /skelbimai/default/populate/<table> # pvz: # /skelbimai/default/populate/auth_user # /skelbimai/default/populate/posts table = request.args[0] if request.vars.extra == 'clear': # /skelbimai/default/populate/posts?extra=clear db(db[table]).delete() populate(db[table], 10) # db yra tarsi lentelių žodynas # populate(db.posts ,10) # db['posts'] return db(db[table]).select()
def generate(): """Content generation function""" ##@todo: use SQLFORM.factory to generate better form! generable_items = ['user', 'node'] form = FORM( TABLE(TBODY( TR( TD(T('Items to generate:')), TD(SELECT( *( [OPTION('Choose one', _value='', _style='font-style:italic;color:#888;')] + [OPTION(i, _value=i) for i in generable_items]), _name='item_type', requires=IS_IN_SET(generable_items))), ), TR( TD(T('Amount:')), TD(INPUT(_name='amount', requires=IS_INT_IN_RANGE(1,1000))), ), TR( TD(INPUT(_name='submit', _type='submit')), _colspan=2, ), )) ) form.process() if form.accepted: response.flash = 'Form accepted. Will generate %(amount)d %(item_type)s(s)' % form.vars if form.vars.item_type == 'node': response.flash = 'Created %(amount)d %(item_type)ss' % form.vars populate(db.node, int(form.vars.amount)) return dict( title=T('Generate'), form=form, )
def generate(): """Content generation function""" ##@todo: use SQLFORM.factory to generate better form! generable_items = ['user', 'node'] form = FORM( TABLE( TBODY( TR( TD(T('Items to generate:')), TD( SELECT(*([ OPTION('Choose one', _value='', _style='font-style:italic;color:#888;') ] + [OPTION(i, _value=i) for i in generable_items]), _name='item_type', requires=IS_IN_SET(generable_items))), ), TR( TD(T('Amount:')), TD(INPUT(_name='amount', requires=IS_INT_IN_RANGE(1, 1000))), ), TR( TD(INPUT(_name='submit', _type='submit')), _colspan=2, ), ))) form.process() if form.accepted: response.flash = 'Form accepted. Will generate %(amount)d %(item_type)s(s)' % form.vars if form.vars.item_type == 'node': response.flash = 'Created %(amount)d %(item_type)ss' % form.vars populate(db.node, int(form.vars.amount)) return dict( title=T('Generate'), form=form, )
def test_school_level_edit(client, web2py): """ Can we edit a school_level? """ populate(web2py.db.school_levels, 1) assert web2py.db(web2py.db.school_levels).count() == 1 url = '/school_properties/level_edit/1' client.get(url) assert client.status == 200 assert 'Edit practice level' in client.text data = dict(id=1, Name='Beginner') client.post(url, data=data) assert client.status == 200 assert 'Practice levels' in client.text # verify redirection assert data['Name'] in client.text assert web2py.db(web2py.db.school_levels).count() > 0
def test_location_edit(client, web2py): """ Can we edit a location? """ populate(web2py.db.school_locations, 1) assert web2py.db(web2py.db.school_locations).count() == 1 url = '/school_properties/location_edit/1' client.get(url) assert client.status == 200 assert 'Edit location' in client.text data = dict(id=1, Name='Maastricht') client.post(url, data=data) assert client.status == 200 assert 'Locations' in client.text # verify redirection assert data['Name'] in client.text assert web2py.db(web2py.db.school_locations).count() > 0
def test_discovery_edit(client, web2py): """ Can we edit a way of discovery? """ populate(web2py.db.school_discovery, 1) assert web2py.db(web2py.db.school_discovery).count() == 1 url = '/school_properties/discovery_edit/1' client.get(url) assert client.status == 200 assert 'Edit way of discovery' in client.text data = dict(id=1, Name='Google') client.post(url, data=data) assert client.status == 200 assert 'Discovery' in client.text # verify redirection assert data['Name'] in client.text assert web2py.db(web2py.db.school_discovery).count() > 0
def init_db(): assert TestDBContext.init == 0 TestDBContext.init = 1 TestDBContext.db_context = DBContext("test.sqlite", lambda table: "%s.test.migrate" % table) db = TestDBContext.db_context.db # populate test database with dummy data populate(db[DBContext.COURSE_TABLE], 100) populate(db[DBContext.NOTE_TABLE], 100) populate(db[DBContext.USER_TABLE], 10) populate(db[DBContext.ENROLLMENT_TABLE], 10)
def test_classtype_edit(client, web2py): """ Can we edit a classtype? """ populate(web2py.db.school_classtypes, 1) assert web2py.db(web2py.db.school_classtypes).count() == 1 url = '/school_properties/classtype_edit/1' client.get(url) assert client.status == 200 assert 'Edit class type' in client.text data = dict(id=1, Name='Mysore style') client.post(url, data=data) assert client.status == 200 assert 'Class types' in client.text # verify redirection assert data['Name'] in client.text assert web2py.db(web2py.db.school_classtypes).count() > 0
def test_financial_dd_categories_edit(client, web2py): """ Can we edit a direct debit category? """ populate(web2py.db.payment_categories, 1) assert web2py.db(web2py.db.payment_categories).count() == 1 url = '/settings/financial_dd_category_edit/1' client.get(url) assert client.status == 200 assert 'Edit direct debit category' in client.text data = dict(id=1, Name='Invoices', CategoryType='1') client.post(url, data=data) assert client.status == 200 assert 'Direct debit categories' in client.text # verify redirection assert data['Name'] in client.text assert web2py.db(web2py.db.payment_categories).count() > 0
def test_shift_add(client, web2py): ''' Can we add a shift? ''' populate_customers(web2py, nr_of_customers=2, employee=True) populate(web2py.db.school_locations, 1) populate(web2py.db.school_shifts, 1) url = '/staff/shift_add' client.get(url) assert client.status == 200 data = dict(school_locations_id='1', school_shifts_id='1', Week_day='1', Starttime='06:00:00', Endtime='08:00:00', Startdate='2014-01-01', ) client.post(url, data=data) assert client.status == 200 assert "Assign employees" in client.text # check redirection to assign employees page url = '/staff/shift_employees_add?shID=1' client.get(url) assert client.status == 200 emp_data = {'shifts_id':1, 'Startdate':data['Startdate'], 'auth_employee_id':1001} client.post(url, data=emp_data) assert client.status == 200 assert 'Edit shift' in client.text # verify redirection # move to schedule page and check display of input url = '/staff/schedule' client.get(url) assert client.status == 200 assert web2py.db(web2py.db.shifts).count() == 1 location = web2py.db.school_locations(1).Name[:10] assert location in client.text
def test_holiday_edit_locations_cancel_bookings_and_refund_credits( client, web2py): ''' Are bookings cancelled and credits returned when editing a holiday? ''' from populate_os_tables import prepare_classes url = '/user/login' client.get(url) assert client.status == 200 prepare_classes(web2py, credits=True) populate(web2py.db.school_locations, 2) shID = web2py.db.school_holidays.insert(Description='test', Startdate='2014-01-01', Enddate='2014-12-31', Classes=True) web2py.db.commit() assert web2py.db(web2py.db.school_holidays).count() == 1 url = '/schedule/holiday_edit_locations?shID=' + str(shID) client.get(url) assert client.status == 200 assert 'Holiday locations' in client.text data = {'1': 'on', '2': 'on'} client.post(url, data=data) assert client.status == 200 assert 'Holidays' in client.text # verify redirection caID = 3 # Check status clatt = web2py.db.classes_attendance(caID) assert clatt.BookingStatus == 'cancelled' # Check credit mutation removed query = (web2py.db.customers_subscriptions_credits.id > 0) assert web2py.db(query).count() == 1
def test_financial_payment_method_archive(client, web2py): """ Can we archive a payment method? """ # Get URL first so the default payment methods (id 1 - 3) get generated url = '/settings/financial_payment_methods' client.get(url) assert client.status == 200 # add one extra to archive populate(web2py.db.payment_methods, 1) assert web2py.db(web2py.db.payment_methods).count() == 5 web2py.db.commit() url = '/settings/financial_payment_method_archive?pmID=101' client.get(url) assert client.status == 200 assert 'Payment methods' in client.text # count archived payment methods: should be one now assert web2py.db(web2py.db.payment_methods.Archived == True).count() == 1
def test_financial_invoices_group_edit(client, web2py): """ Can we edit a invoice group? """ populate(web2py.db.invoices_groups, 1) assert web2py.db(web2py.db.invoices_groups).count() == 1 url = '/settings/financial_invoices_group_edit?igID=1' client.get(url) assert client.status == 200 assert 'Edit invoice group' in client.text data = dict(id=1, Name='Invoices', NextID=1, DueDays=30, InvoicePrefix='INV') client.post(url, data=data) assert client.status == 200 assert 'Groups' in client.text # verify redirection assert data['Name'] in client.text assert web2py.db(web2py.db.invoices_groups).count() > 0
def test_announcement_delete(client, web2py): """ Is the delete permission for an announcement working? """ setup_permission_tests(web2py) populate(web2py.db.announcements, 1) web2py.auth.add_permission(200, 'read', 'announcements', 0) web2py.db.commit() url = '/announcements/index' client.get(url) assert client.status == 200 assert not 'fa-times' in client.text # grant permission and check again web2py.auth.add_permission(200, 'delete', 'announcements', 0) web2py.db.commit() client.get(url) assert client.status == 200 assert 'fa-times' in client.text
def test_get_person_by_creation_date(client, web2py): '''Is my filter working? ''' from gluon.contrib.populate import populate populate(web2py.db.people, 3) # insert 3 persons with random data web2py.db.commit() assert web2py.db(web2py.db.people).count() == 3 data = dict(name='John Smith', phone='3322-4455', created_at='1999-04-03 18:00:00') web2py.db.people.insert(**data) # insert my controlled person web2py.db.commit() client.get('/people/get_by_creation_date.json/' + data['created_at'].split()[0]) assert client.status == 200 assert 'application/json' in client.headers['content-type'] import json person = json.loads(client.text) assert person['name'] == data['name']
def adminuser(): # http://stackoverflow.com/questions/10201300/how-can-i-create-new-auth-user-and-auth-group-on-web2py-running-on-google-app-en if not db().select(db.auth_user.ALL).first(): db.auth_user.insert( username=myconf.get('admin_user.username'), password=db.auth_user.password.validate(myconf.get('admin_user.password'))[0], email=myconf.get('admin_user.email'), first_name=myconf.get('admin_user.first_name'), last_name=myconf.get('admin_user.last_name'), ) user = auth.login_bare( myconf.get('admin_user.username'), myconf.get('admin_user.password') ) authgroups() fixauthgroups() # appstatuses() populate(db.person) populate(db.dog) populate(db.dog_owner) redirect(URL('default', 'index'))
auth.add_permission(manager_group_id, 'manage', 'layers') ## add permissions for regular user auth.add_permission(user_group_id, 'read', db.layers, 0) if db(db.auth_user).isempty(): from gluon.contrib.populate import populate mdp_id = db.auth_user.insert(first_name="Good", last_name='Teacher', email='*****@*****.**', password=CRYPT()('test')[0]) ss_id = db.auth_user.insert(first_name="Svetlin", last_name='Stalinov', email='*****@*****.**', password=CRYPT()('test')[0]) populate(db.auth_user, 8) db(db.auth_user.id > 2).update(is_administrator=False) users = db(db.auth_user).select() org_id = db.organization.insert(name="ss_Solution") for user in users[0:5]: user_id = user.id db.membership.insert(auth_user=user_id, organization=org_id) auth.add_membership(user_group_id, user_id) org_id = db.organization.insert(name="X_Solution") for user in users[5:10]: user_id = user.id db.membership.insert(auth_user=user_id, organization=org_id) auth.add_membership(user_group_id, user_id)
from gluon.contrib import populate if plugins.dialog.DEBUG!=False: plugins.dialog.DEBUG=True if plugins.dialog.MODEL!=False: plugins.dialog.MODEL=True if plugins.dialog.MODEL: db.define_table('plugin_dialog_customer', Field('title', requires=IS_IN_SET(['Mr', 'Mrs', 'Ms'], zero=None)), Field('name', requires=[IS_NOT_EMPTY()]), Field('address1'), Field('address2'), Field('address3'), Field('town'), Field('county')) if db(db.plugin_dialog_customer.id>0).count()==0: populate.populate(db.plugin_dialog_customer,50)
from gluon.contrib.populate import populate if db(db.auth_user).isempty(): populate(db.auth_user,10) populate(db.t_videos,10) populate(db.t_pictures,10)
from gluon.contrib.populate import populate if db(db.auth_user).isempty(): populate(db.auth_user,10) populate(db.t_tbl_components,10)
# -*- coding: utf-8 -*- from plugin_paginator import Paginator, PaginateSelector, PaginateInfo from plugin_solidtable import SOLIDTABLE from gluon.contrib.populate import populate db = DAL('sqlite:memory:') db.define_table('product', Field('name')) populate(db.product, 99) def index(): query = db.product.id > 0 ################################ The core ###################################### paginate_selector = PaginateSelector(anchor='main') paginator = Paginator(paginate=paginate_selector.paginate, extra_vars={'v':1}, anchor='main', renderstyle=True) paginator.records = db(query).count() paginate_info = PaginateInfo(paginator.page, paginator.paginate, paginator.records) rows = db(query).select(limitby=paginator.limitby()) ################################################################################ table = SOLIDTABLE(rows, renderstyle=True) return dict(table=table, paginator=paginator, paginate_selector=paginate_selector, paginate_info=paginate_info)
def populatedb(): populate(db.auth_user, 2) populate(db.boards, 3) populate(db.posts, 12) boards = db(db.boards).select(orderby=db.boards.updated_at) redirect(URL("default", "boards"))
def generate_data(): # populates the database with dummy data from gluon.contrib.populate import populate populate(db.books, 100) return "data generated"
# -*- coding: utf-8 -*- from plugin_solidtable import SOLIDTABLE, OrderbySelector from gluon.contrib.populate import populate db = DAL('sqlite:memory:') db.define_table( 'product', Field('name'), Field('status', requires=IS_IN_SET(['new', 'old'])), Field('description', 'text'), Field('publish_start_date', 'date', label='start'), Field('publish_end_date', 'date', label='end'), Field('price', 'integer', represent=lambda v: '$%s' % v), ) populate(db.product, 10) def index(): tax = db.product.price * 5 / 100 tax.represent = db.product.price.represent pretax_price = db.product.price + tax pretax_price.represent = db.product.price.represent request_headers = request.vars.headers or 'default' request_columns = request.vars.columns or 'default' ################################ The core ###################################### # A custom orderby selector for the solidtable. orderby_selector = OrderbySelector([ db.product.id, db.product.name, ~db.product.publish_start_date, ~pretax_price
from gluon.contrib.populate import populate if db(db.auth_user).isempty(): populate(db.blog_category, 100) db.branch_rating.bulk_insert([{'rating' : 'One Star'}, {'rating' : 'Two Stars'}, {'rating' : 'Three Stars'}, {'rating' : 'Four Stars'}, {'rating' : 'Five Stars'}]) populate(db.branch, 100) populate(db.floor, 100) populate(db.guest, 100) populate(db.news_category, 100) populate(db.news, 100) populate(db.photo_album, 100) db.room_category.bulk_insert([{'category' : 'Single'}, {'category' : 'Double'}, {'category' : 'Suite'}]) db.room_status.bulk_insert([{'status' : 'Available'}, {'status' : 'Booking'}, {'status' : 'Using'}, {'status' : 'Cleaning'}]) populate(db.room, 100) populate(db.booking,
# -*- coding: utf-8 -*- from plugin_solidform import SOLIDFORM from gluon.contrib.populate import populate db = DAL('sqlite:memory:') db.define_table('product', Field('name', requires=IS_NOT_EMPTY()), Field('category'), Field('code', 'integer'), Field('keywords', 'text'), Field('publish_start_date', 'date', label='start'), Field('publish_end_date', 'date', label='end'), Field('description', 'text'), Field('price', 'integer'), Field('point', 'integer'), Field('url', requires=IS_URL()), Field('memo', 'text', comment='(memo)')) populate(db.product, 1) def index(): request_fields = request.vars.fields or 'default' ################################ The core ###################################### # Specify structured fields for the multi-line form layout. # A "None" indicates an empty line over which the precedent line spans if request_fields == 'default': fields = [['name', 'category'], ['code', 'keywords'], ['publish_start_date', None], ['publish_end_date', None], 'url', ['description', 'price'], [None, 'point'], 'memo'] elif request_fields == 'fields_2': fields = [['name', 'category'], None,
Field('valueof', 'string', required=True, notnull=True), Field('item_order', 'integer', required=True, notnull=True), Field('activity', db.activity, required=True, notnull=True), Field('description', 'text'), # redefine=True, migrate=True, format='%(activity)s - %(name)s (%(typeof)s) : %(valueof)s' ) # -- # TODO: from gluon.contrib.populate import populate if ENV_TYPE == 'DEV': populate(db.customer, 100) # populates computed column despite fix for #625 populate(db.customer_attribute, 100) populate(db.activity, 100) populate(db.relation, 100) if db(db.customer.id>0).count(): populate(db.customer,100) if db(db.customer_attribute.id>0).count(): populate(db.customer_attribute,100) if db(db.activity.id>0).count(): populate(db.activity,100) if db(db.relation.id>0).count(): populate(db.relation, 100) # from customvalidator import IS_IN_WHEN_OTHER_IN # modules/customvalidator.py
# comment in the next line every time you change this query # replace = True ) edb.define_view('pvsa', Field('fname', label=T("master first name")), Field('lname', label=T("master last name")), Field('pname', label=T("Pet name")), Field.Virtual('vtest', lambda r: XML(A(I(_class="icon icon-ok"), _class="btn"))), ) # Popuate example tables for table_name in ('padroni', 'animali', ): if edb(edb[table_name].id>0).count()==0: for i in range(2): populate(edb[table_name], 100) db.commit() mytable1 = DataTable(edb.padroni, id='mytable1') if extended_dal: mytable2 = DataTable(edb.pvsa, id='mytable2') # Shortcut menu to the example controller function example_menu = [(T('simple table'), False, URL('plugin_example', 'example1'), )] if extended_dal: example_menu.append((T('view'), False, URL('plugin_example', 'example2'), )) response.menu += [ (T('Examples'), False, None, example_menu, ) ]
label='Difficulty level'), Field('recording', 'string', default=settings.permissions[0], requires=IS_IN_SET(settings.permissions, error_message='Tell us whether we can record your talk'), label='Can we record your talk ?'), Field('status',default='Pending Approval',writable=False,readable=False), Field('file','upload',writable=False, readable=False), Field('country', 'string'), created_by, created_on, format='%(title)s') db.define_table('assignment', Field('paper',db.paper,writable=False,readable=False), Field('reviewer',db.auth_user), created_by, created_on) db.define_table('message', Field('paper',db.paper,writable=False,readable=False), Field('message_type','integer',label='Action',requires=IS_IN_SET(MESSAGE_TYPES)), Field('body','text',label='Message'), Field('file','upload'), created_by, created_on) from gluon.contrib.populate import populate if not settings.production and db(db.auth_user.id>0).count()==1: populate(db.auth_user,25) populate(db.paper,25) db(db.paper.id>0).update(status='Accepted',created_by=2) populate(db.assignment,75) populate(db.message,200)
from gluon.contrib.populate import populate if db(db.auth_user).isempty(): populate(db.auth_user,10) populate(db.t_chat_channels,10) populate(db.t_posts,10)
def get_section_users(section_id): query = (db.membership.course_section==section_id)&(db.membership.auth_user==db.auth_user.id) return db(query).select() def is_user_teacher(section_id, user_id): return db.membership(course_section=section_id, role='teacher', auth_user=user_id) if db(db.auth_user).isempty(): import datetime from gluon.contrib.populate import populate db.auth_user.insert(first_name="Massimo",last_name='Di Pierro', email='*****@*****.**', password=CRYPT()('test')[0]) populate(db.auth_user,500) for k in range(200,300): id = db.course.insert(name="Dummy course", code="CSC%s" % k, prerequisites=[], tags=[], description = 'description...') for s in range(701,703): i = db.course_section.insert( name="CSC%s-%s" % (k,s), course=id, meeting_place="CDM", meeting_time="Tuesday", start_date=datetime.date(2014,9,1), stop_date=datetime.date(2014,12,1), signup_deadline=datetime.date(2014,11,10))
from gluon.contrib.populate import populate if db(db.auth_user).isempty(): populate(db.auth_user,10) populate(db.t_docente,10)
returns a list of users with a role (default STUDENT role) in the section_id """ return db((db.membership.course_section == section_id) & (db.membership.role.belongs(roles))& (db.membership.auth_user == db.auth_user.id)).select(db.auth_user.ALL) #################################################################################################### # Populate some tables so we have data with which to work. if db(db.auth_user).isempty(): import datetime from gluon.contrib.populate import populate mdp_id = db.auth_user.insert(first_name="Good",last_name='Teacher', email='*****@*****.**', password=CRYPT()('test')[0]) populate(db.auth_user,300) db(db.auth_user.id>1).update(is_student=True,is_teacher=False,is_administrator=False) # Add everyone in the auth_user table - except Massimo - to the student group. for k in range(200,300): id = db.course.insert(name="Dummy course", code="CSC%s" % k, prerequisites=[], tags=[], description = 'description...') for s in range(701,703): i = db.course_section.insert( name="CSC%s-%s" % (k,s), course=id, meeting_place="CDM",
def is_user_teacher(section_id, user_id): return db.membership(course_section=section_id, role='teacher', auth_user=user_id) if db(db.auth_user).isempty(): import datetime from gluon.contrib.populate import populate db.auth_user.insert(first_name="Massimo", last_name='Di Pierro', email='*****@*****.**', password=CRYPT()('test')[0]) populate(db.auth_user, 500) for k in range(200, 300): id = db.course.insert(name="Dummy course", code="CSC%s" % k, prerequisites=[], tags=[], description='description...') for s in range(701, 703): i = db.course_section.insert(name="CSC%s-%s" % (k, s), course=id, meeting_place="CDM", meeting_time="Tuesday", start_date=datetime.date(2014, 9, 1), stop_date=datetime.date(2014, 12, 1), signup_deadline=datetime.date( 2014, 11, 10))
from gluon.contrib.populate import populate if not db(db.auth_user).count(): populate(db.auth_user,10)
from gluon.contrib.populate import populate if db(db.auth_user).isempty(): populate(db.auth_user,10) populate(db.t_destinations,10)
## ## >>> db.define_table('mytable',Field('myfield','string')) ## ## Fields can be 'string','text','password','integer','double','boolean' ## 'date','time','datetime','blob','upload', 'reference TABLENAME' ## There is an implicit 'id integer autoincrement' field ## Consult manual for more options, validators, etc. ## ## More API examples for controllers: ## ## >>> db.mytable.insert(myfield='value') ## >>> rows=db(db.mytable.myfield=='value').select(db.mytable.ALL) ## >>> for row in rows: print row.id, row.myfield ######################################################################### ## after defining tables, uncomment below to enable auditing # auth.enable_record_versioning(db) db.define_table('thing', Field('name',requires=IS_NOT_EMPTY()), Field('useless','boolean'), Field('info','text'), Field('filename','upload')) db.define_table('attr',Field('thing','reference thing'),Field('name',requires=IS_NOT_EMPTY())) if db(db.thing).isempty(): from gluon.contrib.populate import populate populate(db.thing,2000) if db(db.attr).isempty(): from gluon.contrib.populate import populate populate(db.attr,5000)