Package s3 :: Module s3utils
[frames] | no frames]

Module s3utils

source code

Utilities


Requires: gluon

Copyright: (c) 2010-2019 Sahana Software Foundation

License: MIT

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Classes
  S3PriorityRepresent
Color-coded representation of priorities
  Traceback
Generate the traceback for viewing error Tickets
  S3CustomController
Base class for custom controllers (template/controllers.py), implements common helper functions
  S3TypeConverter
Universal data type converter
  S3MultiPath
Simplified path toolkit for managing multi-ancestor-hypergraphs in a relational database.
  StringTemplateParser
Helper to parse string templates with named keys
  S3MarkupStripper
Simple markup stripper
Functions
 
s3_get_last_record_id(tablename)
Reads the last record ID for a resource from a session
source code
 
s3_store_last_record_id(tablename, record_id)
Stores a record ID for a resource in a session
source code
 
s3_remove_last_record_id(tablename=None)
Clears one or all last record IDs stored in a session
source code
 
s3_validate(table, field, value, record=None)
Validates a value for a field
source code
 
s3_represent_value(field, value=None, record=None, linkto=None, strip_markup=False, xml_escape=False, non_xml_output=False, extended_comments=False)
Represent a field value
source code
 
s3_dev_toolbar()
Developer Toolbar - ported from gluon.Response.toolbar() Shows useful stuff at the bottom of the page in Debug mode
source code
 
s3_required_label(field_label)
Default HTML for labels of required form fields
source code
 
s3_mark_required(fields, mark_required=None, label_html=None, map_names=None)
Add asterisk to field label if a field is required
source code
 
s3_addrow(form, label, widget, comment, formstyle, row_id, position=-1)
Add a row to a form, applying formstyle
source code
 
s3_truncate(text, length=48, nice=True)
Nice truncating of text
source code
 
s3_datatable_truncate(string, maxlength=40)
Representation method to override the dataTables-internal truncation of strings per field, like:
source code
 
s3_trunk8(selector=None, lines=None, less=None, more=None)
Intelligent client-side text truncation
source code
 
s3_text_represent(text, truncate=True, lines=5, _class=None)
Representation function for text fields with intelligent truncation and preserving whitespace.
source code
 
s3_format_fullname(fname=None, mname=None, lname=None, truncate=True)
Formats the full name of a person
source code
 
s3_fullname(person=None, pe_id=None, truncate=True)
Returns the full name of a person
source code
 
s3_fullname_bulk(record_ids=None, truncate=True)
Returns the full name for a set of Persons - currently unused
source code
 
s3_comments_represent(text, show_link=True)
Represent Comments Fields
source code
 
s3_phone_represent(value)
Ensure that Phone numbers always show as LTR...
source code
 
s3_url_represent(url)
Make URLs clickable
source code
 
s3_URLise(text)
Convert all URLs in a text into an HTML <A> tag.
source code
 
s3_avatar_represent(user_id, tablename="auth_user", gravatar=False, **attr)
Represent a User as their profile picture or Gravatar
source code
 
s3_auth_user_represent(user_id, row=None)
Represent a user as their email address
source code
 
s3_auth_user_represent_name(user_id, row=None)
Represent users by their names
source code
 
s3_yes_no_represent(value)
Represent a Boolean field as Yes/No instead of True/False
source code
 
s3_redirect_default(location="", how=303, client_side=False, headers=None)
Redirect preserving response messages, useful when redirecting from index() controllers.
source code
 
s3_include_debug_css()
Generates html to include the css listed in...
source code
 
s3_include_debug_js()
Generates html to include the js scripts listed in...
source code
 
s3_include_ext()
Add ExtJS CSS & JS into a page for a Map...
source code
 
s3_include_underscore()
Add Undercore JS into a page...
source code
 
s3_is_mobile_client(request)
Simple UA Test whether client is a mobile device
source code
 
s3_populate_browser_compatibility(request)
Use WURFL for browser compatibility detection
source code
 
s3_filename(filename)
Convert a string into a valid filename on all OS http://stackoverflow.com/questions/295135/turn-a-string-into-a-valid-filename-in-python/698714#698714
source code
 
s3_has_foreign_key(field, m2m=True)
Check whether a field contains a foreign key constraint
source code
 
s3_get_foreign_key(field, m2m=True)
Resolve a field type into the name of the referenced table, the referenced key and the reference type (M:1 or M:N)
source code
 
s3_unicode(s, encoding="utf-8")
Convert an object into an unicode instance, to be used instead of unicode(s)
source code
 
s3_str(s)
Unicode-safe conversion of an object s into a utf-8 encoded str, to be used instead of str(s)
source code
 
s3_flatlist(nested)
Iterator to flatten mixed iterables of arbitrary depth
source code
 
s3_set_match_strings(matchDict, value)
Helper method for gis_search_ac and org_search_ac Find which field the search term matched & where
source code
 
s3_orderby_fields(table, orderby, expr=False)
Introspect and yield all fields involved in a DAL orderby expression.
source code
 
s3_get_extension(request=None)
Get the file extension in the path of the request
source code
 
s3_set_extension(url, extension=None)
Add a file extension to the path of a url, replacing all other extensions in the path.
source code
 
search_vars_represent(search_vars)
Unpickle and convert saved search form variables into a human-readable HTML.
source code
 
s3_jaro_winkler(str1, str2)
Return Jaro_Winkler distance of two strings (between 0.0 and 1.0)
source code
 
s3_jaro_winkler_distance_row(row1, row2)
Calculate the percentage match for two db records
source code
 
soundex(name, len=4)
Code referenced from http://code.activestate.com/recipes/52213-soundex-algorithm/
source code
 
sort_dict_by_values(adict)
Sort a dict by value and return an OrderedDict...
source code
 
URL2(a=None, c=None, r=None)
Modified version of URL from gluon/html.py
source code
 
s3_strip_markup(text) source code
Variables
  URLSCHEMA = re.compile(r"((?:(())(www\.([^/?#\s]*))|((http(s)?...
  RCVARS = "rcvars"
Function Details

s3_get_last_record_id(tablename)

source code 

Reads the last record ID for a resource from a session

Parameters:
  • table - the the tablename

s3_store_last_record_id(tablename, record_id)

source code 

Stores a record ID for a resource in a session

Parameters:
  • tablename - the tablename
  • record_id - the record ID to store

s3_remove_last_record_id(tablename=None)

source code 

Clears one or all last record IDs stored in a session

Parameters:
  • tablename - the tablename, None to remove all last record IDs

s3_validate(table, field, value, record=None)

source code 

Validates a value for a field

Parameters:
  • table - Table
  • field - Field or name of the field
  • value - value to validate
  • record - the existing database record, if available
Returns:
tuple (value, error)

s3_represent_value(field, value=None, record=None, linkto=None, strip_markup=False, xml_escape=False, non_xml_output=False, extended_comments=False)

source code 

Represent a field value

Parameters:
  • field - the field (Field)
  • value - the value
  • record - record to retrieve the value from
  • linkto - function or format string to link an ID column
  • strip_markup - strip away markup from representation
  • xml_escape - XML-escape the output
  • non_xml_output - Needed for output such as pdf or xls
  • extended_comments - Typically the comments are abbreviated

s3_dev_toolbar()

source code 

Developer Toolbar - ported from gluon.Response.toolbar() Shows useful stuff at the bottom of the page in Debug mode

s3_required_label(field_label)

source code 

Default HTML for labels of required form fields

s3_mark_required(fields, mark_required=None, label_html=None, map_names=None)

source code 

Add asterisk to field label if a field is required

Parameters:
  • fields - list of fields (or a table)
  • mark_required - list of field names which are always required
  • label_html - function to render labels of requried fields
  • map_names - dict of alternative field names and labels {fname: (name, label)}, used for inline components
Returns:
tuple, (dict of form labels, has_required) with has_required indicating whether there are required fields in this form

s3_addrow(form, label, widget, comment, formstyle, row_id, position=-1)

source code 

Add a row to a form, applying formstyle

Parameters:
  • form - the FORM
  • label - the label
  • widget - the widget
  • comment - the comment
  • formstyle - the formstyle
  • row_id - the form row HTML id
  • position - position where to insert the row

s3_truncate(text, length=48, nice=True)

source code 

Nice truncating of text

Parameters:
  • text - the text
  • length - the maximum length
  • nice - do not truncate words

s3_datatable_truncate(string, maxlength=40)

source code 

Representation method to override the dataTables-internal truncation
of strings per field, like:

if not r.id and not r.method:
    table.field.represent = lambda string:                                     s3_datatable_truncate(string, maxlength=40)

@param string: the string
@param maxlength: the maximum string length

@note: the JS click-event will be attached by s3.ui.datatable.js

s3_trunk8(selector=None, lines=None, less=None, more=None)

source code 

Intelligent client-side text truncation

Parameters:
  • selector - the jQuery selector (default: .s3-truncate)
  • lines - maximum number of lines (default: 1)

s3_text_represent(text, truncate=True, lines=5, _class=None)

source code 

Representation function for text fields with intelligent truncation and preserving whitespace.

Parameters:
  • text - the text
  • truncate - whether to truncate or not
  • lines - maximum number of lines to show
  • _class - CSS class to use for truncation (otherwise using the text-body class itself)

s3_format_fullname(fname=None, mname=None, lname=None, truncate=True)

source code 

Formats the full name of a person

Parameters:
  • fname - the person's pr_person.first_name value
  • mname - the person's pr_person.middle_name value
  • lname - the person's pr_person.last_name value
  • truncate - truncate the name to max 24 characters

s3_fullname(person=None, pe_id=None, truncate=True)

source code 

Returns the full name of a person

Parameters:
  • person - the pr_person record or record_id
  • pe_id - alternatively, the person entity ID
  • truncate - truncate the name to max 24 characters

s3_fullname_bulk(record_ids=None, truncate=True)

source code 

Returns the full name for a set of Persons
- currently unused

@param record_ids: a list of record_ids
@param truncate: truncate the name to max 24 characters

s3_comments_represent(text, show_link=True)

source code 

Represent Comments Fields

s3_phone_represent(value)

source code 

Ensure that Phone numbers always show as LTR
- otherwise + appears at the end which looks wrong even in RTL

s3_url_represent(url)

source code 

Make URLs clickable

s3_URLise(text)

source code 

Convert all URLs in a text into an HTML <A> tag.

Parameters:
  • text - the text

s3_avatar_represent(user_id, tablename="auth_user", gravatar=False, **attr)

source code 

Represent a User as their profile picture or Gravatar

Parameters:
  • tablename - either "auth_user" or "pr_person" depending on which table the 'user_id' refers to
  • attr - additional HTML attributes for the IMG(), such as _class

s3_auth_user_represent(user_id, row=None)

source code 

Represent a user as their email address

s3_auth_user_represent_name(user_id, row=None)

source code 

Represent users by their names

s3_yes_no_represent(value)

source code 

Represent a Boolean field as Yes/No instead of True/False

s3_redirect_default(location="", how=303, client_side=False, headers=None)

source code 

Redirect preserving response messages, useful when redirecting from index() controllers.

Parameters:
  • location - the url where to redirect
  • how - what HTTP status code to use when redirecting
  • client_side - if set to True, it triggers a reload of the entire page when the fragment has been loaded as a component
  • headers - response headers

s3_include_debug_css()

source code 

Generates html to include the css listed in
    /modules/templates/<theme>/css.cfg

s3_include_debug_js()

source code 

Generates html to include the js scripts listed in
    /static/scripts/tools/sahana.js.cfg

s3_include_ext()

source code 

Add ExtJS CSS & JS into a page for a Map
- since this is normally run from MAP.xml() it is too late to insert into
  s3.[external_]stylesheets, so must inject sheets into correct order

s3_include_underscore()

source code 

Add Undercore JS into a page
- for Map templates
- for templates in GroupedOptsWidget comment

s3_is_mobile_client(request)

source code 

Simple UA Test whether client is a mobile device

s3_populate_browser_compatibility(request)

source code 

Use WURFL for browser compatibility detection

To Do: define a list of features to store

s3_filename(filename)

source code 

Convert a string into a valid filename on all OS
http://stackoverflow.com/questions/295135/turn-a-string-into-a-valid-filename-in-python/698714#698714

- currently unused

s3_has_foreign_key(field, m2m=True)

source code 

Check whether a field contains a foreign key constraint

Parameters:
  • field - the field (Field instance)
  • m2m - also detect many-to-many links

Note: many-to-many references (list:reference) are not DB constraints, but pseudo-references implemented by the DAL. If you only want to find real foreign key constraints, then set m2m=False.

s3_get_foreign_key(field, m2m=True)

source code 

Resolve a field type into the name of the referenced table, the referenced key and the reference type (M:1 or M:N)

Parameters:
  • field - the field (Field instance)
  • m2m - also detect many-to-many references
Returns:
tuple (tablename, key, multiple), where tablename is the name of the referenced table (or None if this field has no foreign key constraint), key is the field name of the referenced key, and multiple indicates whether this is a many-to-many reference (list:reference) or not.

Note: many-to-many references (list:reference) are not DB constraints, but pseudo-references implemented by the DAL. If you only want to find real foreign key constraints, then set m2m=False.

s3_unicode(s, encoding="utf-8")

source code 

Convert an object into an unicode instance, to be used instead of unicode(s)

Parameters:
  • s - the object
  • encoding - the character encoding

s3_str(s)

source code 

Unicode-safe conversion of an object s into a utf-8 encoded str, to be used instead of str(s)

Parameters:
  • s - the object

Note: assumes utf-8, for other character encodings use explicit:

  • s3_unicode(s, encoding=<in>).encode(<out>)

s3_flatlist(nested)

source code 

Iterator to flatten mixed iterables of arbitrary depth

s3_set_match_strings(matchDict, value)

source code 

Helper method for gis_search_ac and org_search_ac Find which field the search term matched & where

Parameters:
  • matchDict - usually the record
  • value - the search term

s3_orderby_fields(table, orderby, expr=False)

source code 

Introspect and yield all fields involved in a DAL orderby expression.

Parameters:
  • table - the Table
  • orderby - the orderby expression
  • expr - True to yield asc/desc expressions as they are, False to yield only Fields

s3_get_extension(request=None)

source code 

Get the file extension in the path of the request

Parameters:
  • request - the request object (web2py request or S3Request), defaults to current.request

s3_set_extension(url, extension=None)

source code 

Add a file extension to the path of a url, replacing all other extensions in the path.

Parameters:
  • url - the URL (as string)
  • extension - the extension, defaults to the extension of current. request

search_vars_represent(search_vars)

source code 

Unpickle and convert saved search form variables into a human-readable HTML.

Parameters:
  • search_vars - the (c)pickled search form variables
Returns:
HTML as string

s3_jaro_winkler(str1, str2)

source code 

Return Jaro_Winkler distance of two strings (between 0.0 and 1.0)

Used as a measure of similarity between two strings

Parameters:
  • str1 - the first string
  • str2 - the second string

Status: currently unused

s3_jaro_winkler_distance_row(row1, row2)

source code 

Calculate the percentage match for two db records

To Do: parameter description?

Status: currently unused

soundex(name, len=4)

source code 

Code referenced from http://code.activestate.com/recipes/52213-soundex-algorithm/

To Do: parameter description?

sort_dict_by_values(adict)

source code 

Sort a dict by value and return an OrderedDict
- used by modules/eden/irs.py

URL2(a=None, c=None, r=None)

source code 

Modified version of URL from gluon/html.py

  • used by views/layout_iframe.html for our jquery function

s3_strip_markup(text)

source code 

Variables Details

URLSCHEMA

Value:
re.compile(r"((?:(())(www\.([^/?#\s]*))|((http(s)?|ftp):)" r"(//([^/?#\
\s]*)))([^?#\s]*)(\?([^#\s]*))?(#([^\s]*))?)")

RCVARS

Value:
"rcvars"