How to use the pydal.objects.Row function in pydal

To help you get started, we’ve selected a few pydal examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github web2py / pydal / tests / sql.py View on Github external
db.representers = {
            "rows_render": represent,
        }
        db.tt.insert(aa="foo", bb=2)
        rows = db(db.tt.id > 0).select()
        exp1 = [
            Row(aa="ztest", bb="z1", id=rows[0]["id"]),
            Row(aa="zfoo", bb="z2", id=rows[1]["id"]),
        ]
        exp2 = [
            Row(aa="ztest", bb=1, id=rows[0]["id"]),
            Row(aa="zfoo", bb=2, id=rows[1]["id"]),
        ]
        exp3 = [
            Row(aa="test", bb="z1", id=rows[0]["id"]),
            Row(aa="foo", bb="z2", id=rows[1]["id"]),
        ]
        self.assertEqual(rows.render(i=0), exp1[0])
        self.assertEqual(rows.render(i=0, fields=[db.tt.aa, db.tt.bb]), exp1[0])
        self.assertEqual(rows.render(i=0, fields=[db.tt.aa]), exp2[0])
        self.assertEqual(rows.render(i=0, fields=[db.tt.bb]), exp3[0])
        self.assertEqual(list(rows.render()), exp1)
        self.assertEqual(list(rows.render(fields=[db.tt.aa, db.tt.bb])), exp1)
        self.assertEqual(list(rows.render(fields=[db.tt.aa])), exp2)
        self.assertEqual(list(rows.render(fields=[db.tt.bb])), exp3)
        ret = rows.render(i=0)
        rows = db(db.tt.id > 0).select()
        rows.compact = False
        row = rows[0]
        self.assertIn("tt", row)
        self.assertIn("id", row.tt)
        self.assertNotIn("id", row)
github web2py / pydal / pydal / objects.py View on Github external
def _validate(self, **vars):
        errors = Row()
        for key, value in iteritems(vars):
            value, error = getattr(self, key).validate(value, vars.get("id"))
            if error:
                errors[key] = error
        return errors
github emmett-framework / emmett / weppy / tools / auth.py View on Github external
def login_user(self, user):
        """
        login the user = db.auth_user(id)
        """
        user = Row(user)
        for key, value in user.items():
            if callable(value) or key == 'password':
                delattr(user, key)
        session.auth = sdict(
            user=user,
            last_visit=request.now,
            expiration=self.settings.expiration,
            hmac_key=uuid())
        self.update_groups()
github web2py / pydal / pydal / objects.py View on Github external
# lazy virtual field (because of @staticmethod)
                @lazy_virtualfield
                def lazy_shift(instance, row, delta=4): return row.x.number+delta
            db.x.virtualfields.append(MyVirtualFields())

            for row in db(db.x).select():
                print row.number, row.normal_shift, row.lazy_shift(delta=7)

        """
        if not keyed_virtualfields:
            return self
        for row in self.records:
            for (tablename, virtualfields) in iteritems(keyed_virtualfields):
                attributes = dir(virtualfields)
                if tablename not in row:
                    box = row[tablename] = Row()
                else:
                    box = row[tablename]
                updated = False
                for attribute in attributes:
                    if attribute[0] != "_":
                        method = getattr(virtualfields, attribute)
                        if hasattr(method, "__lazy__"):
                            box[attribute] = VirtualCommand(method, row)
                        elif type(method) == types.MethodType:
                            if not updated:
                                virtualfields.__dict__.update(row)
                                updated = True
                            box[attribute] = method()
        return self
github web2py / web2py / gluon / authapi.py View on Github external
def _update_session_user(self, user):
        if global_settings.web2py_runtime_gae:
            user = Row(self.table_user()._filter_fields(user, id=True))
            delattr(user, self.settings.password_field)
        else:
            user = Row(user)
            for key in list(user.keys()):
                value = user[key]
                if callable(value) or key == self.settings.password_field:
                    delattr(user, key)
        current.session.auth = Storage(user=user,
                                       last_visit=current.request.now,
                                       expiration=self.settings.expiration,
                                       hmac_key=web2py_uuid())
        return user
github web2py / pydal / pydal / objects.py View on Github external
def _validate_fields(self, fields, defattr="default", id=None):
        from .validators import CRYPT
        response = Row()
        response.id, response.errors, new_fields = None, Row(), Row()
        for field in self:
            # we validate even if not passed in case it is required
            error = default = None
            if not field.required and not field.compute:
                default = getattr(field, defattr)
                if callable(default):
                    default = default()
            if not field.compute:
                ovalue = fields.get(field.name, default)
                value, error = field.validate(ovalue, id)
            if error:
                response.errors[field.name] = "%s" % error
            elif field.type == 'password' and ovalue == CRYPT.STARS:
                pass
            elif field.name in fields:
github web2py / pydal / pydal / objects.py View on Github external
mode and colnames are not implemented
        """

        item = self.as_dict(**kwargs)
        if serialize:
            return serializers.json(item)
        else:
            return item


def pickle_row(s):
    return Row, (dict(s),)


copyreg.pickle(Row, pickle_row)


class Table(Serializable, BasicStorage):

    """
    Represents a database table

    Example::
        You can create a table as::
            db = DAL(...)
            db.define_table('users', Field('name'))

        And then::

            db.users.insert(name='me') # print db.users._insert(...) to see SQL
            db.users.drop()
github web2py / pydal / pydal / objects.py View on Github external
def as_dict(self, datetime_to_str=False, custom_types=None):
        SERIALIZABLE_TYPES = [str, int, float, bool, list, dict]
        DT_INST = (datetime.date, datetime.datetime, datetime.time)
        if PY2:
            SERIALIZABLE_TYPES += [unicode, long]
        if isinstance(custom_types, (list, tuple, set)):
            SERIALIZABLE_TYPES += custom_types
        elif custom_types:
            SERIALIZABLE_TYPES.append(custom_types)
        d = dict(self)
        for k in list(d.keys()):
            v = d[k]
            if d[k] is None:
                continue
            elif isinstance(v, Row):
                d[k] = v.as_dict()
            elif isinstance(v, Reference):
                d[k] = long(v)
            elif isinstance(v, decimal.Decimal):
                d[k] = float(v)
            elif isinstance(v, DT_INST):
                if datetime_to_str:
                    d[k] = v.isoformat().replace("T", " ")[:19]
            elif not isinstance(v, tuple(SERIALIZABLE_TYPES)):
                del d[k]
        return d

pydal

pyDAL is a Database Abstraction Layer. It generates queries for SQlite, PotsgreSQL, MySQL, and other backends. It was originally part of the web2py frameworks but it is now an independent project. Example: db.define_table("thing",Field("name")) and db.thing.insert(name="Pizza")

BSD-3-Clause
Latest version published 11 days ago

Package Health Score

81 / 100
Full package analysis