예제 #1
0
    def set_properties(self):
        ckeditor = CKEditor(self.db)
        T = current.T
        self.fields = [
            Field("author", "reference auth_user"),
            Field("title", "string", notnull=True),
            Field("description", "text"),
            Field("body_text", "text", notnull=True),
            Field("slug", "text", notnull=True),
        ]

        self.widgets = {"body_text": ckeditor.widget}

        self.visibility = {"author": (False, False)}

        self.representation = {"body_text": lambda row, value: XML(value)}

        self.validators = {
            "title": IS_NOT_EMPTY(),
            "body_text": IS_NOT_EMPTY()
        }

        self.computations = {
            "slug": lambda r: IS_SLUG()(r.title)[0],
        }

        self.labels = {
            "title": T("Your post title"),
            "description": T("Describe your post (markmin allowed)"),
            "body_text": T("The content")
        }
예제 #2
0
    def set_properties(self):
        ckeditor = CKEditor()
        T = current.T
        self.fields = [
            Field("price", "double", notnull=True, default=0),
            Field("manufacturer", "string", notnull=True),
            Field("in_stock", "boolean", notnull=True, default=True),
            Field("info", "text", notnull=True),
            Field("product_size", "string"),
        ]

        self.validators = {
            "info":
            IS_NOT_EMPTY(),
            "manufacturer":
            IS_NOT_EMPTY(),
            "product_size":
            IS_EMPTY_OR(
                IS_IN_SET([("L", T("Large")), ("M", T("Medium")),
                           ("S", T("Small"))],
                          zero=None)),
        }

        self.widgets = {"info": ckeditor.widget}

        self.labels = {
            "price": T("Product Price"),
            "manufacturer": T("Manufacturer name or brand"),
            "in_stock": T("Available?"),
            "info": T("Product specs"),
            "product_size": T("Product size"),
        }
예제 #3
0
    def check_properties(self):
        f = [
            'author', 'author_nickname', 'title', 'description', 'picture',
            'thumbnail', 'draft', 'tags', 'keywords', 'content_type_id',
            'content_type', 'slug', 'search_index', 'publish_date',
            'publish_tz', 'privacy', 'license', 'likes', 'dislikes', 'views',
            'responses', 'favorited', 'subscribers', 'is_active', 'created_on',
            'created_by', 'modified_on', 'modified_by'
        ]
        for name in f:
            if name in [field.name for field in self.fields]:
                raise NameError("You cant use '%s' as field name for content" %
                                name)

        for field in self.fields:
            if field.type == "upload":
                raise TypeError(
                    "You can define field type upload in content table")

        extra = [
            Field("article_id",
                  "reference article",
                  notnull=True,
                  writable=False,
                  readable=False),  # required field
            Field("type_id",
                  "reference content_type",
                  notnull=True,
                  writable=False,
                  readable=False),  # required field
        ]

        self.fields.extend(extra)
예제 #4
0
    def set_properties(self):
        self.fields = [
            Field("content_type"),
            Field("item_id", "integer"),
            Field("slug"),
            Field("reason"),
            Field("details", "text")
        ]

        reasons = ["Publicação não é vegana",
                   "Violação de direitos autorais",
                   "Falta de referências/fontes",
                   "Conteúdo ofensivo",
                   "Publicação falsa/mentirosa",
                   "Usuário falso",
                   "Usuário ofensivo",
                   "Usuário desrespeita os termos e condições da rede",
                   "Outro motivo (Justifique abaixo)"]

        self.validators = {
            "reason": IS_IN_SET(reasons)
        }

        self.labels = {
            "content_type": self.db.T("Content Type"),
            "item_id": self.db.T("Item id"),
            "slug": self.db.T("Item url slug"),
            "reason": self.db.T("Reason"),
            "details": self.db.T("Details")
        }
예제 #5
0
    def _fetch_columns(self):
        tables = self._tables.copy()
        cols = self.db((self.db.COLUMNS.TABSCHEMA == self.schema)
                       & self.not_in_blacklist_condition(
            self.db.COLUMNS.TABNAME)).select()

        for col in cols:
            try:
                tables[col.TABNAME.lower()].append(
                    Field(col.COLNAME.lower(), **self.__params_for_column(col)))
            except SyntaxError:
                try:
                    # Some colnames may have non-ascii characters, wich needs to be removed and passed as rname
                    normalized = normalize('NFKD', col.COLNAME.decode(
                        self.db._db_codec)).encode('ASCII', 'ignore')
                    tables[col.TABNAME.lower()].append(Field(normalized.lower(),
                                                             **self.__params_for_column(
                                                                 col)))
                except SyntaxError as e:
                    # É ascii e ainda sim é funny name. provavelemnte é palavra
                    # reservado no python e fere a regra REGEX_PYTHON_KEYWORDS
                    # todo: É a melhor abordagem? Estamos ignorando por enquanto
                    print e
            except KeyError:
                print "Não foi possível adicionar a coluna %s de %s - tipo %s desconhecido" % (
                    col.COLNAME,
                    col.TABNAME,
                    col.TYPENAME)
        return tables
예제 #6
0
파일: s3fields.py 프로젝트: apocsantos/eden
    def __init__(self,
                 fieldname,
                 type="string",
                 length=None,
                 default=None,
                 required=False,
                 requires="<default>",
                 ondelete="CASCADE",
                 notnull=False,
                 unique=False,
                 uploadfield=True,
                 widget=None,
                 label=None,
                 comment=None,
                 writable=True,
                 readable=True,
                 update=None,
                 authorize=None,
                 autodelete=False,
                 represent=None,
                 uploadfolder=None,
                 compute=None,
                 sortby=None):

        self.sortby = sortby

        Field.__init__(self, fieldname, type, length, default, required,
                       requires, ondelete, notnull, unique, uploadfield,
                       widget, label, comment, writable, readable, update,
                       authorize, autodelete, represent, uploadfolder, compute)
예제 #7
0
 def _vw_opt_flds_select_json(self, opt_tbl, vw_opt_fields):
     ret = []
     args = Storage( rname = opt_tbl._rname or opt_tbl._tablename,
                     tbl= opt_tbl._entopt.vw_pref or opt_tbl._tablename )
     if opt_tbl._entopt.type=='list':
         name_str_json = 'row_to_json(%(rname)s.*) AS %(vw_name)s'
         args.vw_name = args.tbl
         ret.append(name_str_json % args)
         fld = Field(args.vw_name, 'json')
         fld._entopt=Storage(vw_name = args.vw_name,
                                 is_optrow = True)
         vw_opt_fields.append(fld)
     else:
         name_str = '%(rname)s.%(fld)s AS %(vw_name)s'
         for fld in opt_tbl:
             if fld is opt_tbl._entopt.own_FK:
                 continue
             args.fld = fld.name
             if not hasattr(fld, '_entopt'):
                 fld._entopt = Storage()
             if fld._entopt.vw_name:
                 args.vw_name = fld._entopt.vw_name
             else:
                 args.vw_name = fld._entopt.vw_name = '%(tbl)s_%(fld)s' % args
             vw_opt_fields.append(fld)
             ret.append(name_str % args)
     return ret
예제 #8
0
def ref_field(enm, name=None, **kwargs):
    name = name or enm.FK_name
    _type = 'reference '+ enm.own._tablename
    nocahe = kwargs.pop('nocache', None)
    fld = Field(name, _type, **kwargs)
    def _get_enm_rec(id):
        cache = current.cache
        _enm = enm
        _nocahe = nocahe
        if _nocahe:
            enm_rows= _enm.db().select(_enm.own.ALL)
        else:
            enm_rows= _enm.db().select(_enm.own.ALL, cache = (cache.ram,60), cachable=True)
        if enm_rows.first() and id is not None:
            enm_rec = enm_rows.find(lambda row: row.id==id)[0]
        else:
            enm_rec = None
        return enm_rec
    def _get_repr(v, r):
        rec=_get_enm_rec(v)
        if rec:
            repr_fld = hasattr(rec,'code') and rec.code or rec.name
        else:
            repr_fld = None
        return repr_fld
    fld.represent = _get_repr
    fld._enm_rec = _get_enm_rec
    return fld
예제 #9
0
    def set_properties(self):
        T = self.db.T
        self.fields = [
            Field("user_id", "reference auth_user"),
            Field("event_type", "string", notnull=True),
            Field("way", "list:string", notnull=True),
            Field("unikey", unique=True, notnull=True)
        ]

        self.events = self.db.config.get_list('notification', 'event')
        self.ways = self.db.config.get_list('notification', 'way')

        self.validators = {
            "way":
            IS_IN_SET(self.ways, multiple=True),
            "event_type":
            IS_IN_SET([(key, value % ("", "")) for key, value in self.events])
        }

        self.computations = {
            "unikey": lambda row: "%(user_id)s_%(event_type)s" % row
        }

        self.widgets = {"way": SQLFORM.widgets.checkboxes.widget}

        self.labels = {
            "event_type": T("When"),
            "way": T("You want to be notified by")
        }
예제 #10
0
 def set_properties(self):
     self.fields = [
         Field("user_id", "reference auth_user"),
         Field("sender", "reference auth_user"),
         Field("message_text", "text"),
         Field("x")
     ]
예제 #11
0
 def test_factory(self):
     factory_form = SQLFORM.factory(
         Field('field_one', 'string', IS_NOT_EMPTY()),
         Field('field_two', 'string'))
     self.assertEqual(
         factory_form.xml(),
         '<form action="#" enctype="multipart/form-data" method="post"><table><tr id="no_table_field_one__row"><td class="w2p_fl"><label class="" for="no_table_field_one" id="no_table_field_one__label">Field One: </label></td><td class="w2p_fw"><input class="string" id="no_table_field_one" name="field_one" type="text" value="" /></td><td class="w2p_fc"></td></tr><tr id="no_table_field_two__row"><td class="w2p_fl"><label class="" for="no_table_field_two" id="no_table_field_two__label">Field Two: </label></td><td class="w2p_fw"><input class="string" id="no_table_field_two" name="field_two" type="text" value="" /></td><td class="w2p_fc"></td></tr><tr id="submit_record__row"><td class="w2p_fl"></td><td class="w2p_fw"><input type="submit" value="Submit" /></td><td class="w2p_fc"></td></tr></table></form>'
     )
예제 #12
0
 def define_sms_email(self):
     if 'sms_email' in self.db.tables: return self.db.sms_email
     return self.db.define_table(
         'sms_email',
         Field('email'),
         Field('phone', 'string'),
         #Field('credit','integer',default=0),
         migrate=self.migrate)
예제 #13
0
파일: product.py 프로젝트: pigaov10/Movuca
 def set_properties(self):
     self.fields = [
         Field("order_id", "reference product_order"),
         Field("product_id", "integer"),
         Field("quantity", "integer"),
         Field("current_price", "double"),
         Field("product_options")
     ]
예제 #14
0
    def _auth(self):
        """Create a auth instance. """

        auth = Auth(db=self.db, hmac_key=self.local_settings.hmac_key)
        # This may need to be set to True the first time an app is used.
        if not self.local_settings.disable_authentication:
            auth.settings.extra_fields['auth_user'] = [Field('name')]
            auth.define_tables(username=False, signature=False, migrate=True)
        if self.settings_loader:
            self.settings_loader.import_settings(group='auth',
                    storage=auth.settings)
        auth.settings.mailer = self.mail
        auth.settings.verify_email_onaccept = self.verify_email_onaccept
        # Controller tests scripts require login's with same session.
        if self.get_server_mode() == 'test':
            # Resetting the session farks with controller test scripts
            auth.settings.renew_session_onlogin = False
            auth.settings.renew_session_onlogout = False
        else:
            auth.settings.renew_session_onlogin = True
            auth.settings.renew_session_onlogout = True

        host = ''
        request = self.environment['request']
        if 'wsgi' in request.keys():
            if hasattr(request['wsgi'], 'environ') and \
                    request['wsgi'].environ and \
                    'HTTP_HOST' in request['wsgi'].environ:
                host = request['wsgi'].environ['HTTP_HOST']
        elif 'env' in request.keys():
            host = request.env.http_post
        if host:
            auth.messages.verify_email = 'Click on the link http://' + host \
                + '/' + request.application \
                + '/default/user/verify_email/%(key)s to verify your email'
            auth.messages.reset_password = '******' + host \
                + '/' + request.application \
                + '/default/user/reset_password/%(key)s to reset your password'

        # W0108: *Lambda may not be necessary*
        # pylint: disable=W0108
        auth.signature = self.db.Table(self.db, 'auth_signature',
                              Field('created_on',
                                  'datetime',
                                  default=request.now,
                                  represent=lambda x: str(x),
                                  readable=False,
                                  writable=False,
                                  ),
                              Field('updated_on',
                                  'datetime',
                                  default=request.now,
                                  update=request.now,
                                  represent=lambda x: str(x),
                                  readable=False,
                                  writable=False,
                                  ))
        return auth
예제 #15
0
 def define_page(self, migrate=False):
     db = self.db
     if 'page' in db.tables: return db.page
     return db.define_table('page',
                            Field('name',
                                  unique=True,
                                  requires=IS_NOT_EMPTY()),
                            Field('description', 'text', default=''),
                            Field('content', 'text', default=''),
                            migrate=migrate)
예제 #16
0
	def define_box(self):	
		if 'box' in self.db.tables: return self.db.box
		from gluon.dal import Field
		return self.db.define_table('box',
			Field('name',unique=True,required=True),
			Field('setting','text',default='{}'),
			Field('textcontent','text',default=''),
			Field('htmlcontent','text',default=''),
			Field('avatar','upload',autodelete=True),
			migrate=self.migrate)		
예제 #17
0
파일: user.py 프로젝트: goldenboy/Movuca
    def set_properties(self):
        self.fields = [
            Field("user_id", "reference auth_user"),
            Field("writer", "reference auth_user"),
            Field("board_text", "string"),
        ]

        self.visibility = {"user_id": (False, False), "writer": (False, False)}

        self.validators = {"board_text": IS_NOT_EMPTY()}
예제 #18
0
 def _t_post(self):
     self.db.define_table(
         't_post',
         Field('f_user_id',
               'reference auth_user',
               default=self.auth.user_id,
               writable=False,
               readable=False),
         Field('f_description', 'text'),
     )
예제 #19
0
 def define_table(self, migrate=False):
     db = self.db
     if self.table not in db.tables:
         db.define_table(self.table,
                         Field('tablename', writable=False, readable=False),
                         Field('table_id', writable=False, readable=False),
                         Field('name'),
                         Field('filetype'),
                         Field('extension'),
                         Field('filesize', 'double'),
                         Field('filepath',
                               'upload',
                               autodelete=True,
                               uploadfolder=os.path.join(self.path)),
                         Field('created_by',
                               'integer',
                               default=self.auth.user_id or 1,
                               writable=False,
                               readable=False),
                         Field('created_on',
                               'datetime',
                               default=current.request.now,
                               writable=False,
                               readable=False),
                         migrate=migrate)
     db[self.table].tablename.default = self.tablename
     db[self.table].table_id.default = self.table_id
     return db[self.table]
예제 #20
0
 def define_comment(self, migrate=False):
     if 'tcomment' in self.db.tables: return self.db.tcomment
     from gluon.dal import Field
     from plugin_ckeditor import CKEditor
     ckeditor = CKEditor(self.db)
     return self.db.define_table('tcomment',
                                 Field('tablename'),
                                 Field('table_id', 'integer'),
                                 Field('objects_id', 'integer'),
                                 Field('procedures', 'integer'),
                                 Field('process', 'integer'),
                                 Field('auth_group', 'list:integer'),
                                 Field('txtcontent',
                                       'text',
                                       length=16777215,
                                       widget=ckeditor.widget),
                                 Field('created_by',
                                       'integer',
                                       default=self.auth.user_id or 1,
                                       writable=False,
                                       readable=False),
                                 Field('created_on',
                                       'datetime',
                                       default=current.request.now,
                                       writable=False,
                                       readable=False),
                                 migrate=migrate)
예제 #21
0
 def define_tables(self):
     """Define needed tables for the extension manager.
     This is automatically called by constructor if a valid ``db``
     is passed.
     """
     from gluon.dal import Field
     db = self.db
     db.define_table(
         'system_modules',
         Field('name', 'string', length=128, required=True, notnull=True, unique=True),
         Field('status', 'boolean', default=False),
         )
예제 #22
0
def myform():
    form = SQLFORM.factory(Field('first_name', 'string'),
                           Field('last_name', 'string'))

    def onvalidation(form):
        pass

    if form.process(session=application.session,
                    onvaliidation=onvalidation).accepted:
        redirect(URL())

    return dict(form=form)
예제 #23
0
    def __init__(
        self,
        fieldname,
        type="string",
        length=None,
        default=None,
        required=False,
        requires="<default>",
        ondelete="CASCADE",
        notnull=False,
        unique=False,
        uploadfield=True,
        widget=None,
        label=None,
        comment=None,
        writable=True,
        readable=True,
        update=None,
        authorize=None,
        autodelete=False,
        represent=None,
        uploadfolder=None,
        compute=None,
        sortby=None,
    ):

        self.sortby = sortby

        Field.__init__(
            self,
            fieldname,
            type,
            length,
            default,
            required,
            requires,
            ondelete,
            notnull,
            unique,
            uploadfield,
            widget,
            label,
            comment,
            writable,
            readable,
            update,
            authorize,
            autodelete,
            represent,
            uploadfolder,
            compute,
        )
예제 #24
0
파일: product.py 프로젝트: pigaov10/Movuca
 def set_properties(self):
     self.fields = [
         Field("buyer", "reference auth_user"),
         Field("seller", "reference auth_user"),
         Field("total_items", "integer"),
         Field("total_value", "double"),
         Field("ship_address", "reference product_address"),
         Field("notes", "text"),
         Field("coupom"),
         Field("discount"),
         Field("discount_type"),
         Field("status"),
     ]
예제 #25
0
파일: article.py 프로젝트: pigaov10/Movuca
    def set_properties(self):
        self.fields = [
            Field("comment_id", "reference article_comments", notnull=True),
            Field("user_id", "reference auth_user", notnull=True),
            Field("vote", "integer", notnull=True, default=1),
            Field("unikey", unique=True, notnull=True)
        ]

        self.validators = {"vote": IS_IN_SET([(0, "Down"), (1, "Up")])}

        self.computations = {
            "unikey": lambda row: "%(user_id)s_%(comment_id)s_%(vote)s" % row
        }
예제 #26
0
def edit():
    form = SQLFORM.factory(
        Field('first_name',
              'string',
              requires=IS_NOT_EMPTY(error_message='Please enter first name')),
        Field('last_name',
              'string',
              requires=IS_NOT_EMPTY(error_message='Please enter last name')),
        _action=URL('experiments', 'default', 'edit'))

    if form.process(session=application.session).accepted:
        redirect(URL())

    return {'form': form}
예제 #27
0
파일: article.py 프로젝트: pigaov10/Movuca
    def set_properties(self):
        self.fields = [
            Field("article_id", "reference article", notnull=True),
            Field("user_id", "reference auth_user", notnull=True),
            Field("nickname", notnull=True),
            Field("parent_id", "reference article_comments"),
            Field("replies", "integer", notnull=True, default=0),
            Field("comment_text", "text", notnull=True),
            Field("commenttime", "datetime"),
            Field("answer", "boolean", default=False),
        ]

        self.visibility = {
            "article_id": (False, False),
            "user_id": (False, False),
            "parent_id": (False, False),
            "commenttime": (False, False),
            "replies": (False, False),
            "answer": (False, False),
        }

        self.computations = {
            "nickname": lambda r: self.db.auth_user[r.user_id].nickname
        }

        self.validators = {"comment_text": IS_LENGTH(1024, 2)}
예제 #28
0
    def set_properties(self):
        """
        """

        self.fields = [
            Field('first_name',
                  'string',
                  requires=IS_NOT_EMPTY('Please enter a first name')),
            Field('last_name',
                  'string',
                  requires=IS_NOT_EMPTY('Please enter a last name')),
            Field('email',
                  'string',
                  requires=IS_EMAIL(error_message='Enter a valid email'))
        ]
예제 #29
0
 def _t_comment(self):
     self.db.define_table(
         't_comment',
         Field('f_user_id',
               'reference auth_user',
               default=self.auth.user_id,
               writable=False,
               readable=False),
         Field('f_post_id', 'reference t_post'),
         Field('f_comment', 'text'),
         Field('f_created_on',
               'datetime',
               default=self.request.now,
               writable=False),
     )
예제 #30
0
    def set_properties(self):
        self.fields = [
            Field("user_id", "reference auth_user"),
            Field("nickname", "string"),
            Field("event_type", "string"),
            Field("event_to", "string"),
            Field("event_reference", "integer"),
            Field("event_text", "text"),
            Field("event_image", "string"),
            Field("event_link", "string"),
            Field("event_image_to", "string"),
            Field("event_link_to", "string"),
        ]

        self.representation = {"created_on": lambda v: self.db.pdate(v)}
예제 #31
0
 def set_properties(self):
     self.fields = [
         Field("user_id", "reference auth_user"),
         Field("event_type", "string", notnull=True),
         Field("event_text", "string"),
         Field("event_link", "string"),
         Field("event_reference", "integer"),
         Field("event_image", "string"),
         Field("mail_sent", "boolean", default=False),
         Field("is_read", "boolean", default=False),
         Field("kwargs", "text"),
     ]
예제 #32
0
 def testDALcache(self):
     s = Storage({'application': 'admin', 'folder': 'applications/admin'})
     cache = Cache(s)
     db = DAL(check_reserved=['all'])
     db.define_table('t_a', Field('f_a'))
     db.t_a.insert(f_a='test')
     db.commit()
     a = db(db.t_a.id > 0).select(cache=(cache.ram, 60), cacheable=True)
     b = db(db.t_a.id > 0).select(cache=(cache.ram, 60), cacheable=True)
     self.assertEqual(a.as_csv(), b.as_csv())
     c = db(db.t_a.id > 0).select(cache=(cache.disk, 60), cacheable=True)
     d = db(db.t_a.id > 0).select(cache=(cache.disk, 60), cacheable=True)
     self.assertEqual(c.as_csv(), d.as_csv())
     self.assertEqual(a.as_csv(), c.as_csv())
     self.assertEqual(b.as_csv(), d.as_csv())
     e = db(db.t_a.id > 0).select(cache=(cache.disk, 60))
     f = db(db.t_a.id > 0).select(cache=(cache.disk, 60))
     self.assertEqual(e.as_csv(), f.as_csv())
     self.assertEqual(a.as_csv(), f.as_csv())
     g = db(db.t_a.id > 0).select(cache=(cache.ram, 60))
     h = db(db.t_a.id > 0).select(cache=(cache.ram, 60))
     self.assertEqual(g.as_csv(), h.as_csv())
     self.assertEqual(a.as_csv(), h.as_csv())
     db.t_a.drop()
     db.close()
예제 #33
0
    def setUp(self):
        request = Request(env={})
        request.application = 'a'
        request.controller = 'c'
        request.function = 'f'
        request.folder = 'applications/admin'
        response = Response()
        session = Session()
        T = translator('', 'en')
        session.connect(request, response)
        from gluon.globals import current
        current.request = request
        current.response = response
        current.session = session
        current.T = T
        self.db = DAL(DEFAULT_URI, check_reserved=['all'])
        self.auth = Auth(self.db)
        self.auth.define_tables(username=True, signature=False)
        self.db.define_table('t0', Field('tt'), self.auth.signature)
        self.auth.enable_record_versioning(self.db)
        # Create a user
        self.db.auth_user.insert(first_name='Bart',
                                 last_name='Simpson',
                                 username='******',
                                 email='*****@*****.**',
                                 password='******',
                                 registration_key=None,
                                 registration_id=None)

        self.db.commit()