Do you think IIT Guwahati certified course can help you in your career?
No
Introduction🤔
As a python developer, you've probably heard about web2py, which allows python coders to programme dynamically for development. As a result, it eliminates the requirement to start from scratch. In some circumstances, we require fields that can hold a collection of strings, numbers, and references.
This article will discuss list type, contains and other operators in web2py. Web2py supports special field types, which can hold lists of strings, numbers, and references. Operators in web2py give an API to access analogous SQL operators. Other operators in web2py offer an API to access comparable SQL operators.
List Type and Contains in Web2py💻
The following special field types are offered by web2py and can hold lists of strings, numbers, and references.
list:string
list:integer
list:reference <table>
The NoSQL list:string property on Google App Engine is mapped to StringListProperty, whereas the other two are mapped to ListProperty (int). In text fields on relational databases, they are mapped into lists of objects separated by |.
Examples include mapping [1, 2, 3] into |1|2|3|.
The items in lists of strings are escaped, meaning that any | in the item is replaced with a ||. In any case, the user can see through this internal representation.
Let us see another example of how to use list:reference and contains(value). The list:reference and contains(value) operators are beneficial for de-normalizing many-to-many relationships.
>>> db.define_table('tag',Field('name'),format='%(name)s')
<Table tag (id, name)>
>>> db.define_table('product',Field('name'),Field('tags', 'list:reference tag'))
<Table product (id, name, tags)>
>>> a = db.tag.insert(name='red')
>>> b = db.tag.insert(name='green')
>>> c = db.tag.insert(name='blue')
>>> db.product.insert(name='Toy Car', tags=[a, b, c])
1
>>> products = db(db.product.tags.contains(b)).select()
>>> for an item in products:
print item.name, item.tags
Toy Car [1, 2, 3]
>>> for an item in products:
print item.name, db.product.tags.represent(item.tags)
Output
Toy Car red, green, blue
Operators in Web2py🧐
Operators in web2py give an API to access analogous SQL operators. Let's create a table called "log" to keep track of security events, their event time, and severity, where severity is an integer number.
Following are the various operators provided by Web2py:
like: We can use the like operator in fields to match strings. For example:
>>> for row in db(db.log.event.like('port%')).select():
print row.event
...
port scan
ilike: In most databases, like is case-sensitive and is based on the database's collation. We can use ilike when we want the matching not to be case-sensitive. For example:
db.mytable.myfield.ilike('value')
regexp: There is also a regexp method, which operates similarly to the like method but accepts regular expression syntax for the look-up expression. MySQL, Oracle, PostgreSQL, SQLite, and MongoDB are the only databases that support it (with different degrees of support).
contains: The contains method is used to search for a given value in the database, For example:
db.mytable.myfield.contains('value')
The contains method is also used to search for records that contain all values, send a list of values and an optional boolean argument all to the contains method. For example:
upper, lower: The upper and lower methods transform the field value to upper or lower case, and they can be combined with the like operator:
>>> for row in db(db.log.event.upper().like('PORT%')).select():
... print row.event
Output port scan
year, month, day, hour, minutes, seconds: day, month, and year methods are available in the date and DateTime fields. hour, minute, and second options are open in the DateTime and time fields. Here's an example:
>>> for row in db(db.log.event_time.year() > 2018).select():
print row.event
Output port scan xss injection unauthorized login
belongs: The belongs function, which returns true when the field value belongs to the given set (list or tuples), implements the SQL IN operator:
>>> for row in db(db.log.severity.belongs((1, 2))).select():
print row.event
Output port scan xss injection
sum: To add (sum) the values of a particular field from a collection of records, we can use the sum operator. The storage object can be used to get a sum's result. For example:
>>> sum = db.log.severity.sum()
>>> print db().select(sum).first()[sum]
Output 6
avg, min, max: We may also utilise avg, min, and max to get average, minimum, and maximum values for the chosen records. For example:
>>> max = db.log.severity.max()
>>> print db().select(max).first()[max]
Output 3
len: It determines the value of the field's length. Although it typically only works with text or string fields, other sorts of fields might also be compatible, depending on the back end (boolean, integer, etc.). For example:
>>> for row in db(db.log.event.len() > 13).select():
print row.event
Output unauthorized login
startswith, endswith: Additionally, web2py gives specific shortcuts:
A substring can be referred to using an expression. For instance, we can group items whose names begin with the same three characters and choose only one from each group. For example:
db(db.thing).select(distinct = db.thing.name[:3])
Default Values with coalesce and coalesce_zero👇🏻
There are occasions when you need to retrieve a value from the database but also need default values if the value for a record is NULL. Coalesce is a SQL function that does this. There is an equivalent coalesce method in web2py.
For example:
>>> db.define_table('sysuser', Field('username'), Field('fullname'))
<Table sysuser (id, username, fullname)>
>>> db.sysuser.insert(username='max', fullname='Max Power')
1
>>> db.sysuser.insert(username='tim', fullname=None)
2
>>> coa = db.sysuser.fullname.coalesce(db.sysuser.username)
>>> for row in db().select(coa):
print row[coa]
Max Power
tim
Sometimes you need to compute a mathematical equation, however certain fields have the value None when it should be zero. Coalesce zero saves the day by setting None to zero in the query.
Web2py supports particular field types, which can hold lists of strings, numbers, and references.
What is the use of operators in Web2py?
Operators in web2py give an API to access analogous SQL operators.
Define ilike operator in Web2py?
Most databases like case-sensitive and based on the database's collation. We can use ilike when we want the matching not to be case-sensitive.
What is web2py?
The Python programming language was used to create the free and open-source Web2py web application framework.
Is web2py an MVC model?
The development of web2py was influenced by the Ruby on Rails and Django frameworks. In that it stresses rapid growth, favours convention over configuration, and follows the model-view-controller (MVC) architecture paradigm, Web2py is comparable to these frameworks.
Conclusion
In this article, we have extensively discussed the List type, contains, and operators in Web2py.