web2py documentation - read the docs

196
web2py Documentation Release 2.14.6-stable web2py-developers Nov 01, 2018

Upload: others

Post on 07-Feb-2022

10 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: web2py Documentation - Read the Docs

web2py DocumentationRelease 2146-stable

web2py-developers

Nov 01 2018

Contents

1 admin Module 311 Utility functions for the Admin application 3

2 cache Module 721 Basic caching classes and methods 7

3 cfs Module 931 Functions required to execute app components 9

4 compileapp Module 1141 Functions required to execute app components 11

5 contenttype Module 15

6 custom_import Module 1761 Support for smart import syntax for web2py applications 17

7 dal Module 1971 Takes care of adapting pyDAL to web2pyrsquos needs 19

8 debug Module 2181 Debugger support classes 21

9 decoder Module 23

10 fileutils Module 25101 File operations 25

11 globals Module 27

12 highlight Module 33

13 html Module 35131 Template helpers 35

14 http Module 51141 HTTP statuses helpers 51

i

15 languages Module 53151 Translation system 53

16 main Module 57161 The gluon wsgi application 57

17 messageboxhandler Module 59

18 myregex Module 61181 Useful regexes 61

19 newcron Module 63

20 portalocker Module 65

21 recfile Module 67211 Generates names for cache and session files 67

22 restricted Module 69221 Restricted environment to execute applicationrsquos code 69

23 rewrite Module 71

24 sanitizer Module 75241 Cross-site scripting (XSS) defense 75

25 scheduler Module 77251 Background processes made simple 77

26 serializers Module 83

27 settings Module 85

28 shell Module 87281 Web2py environment in the shell 87

29 sql Module 89291 Just for backward compatibility 89

30 sqlhtml Module 97

31 storage Module 107

32 streamer Module 111321 Facilities to handle file streaming 111

33 template Module 113331 Templating syntax 113

34 tools Module 117341 Auth Mail PluginManager and various utilities 117

35 utf8 Module 139351 Utilities and class for UTF8 strings managing 139

36 utils Module 143361 This file specifically includes utilities for security 143

ii

37 validators Module 145371 Validators 145

38 widget Module 171381 The widget is called from web2py 171

39 xmlrpc Module 173

40 Indices and tables 175

Python Module Index 177

iii

iv

web2py Documentation Release 2146-stable

Contents

Contents 1

web2py Documentation Release 2146-stable

2 Contents

CHAPTER 1

admin Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

11 Utility functions for the Admin application

gluonadminadd_path_first(path)

gluonadminapath(path=rdquo r=None)Builds a path inside an application folder

Parameters

bull path (str) ndash path within the application folder

bull r ndash the global request object

gluonadminapp_cleanup(app request)Removes session cache and error files

Parameters

bull app (str) ndash application name

bull request ndash the global request object

Returns True if everything went ok False otherwise

gluonadminapp_compile(app request skip_failed_views=False)Compiles the application

Parameters

bull app (str) ndash application name

bull request ndash the global request object

3

web2py Documentation Release 2146-stable

Returns None if everything went ok traceback text if errors are found

gluonadminapp_create(app request force=False key=None info=False)Create a copy of welcomew2p (scaffolding) app

Parameters

bull app (str) ndash application name

bull request ndash the global request object

gluonadminapp_install(app fobj request filename overwrite=None)Installs an application

bull Identifies file type by filename

bull Writes fobj contents to the deposit folder

bull Calls w2p_unpack() to do the job

Parameters

bull app (str) ndash new application name

bull fobj (obj) ndash file object containing the application to be installed

bull request ndash the global request object

bull filename (str) ndash original filename of the fobj required to determine extension

bull overwrite (bool) ndash force overwrite of existing application

Returns name of the file where app is temporarily stored or None on failure

gluonadminapp_pack(app request raise_ex=False filenames=None)Builds a w2p package for the application

Parameters

bull app (str) ndash application name

bull request ndash the global request object

Returns filename of the w2p file or None on error

gluonadminapp_pack_compiled(app request raise_ex=False)Builds a w2p bytecode-compiled package for the application

Parameters

bull app (str) ndash application name

bull request ndash the global request object

Returns filename of the w2p file or None on error

gluonadminapp_uninstall(app request)Uninstalls the application

Parameters

bull app (str) ndash application name

bull request ndash the global request object

Returns True on success False on failure

4 Chapter 1 admin Module

web2py Documentation Release 2146-stable

gluonadmincheck_new_version(myversion version_url)Compares current web2pyrsquos version with the latest stable web2py version

Parameters

bull myversion ndash the current version as stored in file web2pyVERSION

bull version_URL ndash the URL that contains the version of the latest stable release

Returns

state version

bull state True if upgrade available False if current version is up-to-date -1 on error

bull version the most up-to-version available

Return type tuple

gluonadmincreate_missing_app_folders(request)

gluonadmincreate_missing_folders()

gluonadminplugin_install(app fobj request filename)Installs a plugin

bull Identifies file type by filename

bull Writes fobj contents to the deposit folder

bull Calls w2p_unpack_plugin() to do the job

Parameters

bull app (str) ndash new application name

bull fobj ndash file object containing the application to be installed

bull request ndash the global request object

bull filename ndash original filename of the fobj required to determine extension

Returns name of the file where plugin is temporarily stored or False on failure

gluonadminplugin_pack(app plugin_name request)Builds a w2p package for the plugin

Parameters

bull app (str) ndash application name

bull plugin_name (str) ndash the name of the plugin without plugin_ prefix

bull request ndash the current request app

Returns filename of the w2p file or False on error

gluonadminunzip(filename dir subfolder=rdquo)Unzips filename into dir (zip only no gz etc)

Parameters

bull filename (str) ndash archive

bull dir (str) ndash destination

bull subfolder (str) ndash if = lsquorsquo unzips only files in subfolder

11 Utility functions for the Admin application 5

web2py Documentation Release 2146-stable

gluonadminupgrade(request url=rsquohttpweb2pycomrsquo)Upgrades web2py (src osx win) if a new version is posted It detects whether src osx or win is running anddownloads the right one

Parameters

bull request ndash the current request object (required to determine version and path)

bull url ndash the incomplete url where to locate the latest web2py (actual url isurl+rsquoexamplesstaticweb2py_(src|osx|win)ziprsquo)

Returns tuple completed traceback

bull completed True on success False on failure (network problem or old version)

bull traceback None on success raised exception details on failure

6 Chapter 1 admin Module

CHAPTER 2

cache Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

21 Basic caching classes and methods

bull Cache - The generic caching object interfacing with the others

bull CacheInRam - providing caching in ram

bull CacheOnDisk - provides caches on disk

Memcache is also available via a different module (see gluoncontribmemcache)

When web2py is running on Google App Engine caching will be provided by the GAE memcache (seegluoncontribgae_memcache)

class gluoncacheCache(request)Bases object

Sets up generic caching creating an instance of both CacheInRam and CacheOnDisk In case of GAE will makeuse of gluoncontribgae_memcache

bull selfram is an instance of CacheInRam

bull selfdisk is an instance of CacheOnDisk

action(time_expire=300 cache_model=None prefix=None session=False vars=True lang=Trueuser_agent=False public=True valid_statuses=None quick=None)

Better fit for caching an action

Warning Experimental

7

web2py Documentation Release 2146-stable

Currently only HTTP 11 compliant reference httpcodegooglecompdoctype-mirrorwikiArticleHttpCaching

Parameters

bull time_expire (int) ndash same as cache

bull cache_model (str) ndash same as cache

bull prefix (str) ndash add a prefix to the calculated key

bull session (bool) ndash adds responsesession_id to the key

bull vars (bool) ndash adds requestenvquery_string

bull lang (bool) ndash adds Taccepted_language

bull user_agent (bool or dict) ndash if True adds is_mobile and is_tablet tothe key Pass a dict to use all the needed values (uses str(items())) (eguser_agent=requestuser_agent()) Used only if session is not True

bull public (bool) ndash if False forces the Cache-Control to be lsquoprivatersquo

bull valid_statuses ndash by default only status codes starting with 123 will be cached passan explicit list of statuses on which turn the cache on

bull quick ndash SessionVarsLangUser-agentPublic fast overrides with initials eg lsquoSVLPrsquoor lsquoVLPrsquo or lsquoVLPrsquo

autokey = (name)s(args)s(vars)s

static with_prefix(cache_model prefix)allow replacing cacheram with cachewith_prefix(cacheramrsquoprefixrsquo) it will add prefix to all the cachekeys used

gluoncachelazy_cache(key=None time_expire=None cache_model=rsquoramrsquo)Can be used to cache any function including ones in modules as long as the cached function is only calledwithin a web2py request

If a key is not provided one is generated from the function name time_expire defaults to None (no cacheexpiration)

If cache_model is ldquoramrdquo then the model is currentcacheram etc

8 Chapter 2 cache Module

CHAPTER 3

cfs Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

31 Functions required to execute app components

Note FOR INTERNAL USE ONLY

gluoncfsgetcfs(key filename filter=None)Caches the filtered file filename with key until the file is modified

Parameters

bull key (str) ndash the cache key

bull filename ndash the file to cache

bull filter ndash is the function used for filtering Normally filename is a py file and filter is afunction that bytecode compiles the file In this way the bytecode compiled file is cached(Default = None)

This is used on Google App Engine since pyc files cannot be saved

9

web2py Documentation Release 2146-stable

10 Chapter 3 cfs Module

CHAPTER 4

compileapp Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

41 Functions required to execute app components

Note FOR INTERNAL USE ONLY

gluoncompileappLOAD(c=None f=rsquoindexrsquo args=None vars=None extension=None target=Noneajax=False ajax_trap=False url=None user_signature=False time-out=None times=1 content=rsquoloadingrsquo post_vars= attr)

LOADs a component into the actionrsquos document

Parameters

bull c (str) ndash controller

bull f (str) ndash function

bull args (tuple or list) ndash arguments

bull vars (dict) ndash vars

bull extension (str) ndash extension

bull target (str) ndash id of the target

bull ajax (bool) ndash True to enable AJAX bahaviour

bull ajax_trap (bool) ndash True if ajax is set to True traps both links and forms ldquoinsiderdquo thetarget

bull url (str) ndash overrides clsquoflsquolsquoargslsquo and vars

11

web2py Documentation Release 2146-stable

bull user_signature (bool) ndash adds hmac signature to all links with a key that is differentfor every user

bull timeout (int) ndash in milliseconds specifies the time to wait before starting the request orthe frequency if times is greater than 1 or ldquoinfinityrdquo

bull times (integer or str) ndash how many times the component will be requested ldquoinfin-ityrdquo or ldquocontinuousrdquo are accepted to reload indefinitely the component

class gluoncompileappLoadFactory(environment)Bases object

Attention this helper is new and experimental

gluoncompileappbuild_environment(request response session store_current=True)Build the environment dictionary into which web2py files are executed

gluoncompileappcompile_application(folder skip_failed_views=False)Compiles all models views controller for the application in folder

gluoncompileappcompile_controllers(folder)Compiles all the controllers in the application specified by folder

gluoncompileappcompile_models(folder)Compiles all the models in the application specified by folder

gluoncompileappcompile_views(folder skip_failed_views=False)Compiles all the views in the application specified by folder

gluoncompileappfind_exposed_functions(data)

gluoncompileapplocal_import_aux(name reload_force=False app=rsquowelcomersquo)In apps instead of importing a local module (in applicationsappmodules) with

import abc as d

you should do

d = local_import(abc)

or (to force a reload)

d = local_import(lsquoabcrsquo reload=True)

This prevents conflict between applications and un-necessary execs It can be used to import any moduleincluding regular Python modules

gluoncompileappmodel_cmp(a b sep=rsquorsquo)

gluoncompileappmodel_cmp_sep(a b sep=rsquorsquo)

class gluoncompileappmybuiltinBases object

NOTE could simple use a dict and populate it NOTE not sure if this changes things though if monkey patchingimport

gluoncompileappre_compile(regex)

gluoncompileappread_pyc(filename)Read the code inside a bytecode compiled file if the MAGIC number is compatible

Returns a code object

12 Chapter 4 compileapp Module

web2py Documentation Release 2146-stable

gluoncompileappremove_compiled_application(folder)Deletes the folder compiled containing the compiled application

gluoncompileapprun_controller_in(controller function environment)Runs the controllerfunction() (for the app specified by the current folder) It tries pre-compiled con-troller_functionpyc first before compiling it

gluoncompileapprun_models_in(environment)Runs all models (in the app specified by the current folder) It tries pre-compiled models first before compilingthem

gluoncompileapprun_view_in(environment)Executes the view for the requested action The view is the one specified in responseview or determined by theurl or viewgenericextension It tries the pre-compiled views_controller_functionpyc before compiling it

gluoncompileappsave_pyc(filename)Bytecode compiles the file filename

gluoncompileapptest()Example

gtgtgt import traceback typesgtgtgt environment=x1gtgtgt open(apy w)write(print 1x)gtgtgt save_pyc(apy)gtgtgt osunlink(apy)gtgtgt if type(read_pyc(apyc))==typesCodeType print codecodegtgtgt exec read_pyc(apyc) in environment1

41 Functions required to execute app components 13

web2py Documentation Release 2146-stable

14 Chapter 4 compileapp Module

CHAPTER 5

contenttype Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

CONTENT_TYPE dictionary created against freedesktoporgrsquos shared mime info database version 11

Deviations from official standards

bull md applicationx-genesis-rom ndashgt textx-markdown

bull png imagex-apple-ios-png ndashgt imagepng

Additions

bull load texthtml

bull json applicationjson

bull jsonp applicationjsonp

bull pickle applicationpython-pickle

bull w2prsquo applicationw2p

gluoncontenttypecontenttype(filename default=rsquotextplainrsquo)Returns the Content-Type string matching extension of the given filename

15

web2py Documentation Release 2146-stable

16 Chapter 5 contenttype Module

CHAPTER 6

custom_import Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

61 Support for smart import syntax for web2py applications

exception gluoncustom_importCustomImportExceptionBases exceptionsImportError

class gluoncustom_importTrackImporterBases object

An importer tracking the date of the module files and reloading them when they are changed

PACKAGE_PATH_SUFFIX = __init__py

THREAD_LOCAL = ltthread_local objectgt

gluoncustom_importcustom_import_install()

gluoncustom_importcustom_importer(name globals=None locals=None fromlist=Nonelevel=-1)

web2pyrsquos custom importer It behaves like the standard Python importer but it tries to transform importstatements as something like ldquoimport applicationsapp_namemodulesxrdquo If the import fails it falls back onnaive_importer

gluoncustom_importis_tracking_changes()

gluoncustom_importtrack_changes(track=True)

17

web2py Documentation Release 2146-stable

18 Chapter 6 custom_import Module

CHAPTER 7

dal Module

Go to httppydalreadthedocsorgenlatest for docs on pyDAL

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

71 Takes care of adapting pyDAL to web2pyrsquos needs

19

web2py Documentation Release 2146-stable

20 Chapter 7 dal Module

CHAPTER 8

debug Module

This file is part of the web2py Web FrameworkDeveloped by Massimo Di Pierro ltmdipierrocsdepauledugtlimodou ltlimodougmailcomgt and srackham ltsrackhamgmailcomgtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

81 Debugger support classes

class gluondebugPipe(name mode=rsquorrsquo args kwargs)Bases QueueQueue

flush()

read(count=None timeout=None)

readline()

write(data)

class gluondebugWebDebugger(pipe completekey=rsquotabrsquo stdin=None stdout=None)Bases gluoncontribqdbFrontend

Qdb web2py interface

clear_interaction()

do_continue(args kwargs)

do_exec(statement)

do_next(args kwargs)

do_quit(args kwargs)

do_return(args kwargs)

do_step(args kwargs)

21

web2py Documentation Release 2146-stable

exception(title extype exvalue trace request)Show a user_exception

interaction(filename lineno line context)

run()Main method dispatcher (infinite loop)

gluondebugcheck_interaction(fn)Decorator to clean and prevent interaction when not available

gluondebugcommunicate(command=None)send command to debbuger wait result

gluondebugset_trace()breakpoint shortcut (like pdb)

gluondebugstop_trace()stop waiting for the debugger (called atexit)

22 Chapter 8 debug Module

CHAPTER 9

decoder Module

Caller will hand this library a buffer and ask it to either convert it or auto-detect the type

Based on httpcodeactivestatecomrecipes52257

Licensed under the PSF License

gluondecoderautoDetectXMLEncoding(buffer)buffer -gt encoding_name The buffer should be at least 4 bytes long Returns None if encoding cannot bedetected Note that encoding_name might not have an installed decoder (eg EBCDIC)

gluondecoderdecoder(buffer)

23

web2py Documentation Release 2146-stable

24 Chapter 9 decoder Module

CHAPTER 10

fileutils Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

101 File operations

gluonfileutilsparse_version(version)Attempts to parse SemVer fallbacks on legacy

gluonfileutilsread_file(filename mode=rsquorrsquo)Returns content from filename making sure to close the file explicitly on exit

gluonfileutilswrite_file(filename value mode=rsquowrsquo)Writes ltvaluegt to filename making sure to close the file explicitly on exit

gluonfileutilsreadlines_file(filename mode=rsquorrsquo)Applies split(lsquo lsquo) to the output of read_file()

gluonfileutilsup(path)

gluonfileutilsabspath(relpath base)Converts relative path to absolute path based (by default) on applications_parent

gluonfileutilsmktree(path)

gluonfileutilslistdir(path expression=rsquo^+$rsquo drop=True add_dirs=False sort=Truemaxnum=None exclude_content_from=None)

Like oslistdir() but you can specify a regex pattern to filter files If add_dirs is True the returned items willhave the full path

gluonfileutilsrecursive_unlink(f)Deletes f If itrsquos a folder also its contents will be deleted

gluonfileutilscleanpath(path)Turns any expressionpath into a valid filename replaces with _ and removes special characters

25

web2py Documentation Release 2146-stable

gluonfileutilstar(file dir expression=rsquo^+$rsquo filenames=None exclude_content_from=None)Tars dir into file only tars file that match expression

gluonfileutilsuntar(file dir)Untar file into dir

gluonfileutilstar_compiled(file dir expression=rsquo^+$rsquo exclude_content_from=None)Used to tar a compiled application The content of models views controllers is not stored in the tar file

gluonfileutilsget_session(request other_application=rsquoadminrsquo)Checks that user is authorized to access other_application

gluonfileutilscheck_credentials(request other_application=rsquoadminrsquo expiration=3600gae_login=True)

Checks that user is authorized to access other_application

gluonfileutilsw2p_pack(filename path compiled=False filenames=None)Packs a web2py application

Parameters

bull filename (str) ndash path to the resulting archive

bull path (str) ndash path to the application

bull compiled (bool) ndash if True packs the compiled version

bull filenames (list) ndash adds filenames to the archive

gluonfileutilsw2p_unpack(filename path delete_tar=True)

gluonfileutilsw2p_pack_plugin(filename path plugin_name)Packs the given plugin into a w2p file Will match files at

ltpathgtplugin_[name]ltpathgtplugin_[name]

gluonfileutilsw2p_unpack_plugin(filename path delete_tar=True)

gluonfileutilsfix_newlines(path)

gluonfileutilsmake_fake_file_like_object()

26 Chapter 10 fileutils Module

CHAPTER 11

globals Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

Contains the classes for the global used variables

bull Request

bull Response

bull Session

class gluonglobalsRequest(env)Bases gluonstorageStorage

Defines the request object and the default values of its members

bull env environment variables by gluonmainwsgibase()

bull cookies

bull get_vars

bull post_vars

bull vars

bull folder

bull application

bull function

bull args

bull extension

bull now datetimedatetimenow()

27

web2py Documentation Release 2146-stable

bull utcnow datetimedatetimeutcnow()

bull is_local

bull is_https

bull restful()

body

compute_uuid()

get_varsLazily parses the query string into get_vars

parse_all_vars()Merges get_vars and post_vars to vars

parse_get_vars()Takes the QUERY_STRING and unpacks it to get_vars

parse_post_vars()Takes the body of the request and unpacks it into post_vars applicationjson is also automatically parsed

post_varsLazily parse the body into post_vars

requires_https()If request comes in over HTTP redirects it to HTTPS and secures the session

restful()

user_agent()

uuidLazily uuid

varsLazily parses all get_vars and post_vars to fill vars

class gluonglobalsResponseBases gluonstorageStorage

Defines the response object and the default values of its members responsewrite( ) can be used to write in theoutput html

download(request db chunk_size=65536 attachment=True download_filename=None)Example of usage in controller

def download()return responsedownload(request db)

Downloads from http downloadfilename

include_files(extensions=None)Includes files (usually in the head) Can minify and cache local files By default caches in ram for 5minutes To change responsecache_includes = (cache_method time_expire) Example (cachedisk 60) caches to disk for 1 minute

include_meta()

json(data default=None)

render(a b)

28 Chapter 11 globals Module

web2py Documentation Release 2146-stable

stream(stream chunk_size=65536 request=None attachment=False filename=None)If in a controller function

return responsestream(file 100)

the file content will be streamed at 100 bytes at the time

Parameters

bull stream ndash filename or read()able content

bull chunk_size (int) ndash Buffer size

bull request ndash the request object

bull attachment (bool) ndash prepares the correct headers to download the file as an attach-ment Usually creates a pop-up download window on browsers

bull filename (str) ndash the name for the attachment

Note for using the stream name (filename) with attachments the option must be explicitly set as functionparameter (will default to the last request argument otherwise)

toolbar()

write(data escape=True)

xmlrpc(request methods)assuming

def add(a b)return a+b

if a controller function ldquofuncrdquo

return responsexmlrpc(request [add])

the controller will be able to handle xmlrpc requests for the add function Example

import xmlrpclibconnection = xmlrpclibServerProxy(

httphostnameappcontrfunc)print connectionadd(3 4)

class gluonglobalsSessionBases gluonstorageStorage

Defines the session object and the default values of its members (None)

bull session_storage_type lsquofilersquo lsquodbrsquo or lsquocookiersquo

bull session_cookie_compression_level

bull session_cookie_expires cookie expiration

bull session_cookie_key for encrypted sessions in cookies

bull session_id a number or None if no session

bull session_id_name

bull session_locked

29

web2py Documentation Release 2146-stable

bull session_masterapp

bull session_new a new session obj is being created

bull session_hash hash of the pickled loaded session

bull session_pickled picked session

if session in cookie

bull session_data_name name of the cookie for session data

if session in db

bull session_db_record_id

bull session_db_table

bull session_db_unique_key

if session in file

bull session_file

bull session_filename

clear()rarr None Remove all items from D

clear_session_cookies()

connect(request=None response=None db=None tablename=rsquoweb2py_sessionrsquo master-app=None migrate=True separate=None check_client=False cookie_key=Nonecookie_expires=None compression_level=None)

Used in models allows to customize Session handling

Parameters

bull request ndash the request object

bull response ndash the response object

bull db ndash to storeretrieve sessions in db (a table is created)

bull tablename (str) ndash table name

bull masterapp (str) ndash points to anotherrsquos app sessions This enables a ldquoSSOrdquo environmentamong apps

bull migrate ndash passed to the underlying db

bull separate ndash with True creates a folder with the 2 initials of the session id Can also bea function eg

separate=lambda(session_name) session_name[-2]

bull check_client ndash if True sessions can only come from the same ip

bull cookie_key (str) ndash secret for cookie encryption

bull cookie_expires ndash sets the expiration of the cookie

bull compression_level (int) ndash 0-9 sets zlib compression on the data before the en-cryption

forget(response=None)

is_expired(seconds=3600)

is_new()

30 Chapter 11 globals Module

web2py Documentation Release 2146-stable

renew(clear_session=False)

save_session_id_cookie()

secure()

31

web2py Documentation Release 2146-stable

32 Chapter 11 globals Module

CHAPTER 12

highlight Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

gluonhighlighthighlight(code language link=rsquoexamplesglobalsvarsrsquo counter=1styles=None highlight_line=None context_lines=None at-tributes=None)

33

web2py Documentation Release 2146-stable

34 Chapter 12 highlight Module

CHAPTER 13

html Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

131 Template helpers

class gluonhtmlA(components attributes)Bases gluonhtmlDIV

Generates an A() link A() in web2py is really important and with the included web2pyjs allows lots of Ajaxinteractions in the page

On top of ldquousualrdquo _attributes it takes

Parameters

bull callback ndash an url to call but not redirect to

bull cid ndash if you want to load the _href into an element of the page (component) pass its id(without the ) here

bull delete ndash element to delete after calling callback

bull target ndash same thing as cid

bull confirm ndash text to display upon a callback with a delete

bull noconfirm ndash donrsquot display alert upon a callback with delete

tag = a

xml()generates the xml for this component

gluonhtmlASSIGNJS(kargs)

35

web2py Documentation Release 2146-stable

Example

ASSIGNJS(var1=lsquo1rsquo var2=lsquo2rsquo) will return the following javascript variables assignations

var var1 = ldquo1rdquo var var2 = ldquo2rdquo

Parameters kargs ndash Any keywords arguments and assigned values

Returns Javascript vars assignations for the keyvalue passed

class gluonhtmlB(components attributes)Bases gluonhtmlDIV

tag = b

class gluonhtmlBEAUTIFY(component attributes)Bases gluonhtmlDIV

Turns any list dictionary etc into decent looking html

Two special attributes are

bull sorted a function that takes the dict and returned sorted keys

bull keyfilter a function that takes a key and returns its representation or None if the key is to be skipped Bydefault key[1]==rsquo_rsquo is skipped

Examples

gtgtgt BEAUTIFY([a b hello world])xml()ltdivgtlttablegtlttrgtlttdgtltdivgtaltdivgtlttdgtlttrgtlttrgtlttdgtltdivgtbltdivgtlttdgtlttrgtlttrgtlttdgtrarr˓ltdivgtlttablegtlttrgtlttd style=font-weightboldvertical-aligntopgthellolttdgtlttdrarr˓style=vertical-aligntopgtlttdgtlttdgtltdivgtworldltdivgtlttdgtlttrgtlttablegtltdivgtltrarr˓tdgtlttrgtlttablegtltdivgt

static no_underscore(key)

tag = div

class gluonhtmlBODY(components attributes)Bases gluonhtmlDIV

tag = body

class gluonhtmlBR(components attributes)Bases gluonhtmlDIV

tag = br

class gluonhtmlBUTTON(components attributes)Bases gluonhtmlDIV

tag = button

class gluonhtmlCENTER(components attributes)Bases gluonhtmlDIV

tag = center

class gluonhtmlCAT(components attributes)Bases gluonhtmlDIV

tag =

36 Chapter 13 html Module

web2py Documentation Release 2146-stable

class gluonhtmlCODE(components attributes)Bases gluonhtmlDIV

Displays code in HTML with syntax highlighting

Parameters

bull language ndash indicates the language otherwise PYTHON is assumed

bull link ndash can provide a link

bull styles ndash for styles

Examples

=CODE(ldquoprint lsquohello worldrsquordquo language=rsquopythonrsquo link=None counter=1 styles= high-light_line=None)

supported languages are

ldquopythonrdquo ldquohtml_plainrdquo ldquocrdquo ldquocpprdquo ldquoweb2pyrdquo ldquohtmlrdquo

The ldquohtmlrdquo language interprets and tags as ldquoweb2pyrdquo code ldquohtml_plainrdquo doesnrsquot

if a link=rsquoexamplesglobalvarsrsquo is provided web2py keywords are linked to the online docs

the counter is used for line numbering counter can be None or a prompt string

xml()generates the xml for this component

class gluonhtmlCOL(components attributes)Bases gluonhtmlDIV

tag = col

class gluonhtmlCOLGROUP(components attributes)Bases gluonhtmlDIV

tag = colgroup

class gluonhtmlDIV(components attributes)Bases gluonhtmlXmlComponent

HTML helper for easy generating and manipulating a DOM structure Little or no validation is done

Behaves like a dictionary regarding updating of attributes Behaves like a list regarding insertingappendingcomponents

Examples

gtgtgt DIV(hello world _style=colorred)xml()ltdiv style=colorredgthelloworldltdivgt

All other HTML helpers are derived from DIV

_something=rdquovaluerdquo attributes are transparently translated into something=rdquovaluerdquo HTML attributes

append(value)list style appending of components

Examples

131 Template helpers 37

web2py Documentation Release 2146-stable

gtgtgt a=DIV()gtgtgt aappend(SPAN(x))gtgtgt print altdivgtltspangtxltspangtltdivgt

element(args kargs)Finds the first component that matches the supplied attribute dictionary or None if nothing could be found

Also the components of the components are searched

elements(args kargs)Find all components that match the supplied attribute dictionary or None if nothing could be found

All components of the components are searched

Examples

gtgtgt a = DIV(DIV(SPAN(x)3DIV(SPAN(y))))gtgtgt for c in aelements(span first_only=True) c[0]=zgtgtgt print altdivgtltdivgtltspangtzltspangt3ltdivgtltspangtyltspangtltdivgtltdivgtltdivgtgtgtgt for c in aelements(span) c[0]=zgtgtgt print altdivgtltdivgtltspangtzltspangt3ltdivgtltspangtzltspangtltdivgtltdivgtltdivgt

It also supports a syntax compatible with jQuery

Examples

gtgtgt a=TAG(ltdivgtltspangtlta id=1-1 uv=$gthelloltagtltspangtltp class=this is ararr˓testgtworldltpgtltdivgt)gtgtgt for e in aelements(div a1-1 pis) print eflatten()helloworldgtgtgt for e in aelements(1-1) print eflatten()hellogtgtgt aelements(a[uv=$])[0]xml()lta id=1-1 uv=$gthelloltagtgtgtgt a=FORM( INPUT(_type=text) SELECT(range(1)) TEXTAREA() )gtgtgt for c in aelements(input select textarea) c[_disabled] = disabledrarr˓gtgtgt axml()ltform action= enctype=multipartform-data method=postgtltinput disabled=rarr˓disabled type=text gtltselect disabled=disabledgtltoption value=0gt0ltrarr˓optiongtltselectgtlttextarea cols=40 disabled=disabled rows=10gtltrarr˓textareagtltformgt

Elements that are matched can also be replaced or removed by specifying a ldquoreplacerdquo argument (note alist of the original matching elements is still returned as usual)

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=abc) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(spanabc replace=P(x _class=xyz))gtgtgt print a We should xml() here instead of printltdivgtltdivgtltp class=xyzgtxltpgtltdivgtltp class=xyzgtxltpgtltp class=xyzgtxltpgtltrarr˓divgtltdivgtltdivgt

38 Chapter 13 html Module

web2py Documentation Release 2146-stable

ldquoreplacerdquo can be a callable which will be passed the original element and should return a new element toreplace it

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=abc) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(spanabc replace=lambda el P(el[0] _class=xyz))gtgtgt print altdivgtltdivgtltp class=xyzgtxltpgtltdivgtltp class=xyzgtyltpgtltp class=xyzgtzltpgtltrarr˓divgtltdivgtltdivgt

If replace=None matching elements will be removed completely

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=abc) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(span find=y replace=None)gtgtgt print altdivgtltdivgtltspan class=abcgtxltspangtltdivgtltspan class=abcgtzltspangtltdivgtltrarr˓divgtltdivgt

If a ldquofind_textrdquo argument is specified elements will be searched for text components that match find_textand any matching text components will be replaced (find_text is ignored if ldquoreplacerdquo is not also specified)Like the ldquofindrdquo argument ldquofind_textrdquo can be a string or a compiled regex

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=abc) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(find_text=recompile(x|y|z) replace=hello)gtgtgt print altdivgtltdivgtltspan class=abcgthelloltspangtltdivgtltspan class=abcgthelloltspangtrarr˓ltspan class=abcgthelloltspangtltdivgtltdivgtltdivgt

If other attributes are specified along with find_text then only components that match the specified at-tributes will be searched for find_text

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=efg) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(spanefg find_text=recompile(x|y|z) replace=hello)gtgtgt print altdivgtltdivgtltspan class=abcgtxltspangtltdivgtltspan class=efggthelloltspangtltspanrarr˓class=abcgtzltspangtltdivgtltdivgtltdivgt

flatten(render=None)Returns the text stored by the DIV object rendered by the render function the render function must taketext tagname and attributes render=None is equivalent to render=lambda text tag attr text

Examples

gtgtgt markdown = lambda text tag=None attributes=rarr˓None resub(s+ text) h1+text+nnrarr˓ ptext+nget(tagtext)gtgtgt a=TAG(lth1gtHeaderlth1gtltpgtthis is a testltpgt)gtgtgt aflatten(markdown)Headernnthis is a testn

131 Template helpers 39

web2py Documentation Release 2146-stable

get(i)

insert(i value)List-style inserting of components

Examples

gtgtgt a=DIV()gtgtgt ainsert(0 SPAN(x))gtgtgt print altdivgtltspangtxltspangtltdivgt

regex_attr = lt_sreSRE_Pattern objectgt

regex_class = lt_sreSRE_Pattern objectgt

regex_id = lt_sreSRE_Pattern objectgt

regex_tag = lt_sreSRE_Pattern objectgt

sibling(args kargs)Finds the first sibling component that match the supplied argument list and attribute dictionary or None ifnothing could be found

siblings(args kargs)Finds all sibling components that match the supplied argument list and attribute dictionary or None ifnothing could be found

tag = div

update(kargs)dictionary like updating of the tag attributes

xml()generates the xml for this component

class gluonhtmlEM(components attributes)Bases gluonhtmlDIV

tag = em

class gluonhtmlEMBED(components attributes)Bases gluonhtmlDIV

tag = embed

class gluonhtmlFIELDSET(components attributes)Bases gluonhtmlDIV

tag = fieldset

class gluonhtmlFORM(components attributes)Bases gluonhtmlDIV

Examples

gtgtgt from validators import IS_NOT_EMPTYgtgtgt form=FORM(INPUT(_name=test requires=IS_NOT_EMPTY()))gtgtgt formxml()ltform action= enctype=multipartform-data method=postgtltinput name=testrarr˓type=text gtltformgt

a FORM is container for INPUT TEXTAREA SELECT and other helpers

form has one important method

40 Chapter 13 html Module

web2py Documentation Release 2146-stable

formaccepts(requestvars session)

if form is accepted (and all validators pass) formvars contains the accepted vars otherwise formerrors containsthe errors in case of errors the form is modified to present the errors to the user

REDIRECT_JS = windowlocation=sreturn false

accepts(request_vars session=None formname=rsquodefaultrsquo keepvalues=False onvalidation=Nonehideerror=False kwargs)

kwargs is not used but allows to specify the same interface for FORM and SQLFORM

add_button(value url _class=None)

as_dict(flat=False sanitize=True)EXPERIMENTAL

Sanitize is naive It should catch any unsafe value for client retrieval

as_json(sanitize=True)

as_xml(sanitize=True)

as_yaml(sanitize=True)

assert_status(status request_vars)

static confirm(text=rsquoOKrsquo buttons=None hidden=None)

hidden_fields()

process(kwargs)Perform the validate() method but returns the form

Usage in controllers

directly on returndef action()

some code herereturn dict(form=FORM()process())

You can use it with FORM SQLFORM or FORM based plugins

responseflash messagesdef action()

form = SQLFORM(dbtable)process(message_onsuccess=Sucess)return dict(form=form)

callback function callback receives True or False as first arg and a list of argsdef my_callback(status msg)

responseflash = Success +msg if status else Errors occured

after argument can be flash to responseflash messages or a function name to use as callback or None to do nothingdef action()

return dict(form=SQLFORM(dbtable)process(onsuccess=my_callback)

tag = form

validate(kwargs)This function validates the form you can use it instead of directly formaccepts

Usage In controller

131 Template helpers 41

web2py Documentation Release 2146-stable

def action()form=FORM(INPUT(_name=test requires=IS_NOT_EMPTY()))formvalidate() you can pass some args here - see belowreturn dict(form=form)

This can receive a bunch of arguments

onsuccess = lsquoflashrsquo - will show message_onsuccess in responseflash None - will do nothing can be afunction (lambda form pass)

onfailure = lsquoflashrsquo - will show message_onfailure in responseflash None - will do nothing can be afunction (lambda form pass)

onchange = lsquoflashrsquo - will show message_onchange in responseflash None - will do nothing can be afunction (lambda form pass)

message_onsuccess message_onfailure message_onchange next = where to redirect in case of success anyother kwargs will be passed for formaccepts( )

xml()generates the xml for this component

class gluonhtmlH1(components attributes)Bases gluonhtmlDIV

tag = h1

class gluonhtmlH2(components attributes)Bases gluonhtmlDIV

tag = h2

class gluonhtmlH3(components attributes)Bases gluonhtmlDIV

tag = h3

class gluonhtmlH4(components attributes)Bases gluonhtmlDIV

tag = h4

class gluonhtmlH5(components attributes)Bases gluonhtmlDIV

tag = h5

class gluonhtmlH6(components attributes)Bases gluonhtmlDIV

tag = h6

class gluonhtmlHEAD(components attributes)Bases gluonhtmlDIV

tag = head

class gluonhtmlHR(components attributes)Bases gluonhtmlDIV

tag = hr

class gluonhtmlHTML(components attributes)Bases gluonhtmlDIV

42 Chapter 13 html Module

web2py Documentation Release 2146-stable

There are four predefined document type definitions They can be specified in the lsquodoctypersquo parameter

bull lsquostrictrsquo enables strict doctype

bull lsquotransitionalrsquo enables transitional doctype (default)

bull lsquoframesetrsquo enables frameset doctype

bull lsquohtml5rsquo enables HTML 5 doctype

bull any other string will be treated as userrsquos own doctype

lsquolangrsquo parameter specifies the language of the document Defaults to lsquoenrsquo

See also DIV

frameset = ltDOCTYPE HTML PUBLIC -W3CDTD HTML 401 FramesetEN httpwwww3orgTRhtml4framesetdtdgtn

html5 = ltDOCTYPE HTMLgtn

strict = ltDOCTYPE HTML PUBLIC -W3CDTD HTML 401EN httpwwww3orgTRhtml4strictdtdgtn

tag = html

transitional = ltDOCTYPE HTML PUBLIC -W3CDTD HTML 401 TransitionalEN httpwwww3orgTRhtml4loosedtdgtn

xml()generates the xml for this component

class gluonhtmlI(components attributes)Bases gluonhtmlDIV

tag = i

class gluonhtmlIFRAME(components attributes)Bases gluonhtmlDIV

tag = iframe

class gluonhtmlIMG(components attributes)Bases gluonhtmlDIV

tag = img

class gluonhtmlINPUT(components attributes)Bases gluonhtmlDIV

INPUT Component

Takes two special attributes value= and requires=

Parameters

bull value ndash used to pass the initial value for the input field value differs from _value becauseit works for checkboxes radio textarea and selectoption too For a checkbox value shouldbe lsquorsquo or lsquoonrsquo For a radio or selectoption value should be the _value of the checkedselecteditem

bull requires ndash should be None or a validator or a list of validators for the value of the field

Examples

gtgtgt INPUT(_type=text _name=name value=Max)xml()ltinput name=name type=text value=Max gt

gtgtgt INPUT(_type=checkbox _name=checkbox value=on)xml()ltinput checked=checked name=checkbox type=checkbox value=on gt

131 Template helpers 43

web2py Documentation Release 2146-stable

gtgtgt INPUT(_type=radio _name=radio _value=yes value=yes)xml()ltinput checked=checked name=radio type=radio value=yes gt

gtgtgt INPUT(_type=radio _name=radio _value=no value=yes)xml()ltinput name=radio type=radio value=no gt

tag = input

xml()generates the xml for this component

class gluonhtmlLABEL(components attributes)Bases gluonhtmlDIV

tag = label

class gluonhtmlLEGEND(components attributes)Bases gluonhtmlDIV

tag = legend

class gluonhtmlLI(components attributes)Bases gluonhtmlDIV

tag = li

class gluonhtmlLINK(components attributes)Bases gluonhtmlDIV

tag = link

class gluonhtmlOL(components attributes)Bases gluonhtmlUL

tag = ol

class gluonhtmlUL(components attributes)Bases gluonhtmlDIV

UL Component

If subcomponents are not LI-components they will be wrapped in a LI

tag = ul

class gluonhtmlMARKMIN(text extra=None allowed=None sep=rsquoprsquo url=None environ-ment=None latex=rsquogooglersquo autolinks=rsquodefaultrsquo protolinks=rsquodefaultrsquoclass_prefix=rdquo id_prefix=rsquomarkmin_rsquo kwargs)

Bases gluonhtmlXmlComponent

For documentation httpweb2pycomexamplesstaticmarkminhtml

flatten()

xml()

class gluonhtmlMENU(data args)Bases gluonhtmlDIV

Used to build menus

Parameters

bull _class ndash defaults to lsquoweb2py-menu web2py-menu-verticalrsquo

bull ul_class ndash defaults to lsquoweb2py-menu-verticalrsquo

44 Chapter 13 html Module

web2py Documentation Release 2146-stable

bull li_class ndash defaults to lsquoweb2py-menu-expandrsquo

bull li_first ndash defaults to lsquoweb2py-menu-firstrsquo

bull li_last ndash defaults to lsquoweb2py-menu-lastrsquo

Use like

menu = MENU([[name False URL() [submenu]] ])=menu

serialize(data level=0)

serialize_mobile(data select=None prefix=rdquo)

tag = ul

xml()generates the xml for this component

class gluonhtmlMETA(components attributes)Bases gluonhtmlDIV

tag = meta

class gluonhtmlOBJECT(components attributes)Bases gluonhtmlDIV

tag = object

class gluonhtmlOPTION(components attributes)Bases gluonhtmlDIV

tag = option

class gluonhtmlP(components attributes)Bases gluonhtmlDIV

Will replace n by ltbr gt if the cr2br attribute is provided

see also DIV

tag = p

xml()generates the xml for this component

class gluonhtmlPRE(components attributes)Bases gluonhtmlDIV

tag = pre

class gluonhtmlSCRIPT(components attributes)Bases gluonhtmlDIV

tag = script

xml()generates the xml for this component

class gluonhtmlOPTGROUP(components attributes)Bases gluonhtmlDIV

tag = optgroup

131 Template helpers 45

web2py Documentation Release 2146-stable

class gluonhtmlSELECT(components attributes)Bases gluonhtmlINPUT

Examples

gtgtgt from validators import IS_IN_SETgtgtgt SELECT(yes no _name=selector value=yes requires=IS_IN_SET([yes no]))xml()ltselect name=selectorgtltoption selected=selected value=yesgtyesltoptiongtrarr˓ltoption value=nogtnoltoptiongtltselectgt

tag = select

class gluonhtmlSPAN(components attributes)Bases gluonhtmlDIV

tag = span

class gluonhtmlSTRONG(components attributes)Bases gluonhtmlDIV

tag = strong

class gluonhtmlSTYLE(components attributes)Bases gluonhtmlDIV

tag = style

xml()generates the xml for this component

class gluonhtmlTABLE(components attributes)Bases gluonhtmlDIV

TABLE Component

If subcomponents are not TRTBODYTHEADTFOOT-components they will be wrapped in a TR

tag = table

gluonhtmlTAGTAG factory

Examples

gtgtgt print TAGfirst(TAGsecond(test) _key = 3)ltfirst key=3gtltsecondgttestltsecondgtltfirstgt

class gluonhtmlTD(components attributes)Bases gluonhtmlDIV

tag = td

class gluonhtmlTEXTAREA(components attributes)Bases gluonhtmlINPUT

Examples

TEXTAREA(_name=sometext value=blah 100 requires=IS_NOT_EMPTY())

lsquoblah blah blah rsquo will be the content of the textarea field

tag = textarea

46 Chapter 13 html Module

web2py Documentation Release 2146-stable

class gluonhtmlTH(components attributes)Bases gluonhtmlDIV

tag = th

class gluonhtmlTHEAD(components attributes)Bases gluonhtmlDIV

tag = thead

class gluonhtmlTBODY(components attributes)Bases gluonhtmlDIV

tag = tbody

class gluonhtmlTFOOT(components attributes)Bases gluonhtmlDIV

tag = tfoot

class gluonhtmlTITLE(components attributes)Bases gluonhtmlDIV

tag = title

class gluonhtmlTR(components attributes)Bases gluonhtmlDIV

TR Component

If subcomponents are not TDTH-components they will be wrapped in a TD

tag = tr

class gluonhtmlTT(components attributes)Bases gluonhtmlDIV

tag = tt

gluonhtmlURL(a=None c=None f=None r=None args=None vars=None an-chor=rdquo extension=None env=None hmac_key=None hash_vars=Truesalt=None user_signature=None scheme=None host=None port=None en-code_embedded_slash=False url_encode=True language=None)

generates a url lsquoacfrsquo corresponding to application a controller c and function f If r=request is passed a c fare set respectively to rapplication rcontroller rfunction

The more typical usage is

URL(lsquoindexrsquo)

that generates a url for the index function within the present application and controller

Parameters

bull a ndash application (default to current if r is given)

bull c ndash controller (default to current if r is given)

bull f ndash function (default to current if r is given)

bull r ndash request (optional)

bull args ndash any arguments (optional) Additional ldquopathrdquo elements

bull vars ndash any variables (optional) Querystring elements

bull anchor ndash anchorname without (optional)

131 Template helpers 47

web2py Documentation Release 2146-stable

bull extension ndash force an extension

bull hmac_key ndash key to use when generating hmac signature (optional)

bull hash_vars ndash which of the vars to include in our hmac signature True (default) - hash allvars False - hash none of the vars iterable - hash only the included vars [lsquokey1rsquorsquokey2rsquo]

bull salt ndash salt hashing with this string

bull user_signature ndash signs automatically the URL in such way that only the user canaccess the URL (use with URLverify or authrequires_signature())

bull scheme ndash URI scheme (True lsquohttprsquo or lsquohttpsrsquo etc) forces absolute URL (optional)

bull host ndash string to force absolute URL with host (True means http_host)

bull port ndash optional port number (forces absolute URL)

bull encode_embedded_slash ndash encode slash characters included in args

bull url_encode ndash encode characters included in vars

Raises SyntaxError ndash when no application controller or function is available or when a CRLFis found in the generated url

Examples

gtgtgt str(URL(a=a c=c f=f args=[x y z] vars=p1 q2 anchor=1))acfxyzp=1ampq=21

gtgtgt str(URL(a=a c=c f=f args=[x y z] vars=p(13) q2 anchor=1))acfxyzp=1ampp=3ampq=21

gtgtgt str(URL(a=a c=c f=f args=[x y z] vars=p(31) q2 anchor=1))acfxyzp=3ampp=1ampq=21

gtgtgt str(URL(a=a c=c f=f anchor=1+2))acf12B2

gtgtgt str(URL(a=a c=c f=f args=[x y z] vars=p(13) q2 anchor=1 hmac_key=key))acfxyzp=1ampp=3ampq=2amp_signature=a32530f0d0caa80964bb92aad2bedf8a4486a31f1

gtgtgt str(URL(a=a c=c f=f args=[wx yz]))acfwxyz

gtgtgt str(URL(a=a c=c f=f args=[wx yz] encode_embedded_slash=True))acfw2Fxy2Fz

gtgtgt str(URL(a=a c=c f=f args=[(id)d] url_encode=False))acf(id)d

gtgtgt str(URL(a=a c=c f=f args=[(id)d] url_encode=True))acf2528id29d

48 Chapter 13 html Module

web2py Documentation Release 2146-stable

gtgtgt str(URL(a=a c=c f=f vars=id (id)d url_encode=False))acfid=(id)d

gtgtgt str(URL(a=a c=c f=f vars=id (id)d url_encode=True))acfid=2528id29d

gtgtgt str(URL(a=a c=c f=f anchor=(id)d url_encode=False))acf(id)d

gtgtgt str(URL(a=a c=c f=f anchor=(id)d url_encode=True))acf2528id29d

class gluonhtmlXHTML(components attributes)Bases gluonhtmlDIV

This is XHTML version of the HTML helper

There are three predefined document type definitions They can be specified in the lsquodoctypersquo parameter

bull lsquostrictrsquo enables strict doctype

bull lsquotransitionalrsquo enables transitional doctype (default)

bull lsquoframesetrsquo enables frameset doctype

bull any other string will be treated as userrsquos own doctype

lsquolangrsquo parameter specifies the language of the document and the xml document Defaults to lsquoenrsquo

lsquoxmlnsrsquo parameter specifies the xml namespace Defaults to lsquohttpwwww3org1999xhtmlrsquo

See also DIV

frameset = ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 FramesetEN httpwwww3orgTRxhtml1DTDxhtml1-framesetdtdgtn

strict = ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgtn

tag = html

transitional = ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 TransitionalEN httpwwww3orgTRxhtml1DTDxhtml1-transitionaldtdgtn

xml()generates the xml for this component

xmlns = httpwwww3org1999xhtml

class gluonhtmlXML(text sanitize=False permitted_tags=[rsquoarsquo rsquobrsquo rsquoblockquotersquo rsquobrrsquo rsquoirsquo rsquolirsquo rsquoolrsquorsquoulrsquo rsquoprsquo rsquocitersquo rsquocodersquo rsquoprersquo rsquoimgrsquo rsquoh1rsquo rsquoh2rsquo rsquoh3rsquo rsquoh4rsquo rsquoh5rsquo rsquoh6rsquo rsquotablersquo rsquotrrsquorsquotdrsquo rsquodivrsquo rsquostrongrsquo rsquospanrsquo] allowed_attributes=rsquoarsquo [rsquohrefrsquo rsquotitlersquo rsquotargetrsquo]rsquoblockquotersquo [rsquotypersquo] rsquoimgrsquo [rsquosrcrsquo rsquoaltrsquo] rsquotdrsquo [rsquocolspanrsquo])

Bases gluonhtmlXmlComponent

use it to wrap a string that contains XMLHTML so that it will not be escaped by the template

Examples

gtgtgt XML(lth1gtHellolth1gt)xml()lth1gtHellolth1gt

elements(args kargs)to be considered experimental since the behavior of this method is questionable another option could beTAG(selftext)elements(args kwargs)

131 Template helpers 49

web2py Documentation Release 2146-stable

flatten(render=None)returns the text stored by the XML object rendered by the render function

xml()

gluonhtmlxmlescape(data quote=True)Returns an escaped string of the provided data

Parameters

bull data ndash the data to be escaped

bull quote ndash optional (default False)

gluonhtmlembed64(filename=None file=None data=None extension=rsquoimagegifrsquo)helper to encode the provided (binary) data into base64

Parameters

bull filename ndash if provided opens and reads this file in lsquorbrsquo mode

bull file ndash if provided reads this file

bull data ndash if provided uses the provided data

50 Chapter 13 html Module

CHAPTER 14

http Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

141 HTTP statuses helpers

exception gluonhttpHTTP(status body=rdquo cookies=None headers)Bases exceptionsException

Raises an HTTP response

Parameters

bull status ndash usually an integer If itrsquos a well known status code the ERROR message will beautomatically added A string can also be passed as 510 Foo Bar and in that case the statuscode and the error message will be parsed accordingly

bull body ndash what to return as body If left as is will return the error code and the status messagein the body itself

bull cookies ndash pass cookies along (usually not needed)

bull headers ndash pass headers as usual dict mapping

cookies2headers(cookies)

messagecompose a message describing this exception

ldquostatus defined_status [web2py_error]rdquo

message elements that are not defined are omitted

to(responder env=None)

51

web2py Documentation Release 2146-stable

gluonhttpredirect(location=rdquo how=303 client_side=False headers=None)Raises a redirect (303)

Parameters

bull location ndash the url where to redirect

bull how ndash what HTTP status code to use when redirecting

bull client_side ndash if set to True it triggers a reload of the entire page when the fragmenthas been loaded as a component

52 Chapter 14 http Module

CHAPTER 15

languages Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)Plural subsystem is created by Vladyslav Kozlovskyy (Ukraine) ltdbdevelopgmailcomgt

151 Translation system

class gluonlanguagestranslator(langpath http_accept_language)Bases object

This class is instantiated by gluoncompileappbuild_environment as the T object

Example

Tforce(None) turns off translation Tforce(lsquofr itrsquo) forces web2py to translate using frpy or itpy

T(ldquoHello Worldrdquo) translates ldquoHello Worldrdquo using the selected file

Note

bull there is no need to force since by default T uses http_accept_language to determine a translation file

bull en and en-en are considered different languages

bull if language xx-yy is not found force() probes other similar languages using such algorithm xx-yypy -gtxxpy -gt xx-yypy -gt xxpy

M(message symbols= language=None lazy=None filter=None ftag=None ns=None)Gets cached translated markmin-message with inserted parametes if lazy==True lazyT object is returned

apply_filter(message symbols= filter=None ftag=None)

53

web2py Documentation Release 2146-stable

force(languages)Selects language(s) for translation

if a list of languages is passed as a parameter the first language from this list that matches the ones fromthe possible_languages dictionary will be selected

default language will be selected if none of them matches possible_languages

get_possible_languages()Gets list of all possible languages for current application

get_possible_languages_info(lang=None)Returns info for selected language or dictionary with all possible languages info from APPlanguagespyIt Returns

bull a tuple containing

langcode langname langfile_mtimepluraldict_fname pluraldict_mtimeprules_langcode npluralsget_plural_id construct_plural_form

or None

bull if lang is NOT defined a dictionary with all possible languages

langcode(from filename)( langcode language code from langcodelangname

language name in national spelling from langnamelangfile_mtime m_time of language filepluraldict_fname name of plural dictionary file or None (when

rarr˓defaultpy is not exist)pluraldict_mtime m_time of plural dictionary file or 0 if file is

rarr˓not existprules_langcode code of plural rules language or defaultnplurals nplurals for current languageget_plural_id get_plural_id() for current languageconstruct_plural_form) construct_plural_form() for current

rarr˓language

Parameters lang (str) ndash language

get_t(message prefix=rdquo)Use to add a comment into a translation string the comment can be useful do discriminate differentpossible translations for the same string (for example different locations)

T( hello world ) -gt hello world T( hello world token) -gt hello world T(hello world token) -gt hello world

the notation is ignored in multiline strings and strings that start with This is needed to allow markminsyntax to be translated

params_substitution(message symbols)Substitutes parameters from symbols into message using also parse placeholders for plural-formsprocessing

Returns string with parameters

54 Chapter 15 languages Module

web2py Documentation Release 2146-stable

Note symbols MUST BE OR tuple OR dict of parameters

plural(word n)Gets plural form of word for number n invoked from T()TM() in tag

Note ldquowordrdquo MUST be defined in current language (Taccepted_language)

Parameters

bull word (str) ndash word in singular

bull n (numeric) ndash number plural form created for

Returns word in appropriate singularplural form

Return type word (str)

set_current_languages(languages)Sets current AKA ldquodefaultrdquo languages Setting one of this languages makes the force() function to turntranslation off

translate(message symbols)Gets cached translated message with inserted parameters(symbols)

gluonlanguagesfindT(path language=rsquoenrsquo)

Note Must be run by the admin app

gluonlanguagesupdate_all_languages(application_path)

Note Must be run by the admin app

151 Translation system 55

web2py Documentation Release 2146-stable

56 Chapter 15 languages Module

CHAPTER 16

main Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

161 The gluon wsgi application

gluonmainwsgibase(environ responder)The gluon wsgi application The first function called when a page is requested (static or dynamic) It can becalled by pastehttpserver or by apache mod_wsgi (or any WSGI-compatible server)

bull fills request with info

bull the environment variables replacing lsquorsquo with lsquo_rsquo

bull adds web2py path and version info

bull compensates for fcgi missing path_info and query_string

bull validates the path in url

The url path must be either

1 for static pages

bull ltapplicationgtstaticltfilegt

2 for dynamic pages

bull ltapplicationgt[ltcontrollergt[ltfunctiongt[ltsubgt]]][ltextensiongt]

The naming conventions are

bull application controller function and extension may only contain [a-zA-Z0-9_]

57

web2py Documentation Release 2146-stable

bull file and sub may also contain lsquo-lsquo lsquo=rsquo lsquorsquo and lsquorsquo

gluonmainsave_password(password port)Used by main() to save the password in the parameters_portpy file

gluonmainappfactory(wsgiapp=ltfunction wsgibasegt logfilename=rsquohttpserverlogrsquo pro-filer_dir=None profilerfilename=None)

generates a wsgi application that does logging and profiling and calls wsgibase

Parameters

bull wsgiapp ndash the base application

bull logfilename ndash where to store apache-compatible requests log

bull profiler_dir ndash where to store profile files

class gluonmainHttpServer(ip=rsquo127001rsquo port=8000 password=rdquopid_filename=rsquohttpserverpidrsquo log_filename=rsquohttpserverlogrsquoprofiler_dir=None ssl_certificate=None ssl_private_key=Nonessl_ca_certificate=None min_threads=None max_threads=Noneserver_name=None request_queue_size=5 timeout=10socket_timeout=1 shutdown_timeout=None path=None inter-faces=None)

Bases object

the web2py web server (Rocket)

start()start the web server

stop(stoplogging=False)stop cron and the web server

58 Chapter 16 main Module

CHAPTER 17

messageboxhandler Module

class gluonmessageboxhandlerMessageBoxHandlerBases loggingHandler

emit(record)Do whatever it takes to actually log the specified logging record

This version is intended to be implemented by subclasses and so raises a NotImplementedError

class gluonmessageboxhandlerNotifySendHandlerBases loggingHandler

emit(record)Do whatever it takes to actually log the specified logging record

This version is intended to be implemented by subclasses and so raises a NotImplementedError

59

web2py Documentation Release 2146-stable

60 Chapter 17 messageboxhandler Module

CHAPTER 18

myregex Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

181 Useful regexes

61

web2py Documentation Release 2146-stable

62 Chapter 18 myregex Module

CHAPTER 19

newcron Module

This file is part of the web2py Web FrameworkCreated by Attila Csipa ltweb2pycsipainrsgtModified by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

Cron-style interface

class gluonnewcronToken(path)Bases object

acquire(startup=False)Returns the time when the lock is acquired or None if cron already running

lock is implemented by writing a pickle (start stop) in cronmaster start is time when cron job starts andstop is time when cron completed stop == 0 if job started but did not yet complete if a cron job startedwithin less than 60 seconds acquire returns None if a cron job started before 60 seconds and did not stopa warning is issue ldquoStale cronmaster detectedrdquo

release()Writes into cronmaster the time when cron job was completed

gluonnewcronabsolute_path_link(path)Returns an absolute path for the destination of a symlink

gluonnewcroncrondance(applications_parent ctype=rsquosoftrsquo startup=False apps=None)

class gluonnewcroncronlauncher(cmd shell=True)Bases threadingThread

run()Method representing the threadrsquos activity

You may override this method in a subclass The standard run() method invokes the callable object passedto the objectrsquos constructor as the target argument if any with sequential and keyword arguments takenfrom the args and kwargs arguments respectively

63

web2py Documentation Release 2146-stable

class gluonnewcronextcron(applications_parent apps=None)Bases threadingThread

run()Method representing the threadrsquos activity

You may override this method in a subclass The standard run() method invokes the callable object passedto the objectrsquos constructor as the target argument if any with sequential and keyword arguments takenfrom the args and kwargs arguments respectively

class gluonnewcronhardcron(applications_parent)Bases threadingThread

launch()

run()Method representing the threadrsquos activity

You may override this method in a subclass The standard run() method invokes the callable object passedto the objectrsquos constructor as the target argument if any with sequential and keyword arguments takenfrom the args and kwargs arguments respectively

gluonnewcronparsecronline(line)

gluonnewcronrangetolist(s period=rsquominrsquo)

class gluonnewcronsoftcron(applications_parent)Bases threadingThread

run()Method representing the threadrsquos activity

You may override this method in a subclass The standard run() method invokes the callable object passedto the objectrsquos constructor as the target argument if any with sequential and keyword arguments takenfrom the args and kwargs arguments respectively

gluonnewcronstopcron()Graceful shutdown of cron

64 Chapter 19 newcron Module

CHAPTER 20

portalocker Module

Cross-platform (posixnt) API for flock-style file locking

Synopsis

import portalockerfile = open(somefile r+)portalockerlock(file portalockerLOCK_EX)fileseek(12)filewrite(foo)fileclose()

If you know what yoursquore doing you may choose to

portalockerunlock(file)

before closing the file but why

Methods

lock( file flags )unlock( file )

Constants

LOCK_EXLOCK_SHLOCK_NB

I learned the win32 technique for locking files from sample code provided by John Nielsen ltnielsenjfmy-dejacomgtin the documentation that accompanies the win32 modules

Author Jonathan Feinberg ltjdfpoboxcomgt Version $Id portalockerpyv 13 20010529 184755 AdministratorExp $

class gluonportalockerLockedFile(filename mode=rsquorbrsquo)Bases object

65

web2py Documentation Release 2146-stable

close()

read(size=None)

readline()

readlines()

write(data)

gluonportalockerlock(file flags)

gluonportalockerread_locked(filename)

gluonportalockerunlock(file)

gluonportalockerwrite_locked(filename data)

66 Chapter 20 portalocker Module

CHAPTER 21

recfile Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

211 Generates names for cache and session files

gluonrecfileexists(filename path=None)

gluonrecfilegenerate(filename depth=2 base=512)

gluonrecfileopen(filename mode=rsquorrsquo path=None)

gluonrecfileremove(filename path=None)

67

web2py Documentation Release 2146-stable

68 Chapter 21 recfile Module

CHAPTER 22

restricted Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

221 Restricted environment to execute applicationrsquos code

exception gluonrestrictedRestrictedError(layer=rdquo code=rdquo output=rdquo environ-ment=None)

Bases exceptionsException

Class used to wrap an exception that occurs in the restricted environment below The traceback is used to logthe exception and generate a ticket

load(request app ticket_id)Loads a logged exception

log(request)Logs the exception

gluonrestrictedrestricted(code environment=None layer=rsquoUnknownrsquo)Runs code in environment and returns the output If an exception occurs in code it raises a RestrictedErrorcontaining the traceback Layer is passed to RestrictedError to identify where the error occurred

class gluonrestrictedTicketStorage(db=None tablename=rsquoweb2py_ticketrsquo)Bases gluonstorageStorage

Defines the ticket object and the default values of its members (None)

load(request app ticket_id)

store(request ticket_id ticket_data)Stores the ticket It will figure out if this must be on disk or in db

gluonrestrictedcompile2(code layer)The +n is necessary else compile fails when code ends in a comment

69

web2py Documentation Release 2146-stable

70 Chapter 22 restricted Module

CHAPTER 23

rewrite Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

gluonrewrite parses incoming URLs and formats outgoing URLs for gluonhtmlURL

In addition it rewrites both incoming and outgoing URLs based on the (optional) user-supplied routespy which alsoallows for rewriting of certain error messages

routespy supports two styles of URL rewriting depending on whether lsquoroutersrsquo is defined Refer to routerexamplepyand routesexamplepy for additional documentation

class gluonrewriteMapUrlIn(request=None env=None)Bases object

Logic for mapping incoming URLs

arg0Returns first arg

harg0Returns first arg with optional hyphen mapping

map_app()Determines application name

map_controller()Identifies controller

map_function()Handles functionextension

map_language()Handles language (no hyphen mapping)

71

web2py Documentation Release 2146-stable

map_prefix()Strips path prefix if present in its entirety

map_root_static()Handles root-static files (no hyphen mapping)

a root-static file is one whose incoming URL expects it to be at the root typically robotstxt amp faviconico

map_static()Handles static files file_match but no hyphen mapping

pop_arg_if(dopop)Conditionally removes first arg and returns new first arg

sluggify()

update_request()Updates request from self Builds envrequest_uri Makes lower-case versions of http headers in env

validate_args()Checks args against validation pattern

class gluonrewriteMapUrlOut(request env application controller function args other schemehost port language)

Bases object

Logic for mapping outgoing URLs

acf()Converts components to applangcontrollerfunction

build_acf()Builds acf from components

omit_acf()Omits what we can of acf

omit_lang()Omits language if possible

gluonrewritecompile_regex(k v env=None)Preprocess and compile the regular expressions in routes_appinout The resulting regex will match a pattern ofthe form

[remote address][protocol][host][method] [path]

We allow abbreviated regexes on input here we try to complete them

gluonrewritefilter_err(status application=rsquoapprsquo ticket=rsquotktrsquo)doctestunittest interface to routes_onerror

gluonrewritefilter_url(url method=rsquogetrsquo remote=rsquo0000rsquo out=False app=False lang=Nonedomain=(None None) env=False scheme=None host=Noneport=None language=None)

doctestunittest interface to regex_filter_in() and regex_filter_out()

gluonrewritefixup_missing_path_info(environ)

gluonrewriteget_effective_router(appname)Returns a private copy of the effective router for the specified application

gluonrewriteinvalid_url(routes)

72 Chapter 23 rewrite Module

web2py Documentation Release 2146-stable

gluonrewriteload(routes=rsquoroutespyrsquo app=None data=None rdict=None)load read (if file) and parse routes store results in params (called from mainpy at web2py initialization time)If data is present itrsquos used instead of the routespy contents If rdict is present it must be a dict to be used forrouters (unit test)

gluonrewriteload_routers(all_apps)Load-time post-processing of routers

gluonrewritelog_rewrite(string)Log rewrite activity under control of routespy

gluonrewritemap_url_in(request env app=False)Routes incoming URL

gluonrewritemap_url_out(request env application controller function args other scheme hostport language=None)

Supply acf (or alangcf) portion of outgoing url

The basic rule is that we can only make transformations that map_url_in can reverse

Suppose that the incoming arguments are acfargslang and that the router defaults are da dc df dl

We can perform these transformations trivially if args=[] and lang=None or dl

dadcdf =gt adcdf =gt aacdf =gt ac

We would also like to be able to strip the default application or applicationcontroller from URLs with func-tionargs present thus

dacfargs =gt cfargsdadcfargs =gt fargs

We use [applications] and [controllers] and functions to suppress ambiguous omissions

We assume that language names do not collide with acf names

gluonrewriteregex_filter_in(e)Regex rewrite incoming URL

gluonrewriteregex_filter_out(url e=None)Regex rewrite outgoing URL

gluonrewriteregex_select(env=None app=None request=None)Selects a set of regex rewrite params for the current request

gluonrewriteregex_uri(e regexes tag default=None)Filters incoming URI against a list of regexes

gluonrewriteregex_url_in(request environ)Rewrites and parses incoming URL

gluonrewritesluggify(key)

gluonrewritetry_redirect_on_error(http_object request ticket=None)Called from mainwsgibase to rewrite the http response

gluonrewritetry_rewrite_on_error(http_response request environ ticket=None)Called from mainwsgibase to rewrite the http response

gluonrewriteurl_in(request environ)Parses and rewrites incoming URL

73

web2py Documentation Release 2146-stable

gluonrewriteurl_out(request environ application controller function args other scheme hostport language=None)

Assembles and rewrites outgoing URL

74 Chapter 23 rewrite Module

CHAPTER 24

sanitizer Module

From httpaspnactivestatecomASPNCookbookPythonRecipe496942Submitter Josh Goldfoot (other recipes)Last Updated 20060805Version 10

241 Cross-site scripting (XSS) defense

gluonsanitizersanitize(text permitted_tags=[rsquoarsquo rsquobrsquo rsquoblockquotersquo rsquobrrsquo rsquoirsquo rsquolirsquo rsquoolrsquo rsquoulrsquorsquoprsquo rsquocitersquo rsquocodersquo rsquoprersquo rsquoimgrsquo rsquoh1rsquo rsquoh2rsquo rsquoh3rsquo rsquoh4rsquo rsquoh5rsquo rsquoh6rsquo rsquota-blersquo rsquotbodyrsquo rsquotheadrsquo rsquotfootrsquo rsquotrrsquo rsquotdrsquo rsquodivrsquo rsquostrongrsquo rsquospanrsquo] al-lowed_attributes=rsquoarsquo [rsquohrefrsquo rsquotitlersquo] rsquoblockquotersquo [rsquotypersquo] rsquoimgrsquo[rsquosrcrsquo rsquoaltrsquo] rsquotdrsquo [rsquocolspanrsquo] escape=True)

75

web2py Documentation Release 2146-stable

76 Chapter 24 sanitizer Module

CHAPTER 25

scheduler Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

251 Background processes made simple

class gluonschedulerJobGraph(db job_name)Bases object

Experimental dependencies amongs tasks

add_deps(task_parent task_child)Create a dependency between task_parent and task_child

validate(job_name=None)Validate if all tasks job_name can be completed

Checks if there are no mutual dependencies among tasks Commits at the end if successfull or it rollbacksthe entire transaction Handle with care

class gluonschedulerMetaSchedulerBases threadingThread

Base class documenting schedulerrsquos base methods

async(task)Start the background process

Parameters task ndash a Task object

Returns

containing

77

web2py Documentation Release 2146-stable

(okresultoutput)(errorexceptionNone)(timeoutNoneNone)(terminatedNoneNone)

Return type tuple

die()Forces termination of the worker process along with any running task

give_up()Waits for any running task to be executed then exits the worker process

loop()Main loop fetching tasks and starting executorrsquos background processes

pop_task()Fetches a task ready to be executed

report_task(task task_report)Creates a task report

run()This is executed by the main thread to send heartbeats

send_heartbeat(counter)

sleep()

start_heartbeats()

terminate_process()Terminates any running tasks (internal use only)

class gluonschedulerScheduler(db tasks=None migrate=True worker_name=Nonegroup_names=None heartbeat=3 max_empty_runs=0discard_results=False utc_time=False)

Bases gluonschedulerMetaScheduler

Scheduler object

Parameters

bull db ndash DAL connection where Scheduler will create its tables

bull tasks (dict) ndash either a dict containing namendashgtfunc or None If None functions will besearched in the environment

bull migrate (bool) ndash turn migration onoff for the Schedulerrsquos tables

bull worker_name (str) ndash force worker_name to identify each process Leave it to None toautoassign a name (hostnamepid)

bull group_names (list) ndash process tasks belonging to this group defaults to [lsquomainrsquo] if noth-ing gets passed

bull heartbeat (int) ndash how many seconds the worker sleeps between one execution and thefollowing one Indirectly sets how many seconds will pass between checks for new tasks

bull max_empty_runs (int) ndash how many loops are allowed to pass without processing anytasks before exiting the process 0 to keep always the process alive

78 Chapter 25 scheduler Module

web2py Documentation Release 2146-stable

bull discard_results (bool) ndash Scheduler stores executionsrsquos details into the sched-uler_run table By default only if there is a result the details are kept Turning this toTrue means discarding results even for tasks that return something

bull utc_time (bool) ndash do all datetime calculations assuming UTC as the timezone Remem-ber to pass start_time and stop_time to tasks accordingly

adj_hibernation()Used to increase the ldquosleeprdquo interval for DISABLED workers

assign_tasks(db)Assign task to workers that can then pop them from the queue

Deals with group_name(s) logic in order to assign linearly tasks to available workers for those groups

being_a_ticker()Elect a TICKER process that assigns tasks to available workers

Does its best to elect a worker that is not busy processing other tasks to allow a proper distribution of tasksamong all active workers ASAP

define_tables(db migrate)Define Scheduler tables structure

disable(group_names=None limit=None worker_name=None)Set DISABLED on the workers processing group_names tasks

A DISABLED worker will be kept alive but it wonrsquot be able to process any waiting tasks essentiallyputting it to sleep By default all group_names of Schedulerrsquos instantation are selected

get_workers(only_ticker=False)Returns a dict holding worker_name columns representing all ldquoregisteredrdquo workers only_ticker re-turns only the workers running as a TICKER if there are any

kill(group_names=None limit=None worker_name=None)Sets KILL as worker status The worker will be killed even if itrsquos processing a task

loop(worker_name=None)Main loop

This works basically as a neverending loop that

bull checks if the worker is ready to process tasks (is not DISABLED)

bull pops a task from the queue

bull if there is a task

ndash spawns the executor background process

ndash waits for the process to be finished

ndash sleeps heartbeat seconds

bull if there is not a task

ndash checks for max_empty_runs

ndash sleeps heartbeat seconds

now()Shortcut that fetches current time based on UTC preferences

pop_task(db)Grab a task ready to be executed from the queue

251 Background processes made simple 79

web2py Documentation Release 2146-stable

queue_task(function pargs=[] pvars= kwargs)Queue tasks This takes care of handling the validation of all parameters

Parameters

bull function ndash the function (anything callable with a __name__)

bull pargs ndash ldquorawrdquo args to be passed to the function Automatically jsonified

bull pvars ndash ldquorawrdquo kwargs to be passed to the function Automatically jsonified

bull kwargs ndash all the parameters available (basically every scheduler_task column) If argsand vars are here they should be jsonified already and they will override pargs and pvars

Returns a dict just as a normal validate_and_insert() plus a uuid key holding the uuid of thequeued task If validation is not passed ( ie some parameters are invalid) both id and uuidwill be None and yoursquoll get an ldquoerrorrdquo dict holding the errors found

report_task(task task_report)Take care of storing the result according to preferences

Deals with logic for repeating tasks

resume(group_names=None limit=None worker_name=None)Wakes a worker up (it will be able to process queued tasks)

send_heartbeat(counter)Coordination among available workers

It - sends the heartbeat - elects a ticker among available workers (the only process that

effectively dispatch tasks to workers)

bull deals with workerrsquos statuses

bull does ldquohousecleaningrdquo for dead workers

bull triggers tasks assignment to workers

set_requirements(scheduler_task)Called to set defaults for lazy_tables connections

set_worker_status(group_names=None action=rsquoACTIVErsquo exclude=None limit=Noneworker_name=None)

Internal function to set workerrsquos status

sleep()Calculate the number of seconds to sleep

stop_task(ref)Shortcut for task termination

If the task is RUNNING it will terminate it meaning that status will be set as FAILED

If the task is QUEUED its stop_time will be set as to ldquonowrdquo the enabled flag will be set to False andthe status to STOPPED

Parameters ref ndash can be

bull an integer lookup will be done by scheduler_taskid

bull a string lookup will be done by scheduler_taskuuid

Returns

bull 1 if task was stopped (meaning an update has been done)

80 Chapter 25 scheduler Module

web2py Documentation Release 2146-stable

bull None if task was not found or if task was not RUNNING or QUEUED

Note Experimental

task_status(ref output=False)Retrieves task status and optionally the result of the task

Parameters

bull ref ndash can be

ndash an integer lookup will be done by scheduler_taskid

ndash a string lookup will be done by scheduler_taskuuid

ndash a Query lookup as you wish eg

dbscheduler_tasktask_name == test1

bull output (bool) ndash if True fetch also the scheduler_run record

Returns a single Row object for the last queued task If output == True returns also the lastscheduler_run record The scheduler_run record is fetched by a left join so it can have allfields == None

terminate(group_names=None limit=None worker_name=None)Sets TERMINATE as worker status The worker will wait for any currently running tasks to be executedand then it will exit gracefully

static total_seconds(td)Backport for py26

update_dependencies(db task_id)Unblock execution paths for Jobs

wrapped_assign_tasks(db)Commodity function to call assign_tasks and trap exceptions

If an exception is raised assume it happened because of database contention and retries assign_task after05 seconds

wrapped_pop_task()Commodity function to call pop_task and trap exceptions

If an exception is raised assume it happened because of database contention and retries pop_task after 05seconds

wrapped_report_task(task task_report)Commodity function to call report_task and trap exceptions

If an exception is raised assume it happened because of database contention and retries pop_task after 05seconds

class gluonschedulerTYPE(myclass=lttype rsquolistrsquogt parse=False)Bases object

Validator that checks whether field is valid json and validates its type Used for args and vars of the sched-uler_task table

class gluonschedulerTask(app function timeout args=rsquo[]rsquo vars=rsquorsquo kwargs)Bases object

251 Background processes made simple 81

web2py Documentation Release 2146-stable

Defines a ldquotaskrdquo object that gets passed from the main thread to the executorrsquos one

class gluonschedulerTaskReport(status result=None output=None tb=None)Bases object

Defines a ldquotask reportrdquo object that gets passed from the executorrsquos thread to the main one

gluonschedulerexecutor(queue task out)The function used to execute tasks in the background process

gluonschedulermain()allows to run worker without python web2pypy by simply

python gluonschedulerpy

82 Chapter 25 scheduler Module

CHAPTER 26

serializers Module

This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

gluonserializerscast_keys(o cast=lttype rsquostrrsquogt encoding=rsquoutf-8rsquo)Builds a new object with ltcastgt type keys Use this function if you are in Python lt 265 This avoids syntaxerrors when unpacking dictionary arguments

Parameters

bull o ndash is the object input

bull cast ndash (defaults to str) is an object type or function which supports conversion such as

converted = cast(o)

bull encoding ndash (defaults to utf-8) is the encoding for unicode keys This is not used forcustom cast functions

gluonserializerscsv(value)

gluonserializerscustom_json(o)

gluonserializersics(events title=None link=None timeshift=0 calname=True ignored)

gluonserializersjson(value default=ltfunction custom_jsongt)

gluonserializersloads_json(o unicode_keys=True kwargs)

gluonserializersloads_yaml(data)

gluonserializersrss(feed)

gluonserializerssafe_encode(text)

gluonserializersxml(value encoding=rsquoUTF-8rsquo key=rsquodocumentrsquo quote=True)

gluonserializersxml_rec(value key quote=True)

gluonserializersyaml(data)

83

web2py Documentation Release 2146-stable

84 Chapter 26 serializers Module

CHAPTER 27

settings Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

85

web2py Documentation Release 2146-stable

86 Chapter 27 settings Module

CHAPTER 28

shell Module

This file is part of the web2py Web FrameworkDeveloped by Massimo Di Pierro ltmdipierrocsdepauledugtlimodou ltlimodougmailcomgt and srackham ltsrackhamgmailcomgtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

281 Web2py environment in the shell

gluonshelldie(msg)

gluonshellenable_autocomplete_and_history(adir env)

gluonshellenv(a import_models=False c=None f=None dir=rdquo extra_request=)Returns web2py execution environment for application (a) controller (c) function (f) If import_models is Truethe exec all application models into the environment

extra_request allows you to pass along any extra variables to the request object before your models get executedThis was mainly done to support web2py_utilstest_runner however you can use it with any wrapper scripts thatneed access to the web2py environment

gluonshellexec_environment(pyfile=rdquo request=None response=None session=None)Environment builder and module loader

Builds a web2py environment and optionally executes a Python file into the environment

A Storage dictionary containing the resulting environment is returned The working directory must be web2pyroot ndash this is the web2py default

gluonshellexec_pythonrc()

gluonshellexecute_from_command_line(argv=None)

gluonshellget_usage()

87

web2py Documentation Release 2146-stable

gluonshellparse_path_info(path_info av=False)Parses path info formatted like acf where c and f are optional and a leading is accepted Return tuple (a c f)If invalid path_info a is set to None If c or f are omitted they are set to None If av=True parse args and vars

gluonshellrun(appname plain=False import_models=False startfile=None bpython=Falsepython_code=False cronjob=False)

Start interactive shell or run Python script (startfile) in web2py controller environment appname is formattedlike

bull a web2py application name

bull ac exec the controller c into the application environment

gluonshelltest(testpath import_models=True verbose=False)Run doctests in web2py environment testpath is formatted like

bull a tests all controllers in application a

bull ac tests controller c in application a

bull acf test function f in controller c application a

Where a c and f are application controller and function names respectively If the testpath is a file name the fileis tested If a controller is specified models are executed by default

88 Chapter 28 shell Module

CHAPTER 29

sql Module

This file is part of the web2py Web FrameworkDeveloped by Massimo Di Pierro ltmdipierrocsdepauledugtlimodou ltlimodougmailcomgt and srackham ltsrackhamgmailcomgtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

291 Just for backward compatibility

class gluonsqlDAL(uri=rsquosqlitedummydbrsquo pool_size=0 folder=None db_codec=rsquoUTF-8rsquo check_reserved=None migrate=True fake_migrate=False mi-grate_enabled=True fake_migrate_all=False decode_credentials=Falsedriver_args=None adapter_args=None attempts=5 auto_import=False big-int_id=False debug=False lazy_tables=False db_uid=None do_connect=Trueafter_connection=None tables=None ignore_field_case=True en-tity_quoting=False table_hash=None)

Bases pydalhelpersclassesSerializable pydalhelpersclassesBasicStorage

An instance of this class represents a database connection

Parameters

bull uri (str) ndash contains information for connecting to a database Defaults tolsquosqlitedummydbrsquo

Note experimental you can specify a dictionary as uri parameter ie with

db = DAL(uri sqlitestoragesqlitetables )

for an example of dict input you can check the output of the scaffolding db model with

dbas_dict()

89

web2py Documentation Release 2146-stable

Note that for compatibility with Python older than version 265 you should cast your dictinput keys to str due to a syntax limitation on kwarg names for proper DAL dictionary inputyou can use one of

obj = serializerscast_keys(dict [encoding=utf-8])or else (for parsing json input)obj = serializersloads_json(data unicode_keys=False)

bull pool_size ndash How many open connections to make to the database object

bull folder ndash where table files will be created Automatically set within web2py Use anexplicit path when using DAL outside web2py

bull db_codec ndash string encoding of the database (default lsquoUTF-8rsquo)

bull table_hash ndash database identifier with tables If your connection hash change you canstill using old tables if they have db_hash as prefix

bull check_reserved ndash list of adapters to check tablenames and column names againstsqlnosql reserved keywords Defaults to None

ndash rsquocommonrsquo List of sql keywords that are common to all database types such as ldquoSELECTINSERTrdquo (recommended)

ndash rsquoallrsquo Checks against all known SQL keywords

ndash rsquoltadapternamegtrdquo Checks against the specific adapters list of keywords

ndash rsquoltadapternamegt_nonreservedrsquo Checks against the specific adapters list of nonreservedkeywords (if available)

bull migrate ndash sets default migrate behavior for all tables

bull fake_migrate ndash sets default fake_migrate behavior for all tables

bull migrate_enabled ndash If set to False disables ALL migrations

bull fake_migrate_all ndash If set to True fake migrates ALL tables

bull attempts ndash Number of times to attempt connecting

bull auto_import ndash If set to True tries import automatically table definitions from thedatabases folder (works only for simple models)

bull bigint_id ndash If set turn on bigint instead of int for id and reference fields

bull lazy_tables ndash delays table definition until table access

bull after_connection ndash can a callable that will be executed after the connection

Example

Use as

db = DAL(sqlitetestdb)

or

90 Chapter 29 sql Module

web2py Documentation Release 2146-stable

db = DAL(uri tables []) experimental

dbdefine_table(tablename Field(fieldname1)Field(fieldname2))

class Field(fieldname type=rsquostringrsquo length=None default=ltfunction ltlambdagtgt re-quired=False requires=ltfunction ltlambdagtgt ondelete=rsquoCASCADErsquo not-null=False unique=False uploadfield=True widget=None label=None com-ment=None writable=True readable=True update=None authorize=Noneautodelete=False represent=None uploadfolder=None uploadseparate=Falseuploadfs=None compute=None custom_store=None custom_retrieve=Nonecustom_retrieve_file_properties=None custom_delete=None filter_in=None fil-ter_out=None custom_qualifier=None map_none=None rname=None)

Bases pydalobjectsExpression pydalhelpersclassesSerializable

Lazyalias of FieldMethod

Methodalias of FieldMethod

Virtualalias of FieldVirtual

as_dict(flat=False sanitize=True)

clone(point_self_references_to=False args)

count(distinct=None)

formatter(value)

retrieve(name path=None nameonly=False)If nameonly==True return (filename fullfilename) instead of (filename stream)

retrieve_file_properties(name path=None)

set_attributes(args attributes)

sqlsafe

sqlsafe_name

store(file filename=None path=None)

validate(value)

class Row(args kwargs)Bases pydalhelpersclassesBasicStorage

A dictionary that lets you do d[lsquoarsquo] as well as da this is only used to store a Row

as_dict(datetime_to_str=False custom_types=None)

as_json(mode=rsquoobjectrsquo default=None colnames=None serialize=True kwargs)serializes the row to a JSON object kwargs are passed to as_dict method only ldquoobjectrdquo mode sup-ported

serialize = False used by Rowsas_json

TODO return array mode with query column order

mode and colnames are not implemented

as_xml(row_name=rsquorowrsquo colnames=None indent=rsquo rsquo)

291 Just for backward compatibility 91

web2py Documentation Release 2146-stable

get(key default=None)

class Table(db tablename fields args)Bases pydalhelpersclassesSerializable pydalhelpersclassesBasicStorage

Represents a database table

Example

You can create a table as db = DAL( ) dbdefine_table(lsquousersrsquo Field(lsquonamersquo))

And then

dbusersinsert(name=me) print dbusers_insert() to see SQLdbusersdrop()

as_dict(flat=False sanitize=True)

bulk_insert(items)here items is a list of dictionaries

drop(mode=rdquo)

fields

import_from_csv_file(csvfile id_map=None null=rsquoltNULLgtrsquo unique=rsquouuidrsquoid_offset=None args kwargs)

Import records from csv file Column headers must have same names as table fields Field lsquoidrsquo isignored If column names read lsquotablefilersquo the lsquotablersquo prefix is ignored

bull lsquouniquersquo argument is a field which must be unique (typically a uuid field)bull lsquorestorersquo argument is default False if set True will remove old values in table firstbull lsquoid_maprsquo if set to None will not map ids

The import will keep the id numbers in the restored table This assumes that there is an field of typeid that is integer and in incrementing order Will keep the id numbers in restored table

insert(fields)

on(query)

sqlsafe

sqlsafe_alias

truncate(mode=None)

update(args kwargs)

update_or_insert(_key=ltfunction ltlambdagtgt values)

validate_and_insert(fields)

validate_and_update(_key=ltfunction ltlambdagtgt fields)

validate_and_update_or_insert(_key=ltfunction ltlambdagtgt fields)

with_alias(alias)

as_dict(flat=False sanitize=True)

can_join()

check_reserved_keyword(name)Validates name against SQL keywords Uses selfcheck_reserve which is a list of operators to use

close()

92 Chapter 29 sql Module

web2py Documentation Release 2146-stable

commit()

define_table(tablename fields args)

static distributed_transaction_begin(instances)

static distributed_transaction_commit(instances)

executesql(query placeholders=None as_dict=False fields=None colnames=Noneas_ordered_dict=False)

Executes an arbitrary query

Parameters

bull query (str) ndash the query to submit to the backend

bull placeholders ndash is optional and will always be None If using raw SQL with place-holders placeholders may be a sequence of values to be substituted in or (if supported bythe DB driver) a dictionary with keys matching named placeholders in your SQL

bull as_dict ndash will always be None when using DAL If using raw SQL can be set to Trueand the results cursor returned by the DB driver will be converted to a sequence of dic-tionaries keyed with the db field names Results returned with as_dict=True are the sameas those returned when applying to_list() to a DAL query If ldquoas_ordered_dictrdquo=True thebehaviour is the same as when ldquoas_dictrdquo=True with the keys (field names) guaranteed tobe in the same order as returned by the select name executed on the database

bull fields ndash list of DAL Fields that match the fields returned from the DB The Field objectsshould be part of one or more Table objects defined on the DAL object The ldquofieldsrdquo listcan include one or more DAL Table objects in addition to or instead of including Fieldobjects or it can be just a single table (not in a list) In that case the Field objects will beextracted from the table(s)

Note if either fields or colnames is provided the results will be converted to a DAL Rowsobject using the db_adapterparse() method

bull colnames ndash list of field names in tablenamefieldname format

Note It is also possible to specify both ldquofieldsrdquo and the associated ldquocolnamesrdquo In that case ldquofieldsrdquocan also include DAL Expression objects in addition to Field objects For Field objects in ldquofieldsrdquo theassociated ldquocolnamesrdquo must still be in tablenamefieldname format For Expression objects in ldquofieldsrdquo theassociated ldquocolnamesrdquo can be any arbitrary labels

DAL Table objects referred to by ldquofieldsrdquo or ldquocolnamesrdquo can be dummy tables and do not have to representany real tables in the database Also note that the ldquofieldsrdquo and ldquocolnamesrdquo must be in the same order asthe fields in the results cursor returned from the DB

export_to_csv_file(ofile args kwargs)

static get_instances()Returns a dictionary with uri as key with timings and defined tables

sqlitestoragesqlite dbstats [(select auth_useremail from auth_user 002009)]dbtables

defined [auth_cas auth_event auth_groupauth_membership auth_permission auth_user]

(continues on next page)

291 Just for backward compatibility 93

web2py Documentation Release 2146-stable

(continued from previous page)

lazy []

has_representer(name)

import_from_csv_file(ifile id_map=None null=rsquoltNULLgtrsquo unique=rsquouuidrsquomap_tablenames=None ignore_missing_tables=False args kwargs)

import_table_definitions(path migrate=False fake_migrate=False tables=None)

lazy_define_table(tablename fields args)

logger = ltloggingLogger objectgt

parse_as_rest(patterns args vars queries=None nested_select=True)

Example

Use as

dbdefine_table(personField(name)Field(info))dbdefine_table(pet

Field(ownedbydbperson)Field(name)Field(info)

)

requestrestful()def index()

def GET(argsvars)patterns = [

friends[person]personnamefieldpersonnamepets[petownedby]personnamepets[petownedby]petnamepersonnamepets[petownedby]petnamefield(dogs[pet] dbpetinfo==dog)(dogs[pet]petnamestartswith dbpetinfo==dog)]

parser = dbparse_as_rest(patternsargsvars)if parserstatus == 200

return dict(content=parserresponse)else

raise HTTP(parserstatusparsererror)

def POST(table_namevars)if table_name == person

return dbpersonvalidate_and_insert(vars)elif table_name == pet

return dbpetvalidate_and_insert(vars)else

raise HTTP(400)return locals()

represent(name args kwargs)

representers = rows_render ltfunction represent at 0x7fcf10dcdb18gt rows_xml ltclass gluonsqlhtmlSQLTABLEgt

94 Chapter 29 sql Module

web2py Documentation Release 2146-stable

rollback()

serializers = json ltfunction custom_json at 0x7fcf11069488gt xml ltfunction xml at 0x7fcf11069578gt

static set_folder(folder)

smart_query(fields text)

tables

uuid()

validators = None

validators_method(field)Field type validation using web2pyrsquos validators mechanism

makes sure the content of a field is in line with the declared fieldtype

where(query=None ignore_common_filters=None)

class gluonsqlField(fieldname type=rsquostringrsquo length=None default=ltfunction ltlambdagtgtrequired=False requires=ltfunction ltlambdagtgt ondelete=rsquoCASCADErsquonotnull=False unique=False uploadfield=True widget=None label=Nonecomment=None writable=True readable=True update=None autho-rize=None autodelete=False represent=None uploadfolder=None upload-separate=False uploadfs=None compute=None custom_store=Nonecustom_retrieve=None custom_retrieve_file_properties=None cus-tom_delete=None filter_in=None filter_out=None custom_qualifier=Nonemap_none=None rname=None)

Bases pydalobjectsExpression pydalhelpersclassesSerializable

LazyRepresents a database field

Example

Usage

a = Field(name string length=32 default=None required=Falserequires=IS_NOT_EMPTY() ondelete=CASCADEnotnull=False unique=Falseuploadfield=True widget=None label=None comment=Noneuploadfield=True True means store on disk

a_field_name means store in this field in db False means file content will be discarded

writable=True readable=True update=None authorize=Noneautodelete=False represent=None uploadfolder=Noneuploadseparate=False upload to separate directories by uuid_keys

first 2 character and tablenamefieldname False - old behavior True - put uploaded file in ltuploaddirgtlttablenamegtltfieldnamegtuuid_key[2] directory)

uploadfs=None a pyfilesystem where to store upload)

to be used as argument of DALdefine_table

alias of FieldMethod

291 Just for backward compatibility 95

web2py Documentation Release 2146-stable

Methodalias of FieldMethod

Virtualalias of FieldVirtual

as_dict(flat=False sanitize=True)

clone(point_self_references_to=False args)

count(distinct=None)

formatter(value)

retrieve(name path=None nameonly=False)If nameonly==True return (filename fullfilename) instead of (filename stream)

retrieve_file_properties(name path=None)

set_attributes(args attributes)

sqlsafe

sqlsafe_name

store(file filename=None path=None)

validate(value)

96 Chapter 29 sql Module

CHAPTER 30

sqlhtml Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

Holds

bull SQLFORM provide a form for a table (withwithout record)

bull SQLTABLE provides a table for a set of records

bull form_factory provides a SQLFORM for an non-db backed table

class gluonsqlhtmlAutocompleteWidget(request field id_field=None db=None or-derby=None limitby=(0 10) distinct=False key-word=rsquo_autocomplete_(tablename)s_(fieldname)srsquomin_length=2 help_fields=Nonehelp_string=None at_beginning=True)

Bases object

callback()

class gluonsqlhtmlBooleanWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates an INPUT checkbox tag

see also FormWidgetwidget

class gluonsqlhtmlCacheRepresenterBases object

class gluonsqlhtmlCheckboxesWidgetBases gluonsqlhtmlOptionsWidget

classmethod widget(field value attributes)Generates a TABLE tag including INPUT checkboxes (multiple allowed)

97

web2py Documentation Release 2146-stable

see also FormWidgetwidget

class gluonsqlhtmlDateWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlDatetimeWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlDecimalWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlDoubleWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlExportClass(rows)Bases object

content_type = None

export()

file_ext = None

label = None

represented()

class gluonsqlhtmlExporterCSV(rows)Bases gluonsqlhtmlExportClass

content_type = textcsv

export()

file_ext = csv

label = CSV

class gluonsqlhtmlExporterCSV_hidden(rows)Bases gluonsqlhtmlExportClass

content_type = textcsv

export()

file_ext = csv

label = CSV

class gluonsqlhtmlExporterHTML(rows)Bases gluonsqlhtmlExportClass

content_type = texthtml

export()

file_ext = html

label = HTML

class gluonsqlhtmlExporterJSON(rows)Bases gluonsqlhtmlExportClass

content_type = applicationjson

export()

file_ext = json

98 Chapter 30 sqlhtml Module

web2py Documentation Release 2146-stable

label = JSON

class gluonsqlhtmlExporterTSV(rows)Bases gluonsqlhtmlExportClass

content_type = texttab-separated-values

export()

file_ext = csv

label = TSV

class gluonsqlhtmlExporterXML(rows)Bases gluonsqlhtmlExportClass

content_type = textxml

export()

file_ext = xml

label = XML

class gluonsqlhtmlFormWidgetBases object

Helper for SQLFORM to generate form input fields (widget) related to the fieldtype

classmethod widget(field value attributes)Generates the widget for the field

When serialized will provide an INPUT tag

bull id = tablename_fieldname

bull class = fieldtype

bull name = fieldname

Parameters

bull field ndash the field needing the widget

bull value ndash value

bull attributes ndash any other attributes to be applied

class gluonsqlhtmlIntegerWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlJSONWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates a TEXTAREA for JSON notation

see also FormWidgetwidget

class gluonsqlhtmlListWidgetBases gluonsqlhtmlStringWidget

classmethod widget(field value attributes)Generates an INPUT text tag

see also FormWidgetwidget

99

web2py Documentation Release 2146-stable

class gluonsqlhtmlMultipleOptionsWidgetBases gluonsqlhtmlOptionsWidget

classmethod widget(field value size=5 attributes)Generates a SELECT tag including OPTIONs (multiple options allowed)

see also FormWidgetwidget

Parameters size ndash optional param (default=5) to indicate how many rows must be shown

class gluonsqlhtmlOptionsWidgetBases gluonsqlhtmlFormWidget

static has_options(field)Checks if the field has selectable options

Parameters field ndash the field needing checking

Returns True if the field has options

classmethod widget(field value attributes)Generates a SELECT tag including OPTIONs (only 1 option allowed)

see also FormWidgetwidget

class gluonsqlhtmlPasswordWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates a INPUT password tag If a value is present it will be shown as a number of lsquorsquo not related tothe length of the actual value

see also FormWidgetwidget

class gluonsqlhtmlRadioWidgetBases gluonsqlhtmlOptionsWidget

classmethod widget(field value attributes)Generates a TABLE tag including INPUT radios (only 1 option allowed)

see also FormWidgetwidget

class gluonsqlhtmlSQLFORM(table record=None deletable=False linkto=None upload=Nonefields=None labels=None col3= submit_button=rsquoSubmitrsquodelete_label=rsquoCheck to deletersquo showid=True readonly=False com-ments=True keepopts=[] ignore_rw=False record_id=Noneformstyle=None buttons=[rsquosubmitrsquo] separator=None ex-tra_fields=None attributes)

Bases gluonhtmlFORM

SQLFORM is used to map a table (and a current record) into an HTML form

Given a Table like dbtable

Generates an insert form

SQLFORM(dbtable)

Generates an update form

record=dbtable[some_id]SQLFORM(dbtable record)

Generates an update with a delete button

100 Chapter 30 sqlhtml Module

web2py Documentation Release 2146-stable

SQLFORM(dbtable record deletable=True)

Parameters

bull table ndash Table object

bull record ndash either an int if the id is an int or the record fetched from the table

bull deletable ndash adds the delete checkbox

bull linkto ndash the URL of a controllerfunction to access referencedby records

bull upload ndash the URL of a controllerfunction to download an uploaded file

bull fields ndash a list of fields that should be placed in the form default is all

bull labels ndash a dictionary with labels for each field keys are the field names

bull col3 ndash a dictionary with content for an optional third column (right of each field) keys arefield names

bull submit_button ndash text to show in the submit button

bull delete_label ndash text to show next to the delete checkbox

bull showid ndash shows the id of the record

bull readonly ndash doesnrsquot allow for any modification

bull comments ndash show comments (stored in col3 or in Field definition)

bull ignore_rw ndash overrides readablewritable attributes

bull record_id ndash used to create session key against CSRF

bull formstyle ndash what to use to generate the form layout

bull buttons ndash override buttons as you please (will be also stored in formcustomsubmit)

bull separator ndash character as separator between labels and inputs

any named optional attribute is passed to the ltformgt tag for example _class _id _style _action _method etc

AUTOTYPES = lttype intgt (integer ltgluonvalidatorsIS_INT_IN_RANGE object at 0x7fcf10deb210gt) lttype floatgt (double ltgluonvalidatorsIS_FLOAT_IN_RANGE object at 0x7fcf10deb250gt) lttype unicodegt (string None) lttype boolgt (boolean None) lttype strgt (string None) lttype listgt (liststring None) lttype datetimedatetimegt (datetime ltgluonvalidatorsIS_DATETIME object at 0x7fcf10deb310gt) lttype datetimedategt (date ltgluonvalidatorsIS_DATE object at 0x7fcf10deb2d0gt)

FIELDKEY_DELETE_RECORD = delete_record

FIELDNAME_REQUEST_DELETE = delete_this_record

ID_LABEL_SUFFIX = __label

ID_ROW_SUFFIX = __row

accepts(request_vars session=None formname=rsquo(tablename)s(record_id)srsquo keepvalues=Noneonvalidation=None dbio=True hideerror=False detect_record_change=False kwargs)

Similar to FORMaccepts but also does insert update or delete in DAL If detect_record_change is Truethan

bull formrecord_changed = False (record is properly validatedsubmitted)

bull formrecord_changed = True (record cannot be submitted because changed)

If detect_record_change == False than

bull formrecord_changed = None

assert_status(status request_vars)

101

web2py Documentation Release 2146-stable

static build_query(fields keywords)

createform(xfields)

static dictform(dictionary kwargs)

static factory(fields attributes)Generates a SQLFORM for the given fields

Internally will build a non-database based data model to hold the fields

formstyles = bootstrap ltfunction formstyle_bootstrap at 0x7fcf10de99b0gt bootstrap3_inline ltfunction _inner at 0x7fcf10de9b90gt bootstrap3_stacked ltfunction formstyle_bootstrap3_stacked at 0x7fcf10de9a28gt divs ltfunction formstyle_divs at 0x7fcf10de9848gt inline ltfunction formstyle_inline at 0x7fcf10de98c0gt table2cols ltfunction formstyle_table2cols at 0x7fcf10de97d0gt table3cols ltfunction formstyle_table3cols at 0x7fcf10dcdde8gt ul ltfunction formstyle_ul at 0x7fcf10de9938gt

static grid(query fields=None field_id=None left=None headers= or-derby=None groupby=None searchable=True sortable=True pagi-nate=20 deletable=True editable=True details=True selectable=None cre-ate=True csv=True links=None links_in_grid=True upload=rsquoltdefaultgtrsquoargs=[] user_signature=True maxtextlengths= maxtextlength=20 on-validation=None onfailure=None oncreate=None onupdate=None on-delete=None sorter_icons=(ltgluonhtmlXML objectgt ltgluonhtmlXMLobjectgt) ui=rsquoweb2pyrsquo showbuttontext=True _class=rsquoweb2py_gridrsquo form-name=rsquoweb2py_gridrsquo search_widget=rsquodefaultrsquo advanced_search=True ig-nore_rw=False formstyle=None exportclasses=None formargs= cre-ateargs= editargs= viewargs= selectable_submit_button=rsquoSubmitrsquobuttons_placement=rsquorightrsquo links_placement=rsquorightrsquo noconfirm=Falsecache_count=None client_side_delete=False ignore_common_filters=Noneauto_pagination=True use_cursor=False)

static search_menu(fields search_options=None prefix=rsquow2prsquo)

static smartdictform(session name filename=None query=None kwargs)

static smartgrid(table constraints=None linked_tables=None links=None links_in_grid=Trueargs=None user_signature=True divider=rsquogtrsquo breadcrumbs_class=rdquokwargs)

Builds a system of SQLFORMgrid(s) between any referenced tables

Parameters

bull table ndash main table

bull constraints (dict) ndash lsquotablersquoquery that limits which records can be accessible

bull links (dict) ndash like lsquotablenamersquo[lambda row A( ) ] that will add buttons whentable tablename is displayed

bull linked_tables (list) ndash list of tables to be linked

Example

given you defined a model as

dbdefine_table(person Field(name) format=(name)s)dbdefine_table(dog

Field(name) Field(owner dbperson) format=(name)s)dbdefine_table(comment Field(body) Field(dog dbdog))if db(dbperson)isempty()

from gluoncontribpopulate import populatepopulate(dbperson 300)populate(dbdog 300)populate(dbcomment 1000)

102 Chapter 30 sqlhtml Module

web2py Documentation Release 2146-stable

in a controller you can do

authrequires_login()def index()

form=SQLFORMsmartgrid(db[requestargs(0) or person])return dict(form=form)

widgets = autocomplete ltclass gluonsqlhtmlAutocompleteWidgetgt blob None boolean ltclass gluonsqlhtmlBooleanWidgetgt checkboxes ltclass gluonsqlhtmlCheckboxesWidgetgt date ltclass gluonsqlhtmlDateWidgetgt datetime ltclass gluonsqlhtmlDatetimeWidgetgt decimal ltclass gluonsqlhtmlDecimalWidgetgt double ltclass gluonsqlhtmlDoubleWidgetgt integer ltclass gluonsqlhtmlIntegerWidgetgt json ltclass gluonsqlhtmlJSONWidgetgt list ltclass gluonsqlhtmlListWidgetgt multiple ltclass gluonsqlhtmlMultipleOptionsWidgetgt options ltclass gluonsqlhtmlOptionsWidgetgt password ltclass gluonsqlhtmlPasswordWidgetgt radio ltclass gluonsqlhtmlRadioWidgetgt string ltclass gluonsqlhtmlStringWidgetgt text ltclass gluonsqlhtmlTextWidgetgt time ltclass gluonsqlhtmlTimeWidgetgt upload ltclass gluonsqlhtmlUploadWidgetgt

class gluonsqlhtmlSQLTABLE(sqlrows linkto=None upload=None orderby=None headers=truncate=16 columns=None th_link=rdquo extracolumns=None se-lectid=None renderstyle=False cid=None colgroup=False at-tributes)

Bases gluonhtmlTABLE

Given with a Rows object as returned by a db()select() generates an html table with the rows

Parameters

bull sqlrows ndash the Rows object

bull linkto ndash URL (or lambda to generate a URL) to edit individual records

bull upload ndash URL to download uploaded files

bull orderby ndash Add an orderby link to column headers

bull headers ndash dictionary of headers to headers redefinions headers can also be a string to gen-erate the headers from data for now only headers=rdquofieldnamecapitalizerdquo headers=rdquolabelsrdquoand headers=None are supported

bull truncate ndash length at which to truncate text in table cells Defaults to 16 characters

bull columns ndash a list or dict contaning the names of the columns to be shown Defaults to all

bull th_link ndash base link to support orderby headers

bull extracolumns ndash a list of dicts

bull selectid ndash The id you want to select

bull renderstyle ndash Boolean render the style with the table

bull cid ndash use this cid for all links

bull colgroup ndash FIXME

Extracolumns example

[labelA(Extra _href=)class class name of the headerwidth width in pixels or contentlambda row rc A(Edit _href=editsrowid)selected False agregate class selected to this column]

style()

class gluonsqlhtmlStringWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates an INPUT text tag

see also FormWidgetwidget

103

web2py Documentation Release 2146-stable

class gluonsqlhtmlTextWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates a TEXTAREA tag

see also FormWidgetwidget

class gluonsqlhtmlTimeWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlUploadWidgetBases gluonsqlhtmlFormWidget

DEFAULT_WIDTH = 150px

DELETE_FILE = delete

GENERIC_DESCRIPTION = file download

ID_DELETE_SUFFIX = __delete

static is_image(value)Tries to check if the filename provided references to an image

Checking is based on filename extension Currently recognized gif png jp(e)g bmp

Parameters value ndash filename

classmethod represent(field value download_url=None)How to represent the file

bull with download url and if it is an image ltA href= gtltIMG gtltAgt

bull otherwise with download url ltA href= gtfileltAgt

bull otherwise file

Parameters

bull field ndash the field

bull value ndash the field value

bull download_url ndash url for the file download (default = None)

classmethod widget(field value download_url=None attributes)generates a INPUT file tag

Optionally provides an A link to the file including a checkbox so the file can be deleted

All is wrapped in a DIV

see also FormWidgetwidget

Parameters

bull field ndash the field

bull value ndash the field value

bull download_url ndash url for the file download (default = None)

gluonsqlhtmladd_class(a b)

104 Chapter 30 sqlhtml Module

web2py Documentation Release 2146-stable

gluonsqlhtmlform_factory(fields attributes)Generates a SQLFORM for the given fields

Internally will build a non-database based data model to hold the fields

gluonsqlhtmlformstyle_bootstrap(form fields)bootstrap 23x format form layout

gluonsqlhtmlformstyle_bootstrap3_inline_factory(col_label_size=3)bootstrap 3 horizontal form layout

Note Experimental

gluonsqlhtmlformstyle_bootstrap3_stacked(form fields)bootstrap 3 format form layout

Note Experimental

gluonsqlhtmlformstyle_divs(form fields)divs only

gluonsqlhtmlformstyle_inline(form fields)divs only but inline

gluonsqlhtmlformstyle_table2cols(form fields)2 column table

gluonsqlhtmlformstyle_table3cols(form fields)3 column table - default

gluonsqlhtmlformstyle_ul(form fields)unordered list

gluonsqlhtmlrepresent(field value record)

gluonsqlhtmlsafe_float(x)

gluonsqlhtmlsafe_int(x)

gluonsqlhtmlshow_if(cond)

105

web2py Documentation Release 2146-stable

106 Chapter 30 sqlhtml Module

CHAPTER 31

storage Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

Provides

bull List like list but returns None instead of IndexOutOfBounds

bull Storage like dictionary allowing also for objfoo for obj[lsquofoorsquo]

class gluonstorageListBases list

Like a regular python list but callable When a(i) is called if i is out of bounds returns None instead of IndexError

class gluonstorageStorageBases dict

A Storage object is like a dictionary except objfoo can be used in addition to obj[lsquofoorsquo] and setting objfoo =None deletes item foo

Example

gtgtgt o = Storage(a=1)gtgtgt print oa1

gtgtgt o[a]1

gtgtgt oa = 2gtgtgt print o[a]2

gtgtgt del oa

(continues on next page)

107

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt print oaNone

getfirst(key default=None)Returns the first value of a list or the value itself when given a requestvars style key

If the value is a list its first item will be returned otherwise the value will be returned as-is

Example output for a query string of x=abcampy=abcampy=def

gtgtgt request = Storage()gtgtgt requestvars = Storage()gtgtgt requestvarsx = abcgtgtgt requestvarsy = [abc def]gtgtgt requestvarsgetfirst(x)abcgtgtgt requestvarsgetfirst(y)abcgtgtgt requestvarsgetfirst(z)

getlast(key default=None)Returns the last value of a list or value itself when given a requestvars style key

If the value is a list the last item will be returned otherwise the value will be returned as-is

Simulated output with a query string of x=abcampy=abcampy=def

gtgtgt request = Storage()gtgtgt requestvars = Storage()gtgtgt requestvarsx = abcgtgtgt requestvarsy = [abc def]gtgtgt requestvarsgetlast(x)abcgtgtgt requestvarsgetlast(y)defgtgtgt requestvarsgetlast(z)

getlist(key)Returns a Storage value as a list

If the value is a list it will be returned as-is If object is None an empty list will be returned Otherwise[value] will be returned

Example output for a query string of x=abcampy=abcampy=def

gtgtgt request = Storage()gtgtgt requestvars = Storage()gtgtgt requestvarsx = abcgtgtgt requestvarsy = [abc def]gtgtgt requestvarsgetlist(x)[abc]gtgtgt requestvarsgetlist(y)[abc def]gtgtgt requestvarsgetlist(z)[]

class gluonstorageSettingsBases gluonstorageStorage

108 Chapter 31 storage Module

web2py Documentation Release 2146-stable

class gluonstorageMessages(T)Bases gluonstorageSettings

class gluonstorageStorageListBases gluonstorageStorage

Behaves like Storage but missing elements defaults to [] instead of None

gluonstorageload_storage(filename)

gluonstoragesave_storage(storage filename)

109

web2py Documentation Release 2146-stable

110 Chapter 31 storage Module

CHAPTER 32

streamer Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

321 Facilities to handle file streaming

gluonstreamerstream_file_or_304_or_206(static_file chunk_size=65536 request=Noneheaders= status=200 error_message=None)

gluonstreamerstreamer(stream chunk_size=65536 bytes=None)

111

web2py Documentation Release 2146-stable

112 Chapter 32 streamer Module

CHAPTER 33

template Module

This file is part of the web2py Web FrameworkLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)Author Thadeus BurgessContributors- Massimo Di Pierro for creating the original gluontemplatepy- Jonathan Lundell for extensively testing the regex on Jython- Limodou (creater of uliweb) who inspired the block-element support for web2py

331 Templating syntax

class gluontemplateBlockNode(name=rdquo pre_extend=False delimiters=(rsquorsquo rsquorsquo))Bases gluontemplateNode

Block Container

This Node can contain other Nodes and will render in a hierarchical order of when nodes were added

ie

block test This is default block test

end

append(node)Adds an element to the nodes

Parameters node ndash Node object or string to append

extend(other)Extends the list of nodes with another BlockNode class

Parameters other ndash BlockNode or Content object to extend from

113

web2py Documentation Release 2146-stable

output(blocks)Merges all nodes into a single string

Parameters blocks ndash Dictionary of blocks that are extending from this template

class gluontemplateContent(name=rsquoContentBlockrsquo pre_extend=False)Bases gluontemplateBlockNode

Parent Container ndash Used as the root level BlockNode

Contains functions that operate as such

Parameters name ndash Unique name for this BlockNode

append(node)Adds a node to list If it is a BlockNode then we assign a block for it

clear_content()

extend(other)Extends the objects list of nodes with another objects nodes

insert(other index=0)Inserts object at index

You may pass a list of objects and have them inserted

class gluontemplateDummyResponse

write(data escape=True)

class gluontemplateNOESCAPE(text)A little helper to avoid escaping

xml()

class gluontemplateNode(value=None pre_extend=False)Bases object

Basic Container Object

class gluontemplateSuperNode(name=rdquo pre_extend=False)Bases gluontemplateNode

class gluontemplateTemplateParser(text name=rsquoParserContainerrsquo context=path=rsquoviewsrsquo writer=rsquoresponsewritersquo lexers=delimiters=(rsquorsquo rsquorsquo) _super_nodes=[])

Bases object

Parse all blocks

Parameters

bull text ndash text to parse

bull context ndash context to parse in

bull path ndash folder path to templates

bull writer ndash string of writer class to use

bull lexers ndash dict of custom lexers to use

bull delimiters ndash for example (lsquolsquorsquorsquo)

114 Chapter 33 template Module

web2py Documentation Release 2146-stable

bull _super_nodes ndash a list of nodes to check for inclusion this should only be set byldquoselfextendrdquo It contains a list of SuperNodes from a child template that need to be han-dled

default_delimiters = ( )

extend(filename)Extends filename Anything not declared in a block defined by the parent will be placed in the parenttemplates include block

include(content filename)Includes filename here

parse(text)

r_multiline = lt_sreSRE_Pattern objectgt

r_tag = lt_sreSRE_Pattern objectgt

re_block = lt_sreSRE_Pattern objectgt

re_pass = lt_sreSRE_Pattern objectgt

re_unblock = lt_sreSRE_Pattern objectgt

reindent(text)Reindents a string of unindented python code

to_string()Returns the parsed template with correct indentation

Used to make it easier to port to python3

gluontemplateget_parsed(text)Returns the indented python code of text Useful for unit testing

gluontemplateoutput_aux(node blocks)

gluontemplateparse_template(filename path=rsquoviewsrsquo context= lexers= delimiters=(rsquorsquorsquorsquo))

Parameters

bull filename ndash can be a view filename in the views folder or an input stream

bull path ndash is the path of a views folder

bull context ndash is a dictionary of symbols used to render the template

bull lexers ndash dict of custom lexers to use

bull delimiters ndash opening and closing tags

gluontemplaterender(content=rsquohello worldrsquo stream=None filename=None path=None con-text= lexers= delimiters=(rsquorsquo rsquorsquo) writer=rsquoresponsewritersquo)

Generic render function

Parameters

bull content ndash default content

bull stream ndash file-like obj to read template from

bull filename ndash where to find template

bull path ndash base path for templates

bull context ndash env

331 Templating syntax 115

web2py Documentation Release 2146-stable

bull lexers ndash custom lexers to use

bull delimiters ndash opening and closing tags

bull writer ndash where to inject the resulting stream

Example

gtgtgt render()hello worldgtgtgt render(content=abc)abcgtgtgt render(content=abc)abcgtgtgt render(content=abc)abcgtgtgt render(content=anbc)anbcgtgtgt render(content=abcde)abcdegtgtgt render(content=anc)ancgtgtgt render(content=ac)acgtgtgt render(content=for i in range(a)=iltbr gtpassrarr˓context=dict(a=5))0ltbr gt1ltbr gt2ltbr gt3ltbr gt4ltbr gtgtgtgt render(content=for i in range(a)=iltbr gtpassrarr˓context=dict(a=5)delimiters=())0ltbr gt1ltbr gt2ltbr gt3ltbr gt4ltbr gtgtgtgt render(content==hellonworld)hellonworldgtgtgt render(content=for i in range(3)n=inpass)012

116 Chapter 33 template Module

CHAPTER 34

tools Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

341 Auth Mail PluginManager and various utilities

class gluontoolsMail(server=None sender=None login=None tls=True)Bases object

Class for configuring and sending emails with alternative text html body multiple attachments and encryptionsupport

Works with SMTP and Google App Engine

Parameters

bull server ndash SMTP server address in addressport notation

bull sender ndash sender email address

bull login ndash sender login name and password in loginpassword notation or None if no authen-tication is required

bull tls ndash enablesdisables encryption (True by default)

In Google App Engine use

server=gae

For sake of backward compatibility all fields are optional and default to None however to be able to send emailsat least server and sender must be specified They are available under following fields

117

web2py Documentation Release 2146-stable

mailsettingsservermailsettingssendermailsettingsloginmailsettingstimeout = 60 seconds (default)

When server is lsquologgingrsquo email is logged but not sent (debug mode)

Optionally you can use PGP encryption or X509

mailsettingscipher_type = Nonemailsettingsgpg_home = Nonemailsettingssign = Truemailsettingssign_passphrase = Nonemailsettingsencrypt = Truemailsettingsx509_sign_keyfile = Nonemailsettingsx509_sign_certfile = Nonemailsettingsx509_sign_chainfile = Nonemailsettingsx509_nocerts = Falsemailsettingsx509_crypt_certfiles = None

cipher_type Nonegpg - need a python-pyme package and gpgme libx509 - smime

gpg_home you can set a GNUPGHOME environment variableto specify home of gnupg

sign sign the message (True or False)sign_passphrase passphrase for key signingencrypt encrypt the message (True or False) It defaults

to True x509 only

x509_sign_keyfile the signers private key filename orstring containing the key (PEM format)

x509_sign_certfile the signers certificate filename orstring containing the cert (PEM format)

x509_sign_chainfile sets the optional all-in-one file where youcan assemble the certificates of CertificationAuthorities (CA) which form the certificatechain of email certificate It can be astring containing the certs to (PEM format)

x509_nocerts if True then no attached certificate in mailx509_crypt_certfiles the certificates file or strings to encrypt

the messages with can be a file name string or a list of file names strings (PEM format)

Examples

Create Mail object with authentication data for remote server

mail = Mail(examplecom25 meexamplecom mepassword)

Notice for GAE users attachments have an automatic content_id=rsquoattachment-irsquo where i is progressive num-ber in this way the can be referenced from the HTML as ltimg src=rdquocidattachment-0rdquo gt etc

118 Chapter 34 tools Module

web2py Documentation Release 2146-stable

class Attachment(payload filename=None content_id=None content_type=Noneencoding=rsquoutf-8rsquo)

Bases emailmimebaseMIMEBase

Email attachment

Parameters

bull payload ndash path to file or file-like object with read() method

bull filename ndash name of the attachment stored in message if set to None it will be fetchedfrom payload path file-like object payload must have explicit filename specified

bull content_id ndash id of the attachment automatically contained within lt and gt

bull content_type ndash content type of the attachment if set to None it will be fetched fromfilename using gluoncontenttype module

bull encoding ndash encoding of all strings passed to this function (except attachment body)

Content ID is used to identify attachments within the html body in example attached image with contentID lsquophotorsquo may be used in html message as a source of img tag ltimg src=rdquocidphotordquo gt

Example Create attachment from text file

attachment = MailAttachment(pathtofiletxt)

Content-Type textplainMIME-Version 10Content-Disposition attachment filename=filetxtContent-Transfer-Encoding base64

SOMEBASE64CONTENT=

Create attachment from image file with custom filename and cid

attachment = MailAttachment(pathtofilepngfilename=photopngcontent_id=photo)

Content-Type imagepngMIME-Version 10Content-Disposition attachment filename=photopngContent-Id ltphotogtContent-Transfer-Encoding base64

SOMEOTHERBASE64CONTENT=

send(to subject=rsquo[no subject]rsquo message=rsquo[no message]rsquo attachments=None cc=None bcc=Nonereply_to=None sender=None encoding=rsquoutf-8rsquo raw=False headers= from_address=Nonecipher_type=None sign=None sign_passphrase=None encrypt=None x509_sign_keyfile=Nonex509_sign_chainfile=None x509_sign_certfile=None x509_crypt_certfiles=Nonex509_nocerts=None)

Sends an email using data specified in constructor

Parameters

bull to ndash list or tuple of receiver addresses will also accept single object

bull subject ndash subject of the email

bull message ndash email body text depends on type of passed object

341 Auth Mail PluginManager and various utilities 119

web2py Documentation Release 2146-stable

ndash if 2-list or 2-tuple is passed first element will be source of plain text while second ofhtml text

ndash otherwise object will be the only source of plain text and html source will be set toNone

If text or html source is

ndash None content part will be ignored

ndash string content part will be set to it

ndash file-like object content part will be fetched from it using itrsquos read() method

bull attachments ndash list or tuple of MailAttachment objects will also accept single object

bull cc ndash list or tuple of carbon copy receiver addresses will also accept single object

bull bcc ndash list or tuple of blind carbon copy receiver addresses will also accept single object

bull reply_to ndash address to which reply should be composed

bull encoding ndash encoding of all strings passed to this method (including message bodies)

bull headers ndash dictionary of headers to refine the headers just before sending mail eg lsquoX-Mailerrsquo lsquoweb2py mailerrsquo

bull from_address ndash address to appear in the lsquoFromrsquo header this is not the envelopesender If not specified the sender will be used

bull cipher_type ndash gpg - need a python-pyme package and gpgme lib x509 - smime

bull gpg_home ndash you can set a GNUPGHOME environment variable to specify home ofgnupg

bull sign ndash sign the message (True or False)

bull sign_passphrase ndash passphrase for key signing

bull encrypt ndash encrypt the message (True or False) It defaults to True x509 only

bull x509_sign_keyfile ndash the signers private key filename or string containing the key(PEM format)

bull x509_sign_certfile ndash the signers certificate filename or string containing the cert(PEM format)

bull x509_sign_chainfile ndash sets the optional all-in-one file where you can assemblethe certificates of Certification Authorities (CA) which form the certificate chain of emailcertificate It can be a string containing the certs to (PEM format)

bull x509_nocerts ndash if True then no attached certificate in mail

bull x509_crypt_certfiles ndash the certificates file or strings to encrypt the messages withcan be a file name string or a list of file names strings (PEM format)

Examples

Send plain text message to single address

mailsend(youexamplecomMessage subjectPlain text body of the message)

120 Chapter 34 tools Module

web2py Documentation Release 2146-stable

Send html message to single address

mailsend(youexamplecomMessage subjectlthtmlgtPlain text body of the messagelthtmlgt)

Send text and html message to three addresses (two in cc)

mailsend(youexamplecomMessage subject(Plain text body lthtmlgthtml bodylthtmlgt)cc=[other1examplecom other2examplecom])

Send html only message with image attachment available from the message by lsquophotorsquo content id

mailsend(youexamplecomMessage subject(None lthtmlgtltimg src=cidphoto gtlthtmlgt)MailAttachment(pathtophotojpg

content_id=photo))

Send email with two attachments and no body text

mailsend(youexamplecomMessage subjectNone[MailAttachment(pathtofistfile)MailAttachment(pathtosecondfile)])

Returns True on success False on failure

Before return method updates two objectrsquos fields

bull selfresult return value of smtplibSMTPsendmail() or GAErsquos mailsend_mail() method

bull selferror Exception message or None if above was successful

class gluontoolsAuth(environment=None db=None mailer=True hmac_key=None con-troller=rsquodefaultrsquo function=rsquouserrsquo cas_provider=None signature=Truesecure=False csrf_prevention=True propagate_extension=Noneurl_index=None jwt=None host_names=None)

Bases object

accessible_query(name table user_id=None)Returns a query with all accessible records for user_id or the current logged in user this method does notwork on GAE because uses JOIN and IN

Example

Use as

db(authaccessible_query(read dbmytable))select(dbmytableALL)

add_group(role description=rdquo)Creates a group associated to a role

add_membership(group_id=None user_id=None role=None)Gives user_id membership of group_id or role if user is None than user_id is that of current logged in user

341 Auth Mail PluginManager and various utilities 121

web2py Documentation Release 2146-stable

add_permission(group_id name=rsquoanyrsquo table_name=rdquo record_id=0)Gives group_id lsquonamersquo access to lsquotable_namersquo and lsquorecord_idrsquo

allows_jwt(otherwise=None)

static archive(form archive_table=None current_record=rsquocurrent_recordrsquoarchive_current=False fields=None)

If you have a table (dbmytable) that needs full revision history you can just do

form = crudupdate(dbmytable myrecord onaccept=autharchive)

or

form = SQLFORM(dbmytable myrecord)process(onaccept=autharchive)

crudarchive will define a new table ldquomytable_archiverdquo and store a copy of the current record (ifarchive_current=True) or a copy of the previous record (if archive_current=False) in the newly createdtable including a reference to the current record

fields allows to specify extra fields that need to be archived

If you want to access such table you need to define it yourself in a model

dbdefine_table(mytable_archiveField(current_record dbmytable)dbmytable)

Notice such table includes all fields of dbmytable plus one current_record crudarchive does not times-tamp the stored record unless your original table has a fields like

dbdefine_table(Field(saved_on datetime

default=requestnow update=requestnow writable=False)Field(saved_by authuser

default=authuser_id update=authuser_id writable=False)

there is nothing special about these fields since they are filled before the record is archived

If you want to change the archive table name and the name of the reference field you can do for example

dbdefine_table(myhistoryField(parent_record dbmytable) dbmytable)

and use it as

form = crudupdate(dbmytable myrecordonaccept=lambda formcrudarchive(form

archive_table=dbrarr˓myhistory

current_record=parent_rarr˓record))

basic(basic_auth_realm=False)Performs basic login

Parameters basic_auth_realm ndash optional basic http authentication realm Can take str orunicode or function or callable or boolean

reads currentrequestenvhttp_authorization and returns basic_allowedbasic_accepteduser

122 Chapter 34 tools Module

web2py Documentation Release 2146-stable

if basic_auth_realm is defined is a callable itrsquos return value is used to set the basic authentication realm ifitrsquos a string its content is used instead Otherwise basic authentication realm is set to the application nameIf basic_auth_realm is None or False (the default) the behavior is to skip sending any challenge

bulk_register(max_emails=100)Creates a form for ther user to send invites to other users to join

cas_login(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt version=2)

cas_validate(version=2 proxy=False)

change_password(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form that lets the user change password

confirm_registration(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form to confirm user registration

default_messages = access_denied Insufficient privileges add_group_log Group (group_id)s created add_membership_log None add_permission_log None bulk_invite_body You have been invited to join (site)s click (link)s to complete the process bulk_invite_subject Invitation to join (site)s change_password_log User (id)s Password changed del_group_log Group (group_id)s deleted del_membership_log None del_permission_log None delete_label Check to delete email_sent Email sent email_taken This email already has an account email_verified Email verified function_disabled Function disabled group_description Group uniquely assigned to user (id)s has_membership_log None has_permission_log None impersonate_log User (id)s is impersonating (other_id)s invalid_email Invalid email invalid_login Invalid login invalid_password Invalid password invalid_reset_password Invalid reset password invalid_two_factor_code Incorrect code 0 more attempt(s) remaining invalid_user Invalid user invalid_username Invalid username is_empty Cannot be empty label_client_ip Client IP label_description Description label_email E-mail label_first_name First name label_group_id Group ID label_last_name Last name label_name Name label_origin Origin label_password Password label_record_id Record ID label_registration_id Registration identifier label_registration_key Registration key label_remember_me Remember me (for 30 days) label_reset_password_key Reset Password key label_role Role label_table_name Object or table name label_time_stamp Timestamp label_two_factor Authentication code label_user_id User ID label_username Username logged_in Logged in logged_out Logged out login_button Log In login_disabled Login disabled by administrator login_failed_log None login_log User (id)s Logged-in logout_log User (id)s Logged-out mismatched_password Password fields dont match new_password New password new_password_sent A new password was emailed to you old_password Old password password_change_button Change password password_changed Password changed password_reset_button Request reset password profile_log User (id)s Profile updated profile_save_button Apply changes profile_updated Profile updated register_button Sign Up register_log User (id)s Registered registration_pending Registration is pending approval registration_successful Registration successful registration_verifying Registration needs verification reset_password Click on the link (link)s to reset your password reset_password_log User (id)s Password reset reset_password_subject Password reset retrieve_password Your password is (password)s retrieve_password_log User (id)s Password retrieved retrieve_password_subject Password retrieve retrieve_two_factor_code Your temporary login code is 0 retrieve_two_factor_code_subject Two-step Login Authentication Code retrieve_username Your username is (username)s retrieve_username_log User (id)s Username retrieved retrieve_username_subject Username retrieve submit_button Submit two_factor_comment This code was emailed to you and is required for login unable_send_email Unable to send email unable_to_send_email Unable to send email username_sent Your username was emailed to you username_taken Username already taken verify_email Welcome (username)s Click on the link (link)s to verify your email verify_email_log User (id)s Verification email sent verify_email_subject Email verification verify_password Verify Password verify_password_comment please input your password againClass for authentication authorization role based access control

Includes

bull registration and profile

bull login and logout

bull username and password retrieval

bull event logging

bull role creation and assignment

bull user defined grouprole based permission

Parameters

bull environment ndash is there for legacy but unused (awful)

bull db ndash has to be the database where to create tables for authentication

bull mailer ndash Mail( ) or None (no mailer) or True (make a mailer)

bull hmac_key ndash can be a hmac_key or hmac_key=Authget_or_create_key()

bull controller ndash (where is the user action)

bull cas_provider ndash (delegate authentication to the URL CAS2)

Authentication Example

from gluoncontributils import mail=Mail()mailsettingsserver=smtpgmailcom587mailsettingssender=yousomewherecommailsettingslogin=usernamepasswordauth=Auth(db)authsettingsmailer=mail authsettings=authdefine_tables()def authentication()

return dict(form=auth())

341 Auth Mail PluginManager and various utilities 123

web2py Documentation Release 2146-stable

Exposes

bull http applicationcontrollerauthenticationlogin

bull http applicationcontrollerauthenticationlogout

bull http applicationcontrollerauthenticationregister

bull http applicationcontrollerauthenticationverify_email

bull http applicationcontrollerauthenticationretrieve_username

bull http applicationcontrollerauthenticationretrieve_password

bull http applicationcontrollerauthenticationreset_password

bull http applicationcontrollerauthenticationprofile

bull http applicationcontrollerauthenticationchange_password

On registration a group with role=new_userid is created and user is given membership of this group

You can create a group with

group_id=authadd_group(Manager can access the manage action)authadd_permission(group_id access to manage)

Here ldquoaccess to managerdquo is just a user defined string You can give access to a user

authadd_membership(group_id user_id)

If user id is omitted the logged in user is assumed

Then you can decorate any action

authrequires_permission(access to manage)def manage()

return dict()

You can restrict a permission to a specific table

authadd_permission(group_id edit dbsometable)authrequires_permission(edit dbsometable)

Or to a specific record

authadd_permission(group_id edit dbsometable 45)authrequires_permission(edit dbsometable 45)

If authorization is not granted calls

authsettingson_failed_authorization

Other options

authsettingsmailer=Noneauthsettingsexpiration=3600 seconds

these are messages that can be customized

124 Chapter 34 tools Module

web2py Documentation Release 2146-stable

default_settings = allow_basic_login False allow_basic_login_only False allow_delete_accounts False alternate_requires_registration False auth_manager_role None auth_two_factor_enabled False auth_two_factor_tries_left 3 bulk_register_enabled False captcha None cas_maps None client_side True create_user_groups user_(id)s email_case_sensitive True everybody_group_id None expiration 3600 formstyle None hideerror False keep_session_onlogin True keep_session_onlogout False label_separator None logging_enabled True login_after_password_change True login_after_registration False login_captcha None login_email_validate True login_userfield None logout_onlogout None long_expiration 2592000 manager_actions multi_login False on_failed_authentication ltfunction ltlambdagt at 0x7fcf0cf9f578gt ondelete CASCADE password_field password password_min_length 4 pre_registration_div None prevent_open_redirect_attacks True prevent_password_reset_attacks True profile_fields None register_captcha None register_fields None register_verify_password True registration_requires_approval False registration_requires_verification False remember_me_form True renew_session_onlogin True renew_session_onlogout True reset_password_requires_verification False retrieve_password_captcha None retrieve_username_captcha None showid False table_cas None table_cas_name auth_cas table_event None table_event_name auth_event table_group None table_group_name auth_group table_membership None table_membership_name auth_membership table_permission None table_permission_name auth_permission table_token_name auth_token table_user None table_user_name auth_user two_factor_authentication_group None update_fields [email] use_username False username_case_sensitive True wiki ltStorage gt

define_signature()

define_tables(username=None signature=None enable_tokens=False migrate=Nonefake_migrate=None)

To be called unless tables are defined manually

Examples

Use as

defines all needed tables and table files myprefix_auth_usertable authdefine_tables(migrate=myprefix_)

defines all needed tables without migrationtable filesauthdefine_tables(migrate=False)

del_group(group_id)Deletes a group

del_membership(group_id=None user_id=None role=None)Revokes membership from group_id to user_id if user_id is None than user_id is that of current logged inuser

del_permission(group_id name=rsquoanyrsquo table_name=rdquo record_id=0)Revokes group_id lsquonamersquo access to lsquotable_namersquo and lsquorecord_idrsquo

email_registration(subject body user)Sends and email invitation to a user informing they have been registered with the application

email_reset_password(user)

enable_record_versioning(tables archive_db=None archive_names=rsquo(tablename)s_archiversquocurrent_record=rsquocurrent_recordrsquo current_record_label=None)

Used to enable full record versioning (including auth tables)

auth = Auth(db)authdefine_tables(signature=True) define our own tablesdbdefine_table(mythingField(name)authsignature)authenable_record_versioning(tables=db)

tables can be the db (all table) or a list of tables only tables with modified_by and modified_on fiels (ascreated by authsignature) will have versioning Old record versions will be in table lsquomything_archiversquoautomatically defined

when you enable enable_record_versioning records are never deleted but marked with is_active=False

enable_record_versioning enables a common_filter for every table that filters out records with is_active =False

Note If you use authenable_record_versioning do not use autharchive or you will end up with dupli-cates autharchive does explicitly what enable_record_versioning does automatically

static get_or_create_key(filename=None alg=rsquosha512rsquo)

341 Auth Mail PluginManager and various utilities 125

web2py Documentation Release 2146-stable

get_or_create_user(keys update_fields=[rsquoemailrsquo] login=True get=True)Used for alternate login methods If the user exists already then password is updated If the user doesnrsquotyet exist then they are created

get_vars_next()

groups()Displays the groups and their roles for the logged in user

has_membership(group_id=None user_id=None role=None)Checks if user is member of group_id or role

has_permission(name=rsquoanyrsquo table_name=rdquo record_id=0 user_id=None group_id=None)Checks if user_id or current logged in user is member of a group that has lsquonamersquo permission on lsquota-ble_namersquo and lsquorecord_idrsquo if group_id is passed it checks whether the group has the permission

here()

id_group(role)Returns the group_id of the group specified by the role

impersonate(user_id=ltfunction ltlambdagtgt)To use this make a POST to http impersonate requestpost_varsuser_id=ltidgt

Set requestpost_varsuser_id to 0 to restore original user

requires impersonator is logged in and

has_permission(impersonate auth_user user_id)

is_impersonating()

is_logged_in()Checks if the user is logged in and returns TrueFalse If so user is in authuser as well as in ses-sionauthuser

jwt()To use JWT authentication 1) instantiate auth with

auth = Auth(db jwt = secret_keysecret)

where lsquosecretrsquo is your own secret string

2 Decorate functions that require login but should accept the JWT token credentials

authallows_jwt()authrequires_login()def myapi() return hello s authuseremail

Notice jwt is allowed but not required if user is logged in myapi is accessible

3 Use it

Now API users can obtain a token with

http appdefaultuserjwtusername= amppassword=

(returns json object with a token attribute) API users can refresh an existing token with

http appdefaultuserjwttoken=

they can authenticate themselves when calling http myapi by injecting a header

Authorization Bearer ltthe jwt tokengt

126 Chapter 34 tools Module

web2py Documentation Release 2146-stable

Any additional attributes in the jwt argument of Auth() below

auth = Auth(db jwt = )

are passed to the constructor of class AuthJWT Look there for documentation

log_event(description vars=None origin=rsquoauthrsquo)

Examples

Use as

authlog_event(description=this happened origin=auth)

login(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a login form

login_bare(username password)Logins user as specified by username (or email) and password

login_user(user)Logins the user = dbauth_user(id)

logout(next=ltfunction ltlambdagtgt onlogout=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)Logouts and redirects to login

logout_bare()

manage_tokens()

navbar(prefix=rsquoWelcomersquo action=None separators=(rsquo [ rsquo rsquo | rsquo rsquo ] rsquo) user_identifier=ltfunctionltlambdagtgt referrer_actions=ltfunction ltlambdagtgt mode=rsquodefaultrsquo)

Navbar with support for more templates This uses some code from the old navbar

Parameters mode ndash see options for list of

not_authorized()You can change the view for this page to make it look as you like

profile(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form that lets the user change hisher profile

random_password()

register(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a registration form

register_bare(fields)Registers a user as specified by username (or email) and a raw password

request_reset_password(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgtonaccept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form to reset the user password

requires(condition requires_login=True otherwise=None)Decorator that prevents access to action if not logged in

requires_login(otherwise=None)Decorator that prevents access to action if not logged in

341 Auth Mail PluginManager and various utilities 127

web2py Documentation Release 2146-stable

requires_login_or_token(otherwise=None)

requires_membership(role=None group_id=None otherwise=None)Decorator that prevents access to action if not logged in or if user logged in is not a member of group_idIf role is provided instead of group_id then the group_id is calculated

requires_permission(name table_name=rdquo record_id=0 otherwise=None)Decorator that prevents access to action if not logged in or if user logged in is not a member of any group(role) that has lsquonamersquo access to lsquotable_namersquo lsquorecord_idrsquo

requires_signature(otherwise=None hash_vars=True)Decorator that prevents access to action if not logged in or if user logged in is not a member of group_idIf role is provided instead of group_id then the group_id is calculated

reset_password(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form to reset the user password

reset_password_deprecated(next=ltfunction ltlambdagtgt onvalidation=ltfunctionltlambdagtgt onaccept=ltfunction ltlambdagtgt log=ltfunctionltlambdagtgt)

Returns a form to reset the user password (deprecated)

retrieve_password(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

retrieve_username(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form to retrieve the user username (only if there is a username field)

run_login_onaccept()

select_host(host host_names=None)checks that host is valid ie in the list of glob host_names if the host is missing then is it selects the firstentry from host_names read more here httpsgithubcomweb2pyweb2pyissues1196

table_cas()

table_event()

table_group()

table_membership()

table_permission()

table_token()

table_user()

update_groups()

url(f=None args=None vars=None scheme=False)

user_group(user_id=None)Returns the group_id of the group uniquely associated to this user ie role=user[user_id]

user_group_role(user_id=None)

user_iduserid or None

verify_email(next=ltfunction ltlambdagtgt onaccept=ltfunction ltlambdagtgt log=ltfunctionltlambdagtgt)

Action used to verify the registration email

128 Chapter 34 tools Module

web2py Documentation Release 2146-stable

when_is_logged_in_bypass_next_in_url(next session)This function should be use when someone want to avoid asking for user credentials when loaded pagecontains ldquouserlogin_next=NEXT_COMPONENTrdquo in the URL is refresh but user is already authenti-cated

wiki(slug=None env=None render=rsquomarkminrsquo manage_permissions=False force_prefix=rdquo re-strict_search=False resolve=True extra=None menu_groups=None templates=None mi-grate=True controller=None function=None force_render=False groups=None)

wikimenu()To be used in menupy for app wide wiki menus

class gluontoolsRecaptcha(request=None public_key=rdquo private_key=rdquo use_ssl=False er-ror=None error_message=rsquoinvalidrsquo label=rsquoVerifyrsquo options=rdquocomment=rdquo ajax=False)

Bases gluonhtmlDIV

Examples

Use as

form = FORM(Recaptcha(public_key= private_key=))

or

form = SQLFORM()formappend(Recaptcha(public_key= private_key=))

API_SERVER = httpwwwgooglecomrecaptchaapi

API_SSL_SERVER = httpswwwgooglecomrecaptchaapi

VERIFY_SERVER = httpwwwgooglecomrecaptchaapiverify

xml()generates the xml for this component

class gluontoolsRecaptcha2(request=None public_key=rdquo private_key=rdquo er-ror_message=rsquoinvalidrsquo label=rsquoVerifyrsquo options=None com-ment=rdquo)

Bases gluonhtmlDIV

Experimental Creates a DIV holding the newer Recaptcha from Google (v2)

Parameters

bull request ndash the request If not passed uses current request

bull public_key ndash the public key Google gave you

bull private_key ndash the private key Google gave you

bull error_message ndash the error message to show if verification fails

bull label ndash the label to use

bull options (dict) ndash takes these parameters

ndash hl

ndash theme

ndash type

341 Auth Mail PluginManager and various utilities 129

web2py Documentation Release 2146-stable

ndash tabindex

ndash callback

ndash expired-callback

see httpsdevelopersgooglecomrecaptchadocsdisplay for docs about those

bull comment ndash the comment

Examples

Use as

form = FORM(Recaptcha2(public_key= private_key=))

or

form = SQLFORM()formappend(Recaptcha2(public_key= private_key=))

to protect the login page instead use

from gluontools import Recaptcha2authsettingscaptcha = Recaptcha2(request public_key= private_key=)

API_URI = httpswwwgooglecomrecaptchaapijs

VERIFY_SERVER = httpswwwgooglecomrecaptchaapisiteverify

xml()generates the xml for this component

class gluontoolsCrud(environment db=None controller=rsquodefaultrsquo)Bases object

static archive(form archive_table=None current_record=rsquocurrent_recordrsquo)

create(table next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt message=ltfunction ltlambdagtgt form-name=ltfunction ltlambdagtgt attributes)

delete(table record_id next=ltfunction ltlambdagtgt message=ltfunction ltlambdagtgt)

get_format(field)

get_query(field op value refsearch=False)

has_permission(name table record=0)

log_event(message vars)

read(table record)

rows(table query=None fields=None orderby=None limitby=None)

search(tables args)Creates a search form and its results for a table rubric Examples

Use as

130 Chapter 34 tools Module

web2py Documentation Release 2146-stable

form results = crudsearch(dbtestqueries = [equals not equal contains]query_labels=equalsEquals

not equalNot equalfields = [idchildren]field_labels =

idIDchildrenChildrenzero=Please choosequery = (dbtestid gt 0)amp(dbtestid = 3) )

select(table query=None fields=None orderby=None limitby=None headers=None attr)

tables()

update(table record next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt ondelete=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgtmessage=ltfunction ltlambdagtgt deletable=ltfunction ltlambdagtgt formname=ltfunctionltlambdagtgt attributes)

url(f=None args=None vars=None)This should point to the controller that exposes download and crud

class gluontoolsService(environment=None)Bases object

exception JsonRpcException(code info)Bases exceptionsException

amfrpc(f)

Example

Use as

service = Service()serviceamfrpcdef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget httpappdefaultcallamfrpcmyfunctiona=helloampb=world

amfrpc3(domain=rsquodefaultrsquo)

Example

Use as

service = Service()serviceamfrpc3(domain)def myfunction(a b)

return a + bdef call()

return service()

341 Auth Mail PluginManager and various utilities 131

web2py Documentation Release 2146-stable

Then call it with

wget http appdefaultcallamfrpc3myfunctiona=helloampb=world

csv(f)

Example

Use as

service = Service()servicecsvdef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget httpappdefaultcallcsvmyfunctiona=3ampb=4

error()

json(f)

Example

Use as

service = Service()servicejsondef myfunction(a b)

return [a b]def call()

return service()

Then call it with

wget http appdefaultcalljsonmyfunctiona=helloampb=world

jsonrpc(f)

Example

Use as

service = Service()servicejsonrpcdef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget http appdefaultcalljsonrpcmyfunctiona=helloampb=world

132 Chapter 34 tools Module

web2py Documentation Release 2146-stable

jsonrpc2(f)

Example

Use as

service = Service()servicejsonrpc2def myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget ndashpost-data lsquoldquojsonrpcrdquo ldquo20rdquo ldquoidrdquo 1 ldquomethodrdquo ldquomyfunctionrdquo ldquoparamsrdquo ldquoardquo 1 ldquobrdquo2rsquo http appdefaultcalljsonrpc2

jsonrpc_errors = -32700 (Parse error Invalid JSON was received by the server An error occurred on the server while parsing the JSON text) -32603 (Internal error Internal JSON-RPC error) -32602 (Invalid params Invalid method parameter(s)) -32601 (Method not found The method does not exist is not available) -32600 (Invalid Request The JSON sent is not a valid Request object) -32099 (Server error Reserved for implementation-defined server-errors)

rss(f)

Example

Use as

service = Service()servicerssdef myfunction()

return dict(title= link= description=created_on= entries=[dict(title= link=

description= created_on=])def call()

return service()

Then call it with

wget http appdefaultcallrssmyfunction

run(f)

Example

Use as

service = Service()servicerundef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget httpappdefaultcallrunmyfunctiona=3ampb=4

341 Auth Mail PluginManager and various utilities 133

web2py Documentation Release 2146-stable

serve_amfrpc(version=0)

serve_csv(args=None)

serve_json(args=None)

serve_jsonrpc()

serve_jsonrpc2(data=None batch_element=False)

serve_rss(args=None)

serve_run(args=None)

serve_soap(version=rsquo11rsquo)

serve_xml(args=None)

serve_xmlrpc()

soap(name=None returns=None args=None doc=None)

Example

Use as

service = Service()servicesoap(MyFunctionreturns=resultintargs=aintbint)def myfunction(a b)

return a + bdef call()

return service()

Then call it with

from gluoncontribpysimplesoapclient import SoapClientclient = SoapClient(wsdl=httpappdefaultcallsoapWSDL)response = clientMyFunction(a=1b=2)return response[result]

It also exposes online generated documentation and xml example messages athttp appdefaultcallsoap

xml(f)

Example

Use as

service = Service()servicexmldef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget httpappdefaultcallxmlmyfunctiona=3ampb=4

134 Chapter 34 tools Module

web2py Documentation Release 2146-stable

xmlrpc(f)

Example

Use as

service = Service()servicexmlrpcdef myfunction(a b)

return a + bdef call()

return service()

The call it with

wget http appdefaultcallxmlrpcmyfunctiona=helloampb=world

class gluontoolsWiki(auth env=None render=rsquomarkminrsquo manage_permissions=Falseforce_prefix=rdquo restrict_search=False extra=None menu_groups=Nonetemplates=None migrate=True controller=None function=Nonegroups=None)

Bases object

automenu()adds the menu if not present

can_edit(page=None)

can_manage()

can_read(page)

can_search()

can_see_menu()

cloud()

static component(text)In wiki docs allows componentcontrollerfunctionargs which renders as a LOAD( ajax=True)

create()

edit(slug from_template=0)

editmedia(slug)

everybody = everybody

first_paragraph(page)

fix_hostname(body)

get_renderer()

html_render(page)

markmin_base(body)

markmin_render(page)

media(id)

menu(controller=rsquodefaultrsquo function=rsquoindexrsquo)

341 Auth Mail PluginManager and various utilities 135

web2py Documentation Release 2146-stable

not_authorized(page=None)

pages()

preview(render)

read(slug force_render=False)

render_tags(tags)

rows_page = 25

search(tags=None query=None cloud=True preview=True limitby=(0 100) orderby=None)

class gluontoolsPluginManager(plugin=None defaults)Bases object

Plugin Manager is similar to a storage object but it is a single level singleton This means that multiple instanceswithin the same thread share the same attributes Its constructor is also special The first argument is the nameof the plugin you are defining The named arguments are parameters needed by the plugin with default valuesIf the parameters were previous defined the old values are used

Example

in some general configuration file

plugins = PluginManager()pluginsmeparam1=3

within the plugin model

_ = PluginManager(meparam1=5param2=6param3=7)

where the plugin is used

gtgtgt print pluginsmeparam13gtgtgt print pluginsmeparam26gtgtgt pluginsmeparam3 = 8gtgtgt print pluginsmeparam38

Here are some tests

gtgtgt a=PluginManager()gtgtgt ax=6gtgtgt b=PluginManager(check)gtgtgt print bx6gtgtgt b=PluginManager() reset settingsgtgtgt print bxltStorage gtgtgtgt bx=7gtgtgt print ax7gtgtgt ayz=8gtgtgt print byz8

(continues on next page)

136 Chapter 34 tools Module

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt test_thread_separation()5gtgtgt plugins=PluginManager(medb=mydb)gtgtgt print pluginsmedbmydbgtgtgt print me in pluginsTruegtgtgt print pluginsmeinstalledTrue

instances =

keys()

gluontoolsfetch(url data=None headers=None cookie= user_agent=rsquoMozilla50rsquo)

gluontoolsgeocode(address)

gluontoolsreverse_geocode(lat lng lang=None)Try to get an approximate address for a given latitude longitude

gluontoolsprettydate(d T=ltfunction ltlambdagtgt utc=False)

341 Auth Mail PluginManager and various utilities 137

web2py Documentation Release 2146-stable

138 Chapter 34 tools Module

CHAPTER 35

utf8 Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)Created by Vladyslav Kozlovskyy (Ukraine) ltdbdevelopcopygmailcomgtfor Web2py project

351 Utilities and class for UTF8 strings managing

class gluonutf8Utf8Bases str

Class for utf8 string storing and manipulations

The base presupposition of this class usage is ldquoALL strings in the application are either of utf-8 or unicodetype even when simple str type is used UTF-8 is only a ldquopackedrdquo version of unicode so Utf-8 and unicodestrings are interchangeablerdquo

CAUTION This class is slower than strunicode Do NOT use it inside intensive loops Simply decode string(s)to unicode before loop and encode it back to utf-8 string(s) after intensive calculation

You can see the benefit of this class in doctests() below

capitalize()rarr stringReturn a copy of the string S with only its first character capitalized

center(width[ fillchar ])rarr stringReturn S centered in a string of length width Padding is done using the specified fill character (default isa space)

count(sub[ start[ end ]])rarr intReturn the number of non-overlapping occurrences of substring sub in string S[startend] Optional argu-ments start and end are interpreted as in slice notation

139

web2py Documentation Release 2146-stable

decode([encoding[ errors]])rarr objectDecodes S using the codec registered for encoding encoding defaults to the default encoding errors maybe given to set a different error handling scheme Default is lsquostrictrsquo meaning that encoding errors raise aUnicodeDecodeError Other possible values are lsquoignorersquo and lsquoreplacersquo as well as any other name registeredwith codecsregister_error that is able to handle UnicodeDecodeErrors

encode([encoding[ errors]])rarr objectEncodes S using the codec registered for encoding encoding defaults to the default encoding errors maybe given to set a different error handling scheme Default is lsquostrictrsquo meaning that encoding errors raise aUnicodeEncodeError Other possible values are lsquoignorersquo lsquoreplacersquo and lsquoxmlcharrefreplacersquo as well as anyother name registered with codecsregister_error that is able to handle UnicodeEncodeErrors

endswith(suffix[ start[ end ]])rarr boolReturn True if S ends with the specified suffix False otherwise With optional start test S beginning atthat position With optional end stop comparing S at that position suffix can also be a tuple of strings totry

expandtabs([tabsize])rarr stringReturn a copy of S where all tab characters are expanded using spaces If tabsize is not given a tab size of8 characters is assumed

find(sub[ start[ end ]])rarr intReturn the lowest index in S where substring sub is found such that sub is contained within S[startend]Optional arguments start and end are interpreted as in slice notation

Return -1 on failure

format(args kwargs)rarr stringReturn a formatted version of S using substitutions from args and kwargs The substitutions are identifiedby braces (lsquolsquo and lsquorsquo)

index(sub[ start[ end ]])rarr intLike Sfind() but raise ValueError when the substring is not found

isalnum()rarr boolReturn True if all characters in S are alphanumeric and there is at least one character in S False otherwise

isalpha()rarr boolReturn True if all characters in S are alphabetic and there is at least one character in S False otherwise

isdigit()rarr boolReturn True if all characters in S are digits and there is at least one character in S False otherwise

islower()rarr boolReturn True if all cased characters in S are lowercase and there is at least one cased character in S Falseotherwise

isspace()rarr boolReturn True if all characters in S are whitespace and there is at least one character in S False otherwise

istitle()rarr boolReturn True if S is a titlecased string and there is at least one character in S ie uppercase characters mayonly follow uncased characters and lowercase characters only cased ones Return False otherwise

isupper()rarr boolReturn True if all cased characters in S are uppercase and there is at least one cased character in S Falseotherwise

join(iterable)rarr stringReturn a string which is the concatenation of the strings in the iterable The separator between elements isS

140 Chapter 35 utf8 Module

web2py Documentation Release 2146-stable

ljust(width[ fillchar ])rarr stringReturn S left-justified in a string of length width Padding is done using the specified fill character (defaultis a space)

lower()rarr stringReturn a copy of the string S converted to lowercase

lstrip([chars])rarr string or unicodeReturn a copy of the string S with leading whitespace removed If chars is given and not None removecharacters in chars instead If chars is unicode S will be converted to unicode before stripping

partition(sep) -gt (head sep tail)Search for the separator sep in S and return the part before it the separator itself and the part after it Ifthe separator is not found return S and two empty strings

replace(old new[ count ])rarr stringReturn a copy of string S with all occurrences of substring old replaced by new If the optional argumentcount is given only the first count occurrences are replaced

rfind(sub[ start[ end ]])rarr intReturn the highest index in S where substring sub is found such that sub is contained within S[startend]Optional arguments start and end are interpreted as in slice notation

Return -1 on failure

rindex(sub[ start[ end ]])rarr intLike Srfind() but raise ValueError when the substring is not found

rjust(width[ fillchar ])rarr stringReturn S right-justified in a string of length width Padding is done using the specified fill character (defaultis a space)

rpartition(sep) -gt (head sep tail)Search for the separator sep in S starting at the end of S and return the part before it the separator itselfand the part after it If the separator is not found return two empty strings and S

rsplit([sep[ maxsplit ]])rarr list of stringsReturn a list of the words in the string S using sep as the delimiter string starting at the end of the stringand working to the front If maxsplit is given at most maxsplit splits are done If sep is not specified or isNone any whitespace string is a separator

rstrip([chars])rarr string or unicodeReturn a copy of the string S with trailing whitespace removed If chars is given and not None removecharacters in chars instead If chars is unicode S will be converted to unicode before stripping

split([sep[ maxsplit ]])rarr list of stringsReturn a list of the words in the string S using sep as the delimiter string If maxsplit is given at mostmaxsplit splits are done If sep is not specified or is None any whitespace string is a separator and emptystrings are removed from the result

splitlines(keepends=False)rarr list of stringsReturn a list of the lines in S breaking at line boundaries Line breaks are not included in the resulting listunless keepends is given and true

startswith(prefix[ start[ end ]])rarr boolReturn True if S starts with the specified prefix False otherwise With optional start test S beginning atthat position With optional end stop comparing S at that position prefix can also be a tuple of strings totry

strip([chars])rarr string or unicodeReturn a copy of the string S with leading and trailing whitespace removed If chars is given and not None

351 Utilities and class for UTF8 strings managing 141

web2py Documentation Release 2146-stable

remove characters in chars instead If chars is unicode S will be converted to unicode before stripping

swapcase()rarr stringReturn a copy of the string S with uppercase characters converted to lowercase and vice versa

title()rarr stringReturn a titlecased version of S ie words start with uppercase characters all remaining cased charactershave lowercase

translate(table[ deletechars])rarr stringReturn a copy of the string S where all characters occurring in the optional argument deletechars areremoved and the remaining characters have been mapped through the given translation table which mustbe a string of length 256 or None If the table argument is None no translation is applied and the operationsimply removes the characters in deletechars

upper()rarr stringReturn a copy of the string S converted to uppercase

zfill(width)rarr stringPad a numeric string S with zeros on the left to fill a field of the specified width The string S is nevertruncated

142 Chapter 35 utf8 Module

CHAPTER 36

utils Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

361 This file specifically includes utilities for security

gluonutilsAES_new(key IV=None)Returns an AES cipher object and random IV if None specified

gluonutilscompare(a b)Compares two strings and not vulnerable to timing attacks

gluonutilsfast_urandom16(urandom=[] locker=lt_RLock owner=None count=0gt)This is 4x faster than calling osurandom(16) and prevents the ldquotoo many files openrdquo issue with concurrent accessto osurandom()

gluonutilsget_callable_argspec(fn)

gluonutilsget_digest(value)Returns a hashlib digest algorithm from a string

gluonutilsgetipaddrinfo(host)Filter out non-IP and bad IP addresses from getaddrinfo

gluonutilsinitialize_urandom()This function and the web2py_uuid follow from the following discussionhttpgroupsgooglecomgroupweb2py-developersbrowse_threadthread7fd5789a7da3f09

At startup web2py compute a unique ID that identifies the machine by adding uuidgetnode() + int(timetime() 1e3)

This is a 48-bit number It converts the number into 16 8-bit tokens It uses this value to initialize the entropysource (lsquodevurandomrsquo) and to seed random

143

web2py Documentation Release 2146-stable

If osrandom() is not supported it falls back to using random and issues a warning

gluonutilsis_loopback_ip_address(ip=None addrinfo=None)Determines whether the address appears to be a loopback address This assumes that the IP is valid

gluonutilsis_valid_ip_address(address)

Examples

Better than a thousand words

gtgtgt is_valid_ip_address(1270)Falsegtgtgt is_valid_ip_address(127001)Truegtgtgt is_valid_ip_address(20016601)True

gluonutilsmd5_hash(text)Generates a md5 hash with the given text

gluonutilspad(s n=32 padchar=rsquo rsquo)

gluonutilspbkdf2_hex(data salt iterations=1000 keylen=24 hashfunc=None)

gluonutilssecure_dumps(data encryption_key hash_key=None compression_level=None)

gluonutilssecure_loads(data encryption_key hash_key=None compression_level=None)

gluonutilssimple_hash(text key=rdquo salt=rdquo digest_alg=rsquomd5rsquo)Generates hash with the given text using the specified digest hashing algorithm

gluonutilsweb2py_uuid(ctokens=(12807810588179607998L 787762416516532974))This function follows from the following discussion httpgroupsgooglecomgroupweb2py-developersbrowse_threadthread7fd5789a7da3f09

It works like uuiduuid4 except that tries to use osurandom() if possible and it XORs the output with the tokensuniquely associated with this machine

144 Chapter 36 utils Module

CHAPTER 37

validators Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)Thanks to ga2arch for help with IS_IN_DB and IS_NOT_IN_DB on GAE

371 Validators

class gluonvalidatorsANY_OF(subs)Bases gluonvalidatorsValidator

Tests if any of the validators in a list returns successfully

gtgtgt ANY_OF([IS_EMAIL()IS_ALPHANUMERIC()])(abco)(abco None)gtgtgt ANY_OF([IS_EMAIL()IS_ALPHANUMERIC()])(abco)(abco None)gtgtgt ANY_OF([IS_EMAIL()IS_ALPHANUMERIC()])(abco)(abco enter only letters numbers and underscore)gtgtgt ANY_OF([IS_ALPHANUMERIC()IS_EMAIL()])(abco)(abco enter a valid email address)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

class gluonvalidatorsCLEANUP(regex=None)Bases gluonvalidatorsValidator

Examples

Use as

145

web2py Documentation Release 2146-stable

INPUT(_type=text _name=name requires=CLEANUP())

removes special characters on validation

REGEX_CLEANUP = lt_sreSRE_Pattern objectgt

class gluonvalidatorsCRYPT(key=None digest_alg=rsquopbkdf2(1000 20 sha512)rsquo min_length=0error_message=rsquoToo shortrsquo salt=True max_length=1024)

Bases object

Examples

Use as

INPUT(_type=text _name=name requires=CRYPT())

encodes the value on validation with a digest

If no arguments are provided CRYPT uses the MD5 algorithm If the key argument is provided the HMAC+MD5algorithm is used If the digest_alg is specified this is used to replace the MD5 with for example SHA512 Thedigest_alg can be the name of a hashlib algorithm as a string or the algorithm itself

min_length is the minimal password length (default 4) - IS_STRONG for serious security error_message is themessage if password is too short

Notice that an empty password is accepted but invalid It will not allow login back Stores junk as hashedpassword

Specify an algorithm or by default we will use sha512

Typical available algorithms md5 sha1 sha224 sha256 sha384 sha512

If salt it hashes a password with a salt If salt is True this method will automatically generate one Either caseit returns an encrypted password string in the following format

ltalgorithmgt$ltsaltgt$lthashgt

Important hashed password is returned as a LazyCrypt object and computed only if needed The LasyCryptobject also knows how to compare itself with an existing salted password

Supports standard algorithms

gtgtgt for alg in (md5sha1sha256sha384sha512) print str(CRYPT(digest_alg=algsalt=True)(test)[0])md5$$sha1$$sha256$$sha384$$sha512$$

The syntax is always alg$salt$hash

Supports for pbkdf2

gtgtgt alg = pbkdf2(100020sha512)gtgtgt print str(CRYPT(digest_alg=algsalt=True)(test)[0])pbkdf2(100020sha512)$$

An optional hmac_key can be specified and it is used as salt prefix

146 Chapter 37 validators Module

web2py Documentation Release 2146-stable

gtgtgt a = str(CRYPT(digest_alg=md5key=mykeysalt=True)(test)[0])gtgtgt print amd5$$

Even if the algorithm changes the hash can still be validated

gtgtgt CRYPT(digest_alg=sha1key=mykeysalt=True)(test)[0] == aTrue

If no salt is specified CRYPT can guess the algorithms from length

gtgtgt a = str(CRYPT(digest_alg=sha1salt=False)(test)[0])gtgtgt asha1$$a94a8fe5ccb19ba61c4c0873d391e987982fbbd3gtgtgt CRYPT(digest_alg=sha1salt=False)(test)[0] == aTruegtgtgt CRYPT(digest_alg=sha1salt=False)(test)[0] == a[6]Truegtgtgt CRYPT(digest_alg=md5salt=False)(test)[0] == aTruegtgtgt CRYPT(digest_alg=md5salt=False)(test)[0] == a[6]True

class gluonvalidatorsIS_ALPHANUMERIC(error_message=rsquoEnter only letters numbers andunderscorersquo)

Bases gluonvalidatorsIS_MATCH

Example

Used as

INPUT(_type=text _name=name requires=IS_ALPHANUMERIC())

gtgtgt IS_ALPHANUMERIC()(1)(1 None)gtgtgt IS_ALPHANUMERIC()()( None)gtgtgt IS_ALPHANUMERIC()(A_a)(A_a None)gtgtgt IS_ALPHANUMERIC()()( enter only letters numbers and underscore)

class gluonvalidatorsIS_DATE_IN_RANGE(minimum=None maximum=None format=rsquoY-m-drsquo error_message=None)

Bases gluonvalidatorsIS_DATE

Examples

Use as

gtgtgt v = IS_DATE_IN_RANGE(minimum=datetimedate(200811)rarr˓ maximum=datetimedate(20091231)rarr˓ format=mdYerror_message=Oops)

(continues on next page)

371 Validators 147

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt v(03032008)(datetimedate(2008 3 3) None)

gtgtgt v(03032010)(03032010 oops)

gtgtgt v(datetimedate(200833))(datetimedate(2008 3 3) None)

gtgtgt v(datetimedate(201033))(datetimedate(2010 3 3) oops)

class gluonvalidatorsIS_DATE(format=rsquoY-m-drsquo error_message=rsquoEnter date as (for-mat)srsquo)

Bases gluonvalidatorsValidator

Examples

Use as

INPUT(_type=text _name=name requires=IS_DATE())

date has to be in the ISO8960 format YYYY-MM-DD

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

class gluonvalidatorsIS_DATETIME_IN_RANGE(minimum=None maximum=Noneformat=rsquoY-m-d HMSrsquo er-ror_message=None timezone=None)

Bases gluonvalidatorsIS_DATETIME

Examples

Use as

gtgtgt v = IS_DATETIME_IN_RANGE( minimum=datetimerarr˓datetime(2008111220) maximum=datetimerarr˓datetime(200912311220) format=mdY HMrarr˓error_message=Oops)gtgtgt v(03032008 1240)(datetimedatetime(2008 3 3 12 40) None)

gtgtgt v(03032010 1034)(03032010 1034 oops)

gtgtgt v(datetimedatetime(20083300))(datetimedatetime(2008 3 3 0 0) None)

gtgtgt v(datetimedatetime(20103300))(datetimedatetime(2010 3 3 0 0) oops)

148 Chapter 37 validators Module

web2py Documentation Release 2146-stable

class gluonvalidatorsIS_DATETIME(format=rsquoY-m-d HMSrsquo er-ror_message=rsquoEnter date and time as (format)srsquotimezone=None)

Bases gluonvalidatorsValidator

Examples

Use as

INPUT(_type=text _name=name requires=IS_DATETIME())

datetime has to be in the ISO8960 format YYYY-MM-DD hhmmss timezome must be None or apytztimezone(ldquoAmericaChicagordquo) object

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

isodatetime = Y-m-d HMS

static nice(format)

class gluonvalidatorsIS_DECIMAL_IN_RANGE(minimum=None maximum=None er-ror_message=None dot=rsquorsquo)

Bases gluonvalidatorsValidator

Determines that the argument is (or can be represented as) a Python Decimal and that it falls within the specifiedinclusive range The comparison is made with Python Decimal arithmetic

The minimum and maximum limits can be None meaning no lower or upper limit respectively

Example

Used as

INPUT(_type=text _name=name requires=IS_DECIMAL_IN_RANGE(0 10))

gtgtgt IS_DECIMAL_IN_RANGE(15)(4)(Decimal(4) None)gtgtgt IS_DECIMAL_IN_RANGE(15)(4)(Decimal(4) None)gtgtgt IS_DECIMAL_IN_RANGE(15)(1)(Decimal(1) None)gtgtgt IS_DECIMAL_IN_RANGE(15)(525)(525 enter a number between 1 and 5)gtgtgt IS_DECIMAL_IN_RANGE(5256)(525)(Decimal(525) None)gtgtgt IS_DECIMAL_IN_RANGE(5256)(525)(Decimal(525) None)gtgtgt IS_DECIMAL_IN_RANGE(15)(60)(60 enter a number between 1 and 5)gtgtgt IS_DECIMAL_IN_RANGE(15)(35)(Decimal(35) None)gtgtgt IS_DECIMAL_IN_RANGE(1555)(35)(Decimal(35) None)gtgtgt IS_DECIMAL_IN_RANGE(1555)(65)(65 enter a number between 15 and 55)

(continues on next page)

371 Validators 149

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_DECIMAL_IN_RANGE(15None)(65)(Decimal(65) None)gtgtgt IS_DECIMAL_IN_RANGE(15None)(05)(05 enter a number greater than or equal to 15)gtgtgt IS_DECIMAL_IN_RANGE(None55)(45)(Decimal(45) None)gtgtgt IS_DECIMAL_IN_RANGE(None55)(65)(65 enter a number less than or equal to 55)gtgtgt IS_DECIMAL_IN_RANGE()(65)(Decimal(65) None)gtgtgt IS_DECIMAL_IN_RANGE(099)(123123)(123123 enter a number between 0 and 99)gtgtgt IS_DECIMAL_IN_RANGE(099)(123123)(123123 enter a number between 0 and 99)gtgtgt IS_DECIMAL_IN_RANGE(099)(1234)(Decimal(1234) None)gtgtgt IS_DECIMAL_IN_RANGE()(abc)(abc enter a number)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

class gluonvalidatorsIS_EMAIL(banned=None forced=None error_message=rsquoEnter a validemail addressrsquo)

Bases gluonvalidatorsValidator

Checks if fieldrsquos value is a valid email address Can be set to disallow or force addresses from certain domain(s)

Email regex adapted from httphaackedcomarchive20070821i-knew-how-to-validate-an-email-address-until-iaspx generally following the RFCs except that we disallow quoted strings and permit underscores and leadingnumerics in subdomain labels

Parameters

bull banned ndash regex text for disallowed address domains

bull forced ndash regex text for required address domains

Both arguments can also be custom objects with a match(value) method

Example

Check for valid email address

INPUT(_type=text _name=namerequires=IS_EMAIL())

Check for valid email address that canrsquot be from a com domain

INPUT(_type=text _name=namerequires=IS_EMAIL(banned=^com(|)$))

Check for valid email address that must be from a edu domain

INPUT(_type=text _name=namerequires=IS_EMAIL(forced=^edu(|)$))

(continues on next page)

150 Chapter 37 validators Module

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_EMAIL()(abcom)(abcom None)gtgtgt IS_EMAIL()(abcdefcom)(abcdefcom None)gtgtgt IS_EMAIL()(abc3defcom)(abc3defcom None)gtgtgt IS_EMAIL()(abcdefus)(abcdefus None)gtgtgt IS_EMAIL()(abcd_-fus)(abcd_-fus None)gtgtgt IS_EMAIL()(defcom) missing name(defcom enter a valid email address)gtgtgt IS_EMAIL()(abcdefcom) quoted name(abcdefcom enter a valid email address)gtgtgt IS_EMAIL()(abc+defcom) no (abc+defcom enter a valid email address)gtgtgt IS_EMAIL()(abcdefx) one-char TLD(abcdefx enter a valid email address)gtgtgt IS_EMAIL()(abcdef12) numeric TLD(abcdef12 enter a valid email address)gtgtgt IS_EMAIL()(abcdefcom) double-dot in domain(abcdefcom enter a valid email address)gtgtgt IS_EMAIL()(abcdefcom) dot starts domain(abcdefcom enter a valid email address)gtgtgt IS_EMAIL()(abcdefc_m) underscore in TLD(abcdefc_m enter a valid email address)gtgtgt IS_EMAIL()(NotAnEmail) missing (NotAnEmail enter a valid email address)gtgtgt IS_EMAIL()(abcNotAnEmail) missing TLD(abcNotAnEmail enter a valid email address)gtgtgt IS_EMAIL()(customerdepartmentexamplecom)(customerdepartmentexamplecom None)gtgtgt IS_EMAIL()($A12345examplecom)($A12345examplecom None)gtgtgt IS_EMAIL()(defxyzabcexamplecom)(defxyzabcexamplecom None)gtgtgt IS_EMAIL()(_YosemiteSamexamplecom)(_YosemiteSamexamplecom None)gtgtgt IS_EMAIL()(~examplecom)(~examplecom None)gtgtgt IS_EMAIL()(woolyexamplecom) dot starts name(woolyexamplecom enter a valid email address)gtgtgt IS_EMAIL()(woolyexamplecom) adjacent dots in name(woolyexamplecom enter a valid email address)gtgtgt IS_EMAIL()(pootietangexamplecom) dot ends name(pootietangexamplecom enter a valid email address)gtgtgt IS_EMAIL()(examplecom) name is bare dot(examplecom enter a valid email address)gtgtgt IS_EMAIL()(ImaFoolexamplecom)(ImaFoolexamplecom None)gtgtgt IS_EMAIL()(Ima Foolexamplecom) space in name(Ima Foolexamplecom enter a valid email address)gtgtgt IS_EMAIL()(localguylocalhost) localhost as domain(localguylocalhost None)

regex = lt_sreSRE_Pattern object at 0x2e0e160gt

371 Validators 151

web2py Documentation Release 2146-stable

regex_proposed_but_failed = lt_sreSRE_Pattern object at 0x2e100d0gt

class gluonvalidatorsIS_LIST_OF_EMAILS(error_message=rsquoInvalid emails srsquo)Bases object

Example

Used as

Field(emailsliststringwidget=SQLFORMwidgetstextwidgetrequires=IS_LIST_OF_EMAILS()represent=lambda vr SPAN([A(x_href=mailto+x)

rarr˓for x in (v or [])]))

formatter(value row=None)

split_emails = lt_sreSRE_Pattern objectgt

class gluonvalidatorsIS_EMPTY_OR(other null=None empty_regex=None)Bases gluonvalidatorsValidator

Dummy class for testing IS_EMPTY_OR

gtgtgt IS_EMPTY_OR(IS_EMAIL())(abcdefcom)(abcdefcom None)gtgtgt IS_EMPTY_OR(IS_EMAIL())( )(None None)gtgtgt IS_EMPTY_OR(IS_EMAIL() null=abc)( )(abc None)gtgtgt IS_EMPTY_OR(IS_EMAIL() null=abc empty_regex=def)(def)(abc None)gtgtgt IS_EMPTY_OR(IS_EMAIL())(abc)(abc enter a valid email address)gtgtgt IS_EMPTY_OR(IS_EMAIL())( abc )(abc enter a valid email address)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

set_self_id(id)

class gluonvalidatorsIS_EXPR(expression error_message=rsquoInvalid expressionrsquo environ-ment=None)

Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=namerequires=IS_EXPR(5 lt int(value) lt 10))

The argument of IS_EXPR must be python condition

152 Chapter 37 validators Module

web2py Documentation Release 2146-stable

gtgtgt IS_EXPR(int(value) lt 2)(1)(1 None)

gtgtgt IS_EXPR(int(value) lt 2)(2)(2 invalid expression)

class gluonvalidatorsIS_FLOAT_IN_RANGE(minimum=None maximum=None er-ror_message=None dot=rsquorsquo)

Bases gluonvalidatorsValidator

Determines that the argument is (or can be represented as) a float and that it falls within the specified inclusiverange The comparison is made with native arithmetic

The minimum and maximum limits can be None meaning no lower or upper limit respectively

Example

Used as

INPUT(_type=text _name=name requires=IS_FLOAT_IN_RANGE(0 10))

gtgtgt IS_FLOAT_IN_RANGE(15)(4)(40 None)gtgtgt IS_FLOAT_IN_RANGE(15)(4)(40 None)gtgtgt IS_FLOAT_IN_RANGE(15)(1)(10 None)gtgtgt IS_FLOAT_IN_RANGE(15)(525)(525 enter a number between 1 and 5)gtgtgt IS_FLOAT_IN_RANGE(15)(60)(60 enter a number between 1 and 5)gtgtgt IS_FLOAT_IN_RANGE(15)(35)(35 None)gtgtgt IS_FLOAT_IN_RANGE(1None)(35)(35 None)gtgtgt IS_FLOAT_IN_RANGE(None5)(35)(35 None)gtgtgt IS_FLOAT_IN_RANGE(1None)(05)(05 enter a number greater than or equal to 1)gtgtgt IS_FLOAT_IN_RANGE(None5)(65)(65 enter a number less than or equal to 5)gtgtgt IS_FLOAT_IN_RANGE()(65)(65 None)gtgtgt IS_FLOAT_IN_RANGE()(abc)(abc enter a number)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

class gluonvalidatorsIS_IMAGE(extensions=(rsquobmprsquo rsquogifrsquo rsquojpegrsquo rsquopngrsquo) maxsize=(1000010000) minsize=(0 0) error_message=rsquoInvalid imagersquo)

Bases gluonvalidatorsValidator

Checks if file uploaded through file input was saved in one of selected image formats and has dimensions (widthand height) within given boundaries

371 Validators 153

web2py Documentation Release 2146-stable

Does not check for maximum file size (use IS_LENGTH for that) Returns validation failure if no data wasuploaded

Supported file formats BMP GIF JPEG PNG

Code parts taken from httpmailpythonorgpipermailpython-list2007-June617126html

Parameters

bull extensions ndash iterable containing allowed lowercase image file extensions

bull extension of uploaded file counts as jpeg) ((jpg) ndash

bull maxsize ndash iterable containing maximum width and height of the image

bull minsize ndash iterable containing minimum width and height of the image

Use (-1 -1) as minsize to pass image size check

Examples

Check if uploaded file is in any of supported image formats

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_IMAGE())

Check if uploaded file is either JPEG or PNG

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_IMAGE(extensions=(lsquojpegrsquo lsquopngrsquo)))

Check if uploaded file is PNG with maximum size of 200x200 pixels

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_IMAGE(extensions=(lsquopngrsquo) maxsize=(200200)))

class gluonvalidatorsIS_IN_DB(dbset field label=None error_message=rsquoValue not indatabasersquo orderby=None groupby=None distinct=Nonecache=None multiple=False zero=rdquo sort=False_and=None left=None delimiter=None auto_add=False)

Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=namerequires=IS_IN_DB(db dbmytablemyfield zero=))

used for reference fields rendered as a dropbox

build_set()

maybe_add(table fieldname value)

options(zero=True)

set_self_id(id)

class gluonvalidatorsIS_IN_SET(theset labels=None error_message=rsquoValue not allowedrsquomultiple=False zero=rdquo sort=False)

Bases gluonvalidatorsValidator

154 Chapter 37 validators Module

web2py Documentation Release 2146-stable

Example

Used as

INPUT(_type=text _name=namerequires=IS_IN_SET([max john]zero=))

The argument of IS_IN_SET must be a list or set

gtgtgt IS_IN_SET([max john])(max)(max None)gtgtgt IS_IN_SET([max john])(massimo)(massimo value not allowed)gtgtgt IS_IN_SET([max john] multiple=True)((max john))((max john) None)gtgtgt IS_IN_SET([max john] multiple=True)((bill john))((bill john) value not allowed)gtgtgt IS_IN_SET((id1id2) [first labelsecond label])(id1) Traditionalrarr˓way(id1 None)gtgtgt IS_IN_SET(id1first label id2second label)(id1)(id1 None)gtgtgt import itertoolsgtgtgt IS_IN_SET(itertoolschain([135][246]))(1)(1 None)gtgtgt IS_IN_SET([(id1first label) (id2second label)])(id1) Redundantrarr˓way(id1 None)

options(zero=True)

class gluonvalidatorsIS_INT_IN_RANGE(minimum=None maximum=None er-ror_message=None)

Bases gluonvalidatorsValidator

Determines that the argument is (or can be represented as) an int and that it falls within the specified range Therange is interpreted in the Pythonic way so the test is min lt= value lt max

The minimum and maximum limits can be None meaning no lower or upper limit respectively

Example

Used as

INPUT(_type=text _name=name requires=IS_INT_IN_RANGE(0 10))

gtgtgt IS_INT_IN_RANGE(15)(4)(4 None)gtgtgt IS_INT_IN_RANGE(15)(4)(4 None)gtgtgt IS_INT_IN_RANGE(15)(1)(1 None)gtgtgt IS_INT_IN_RANGE(15)(5)(5 enter an integer between 1 and 4)gtgtgt IS_INT_IN_RANGE(15)(5)(5 enter an integer between 1 and 4)gtgtgt IS_INT_IN_RANGE(15)(35)

(continues on next page)

371 Validators 155

web2py Documentation Release 2146-stable

(continued from previous page)

(35 enter an integer between 1 and 4)gtgtgt IS_INT_IN_RANGE(None5)(4)(4 None)gtgtgt IS_INT_IN_RANGE(None5)(6)(6 enter an integer less than or equal to 4)gtgtgt IS_INT_IN_RANGE(1None)(4)(4 None)gtgtgt IS_INT_IN_RANGE(1None)(0)(0 enter an integer greater than or equal to 1)gtgtgt IS_INT_IN_RANGE()(6)(6 None)gtgtgt IS_INT_IN_RANGE()(abc)(abc enter an integer)

class gluonvalidatorsIS_IPV4(minip=rsquo0000rsquo maxip=rsquo255255255255rsquo invert=Falseis_localhost=None is_private=None is_automatic=Noneerror_message=rsquoEnter valid IPv4 addressrsquo)

Bases gluonvalidatorsValidator

Checks if fieldrsquos value is an IP version 4 address in decimal form Can be set to force addresses from certainrange

IPv4 regex taken from httpregexlibcomREDetailsaspxregexp_id=1411

Parameters

bull minip ndash lowest allowed address accepts

ndash str eg 19216801

ndash list or tuple of octets eg [192 168 0 1]

bull maxip ndash highest allowed address same as above

bull invert ndash True to allow addresses only from outside of given range note that range bound-aries are not matched this way

bull is_localhost ndash localhost address treatment

ndash None (default) indifferent

ndash True (enforce) query address must match localhost address (127001)

ndash False (forbid) query address must not match localhost address

bull is_private ndash same as above except that query address is checked against two addressranges 1721600 - 17231255255 and 19216800 - 192168255255

bull is_automatic ndash same as above except that query address is checked against one addressrange 16925400 - 169254255255

Minip and maxip may also be lists or tuples of addresses in all above forms (str int list tuple) allowing setupof multiple address ranges

minip = (minip1 minip2 minipN)| | || | |

maxip = (maxip1 maxip2 maxipN)

Longer iterable will be truncated to match length of shorter one

156 Chapter 37 validators Module

web2py Documentation Release 2146-stable

Examples

Check for valid IPv4 address

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV4())

Check for valid IPv4 address belonging to specific range

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV4(minip=lsquo10020000rsquomaxip=lsquo100200255255rsquo))

Check for valid IPv4 address belonging to either 10011000 - 100110255255 or 2005000 - 200500255address range

INPUT(_type=rsquotextrsquo _name=rsquonamersquo

requires=IS_IPV4(minip=(lsquo10011000rsquo lsquo2005000rsquo) maxip=(lsquo100110255255rsquolsquo200500255rsquo)))

Check for valid IPv4 address belonging to private address space

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV4(is_private=True))

Check for valid IPv4 address that is not a localhost address

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV4(is_localhost=False))

gtgtgt IS_IPV4()(1234)(1234 None)gtgtgt IS_IPV4()(255255255255)(255255255255 None)gtgtgt IS_IPV4()(1234 )(1234 enter valid IPv4 address)gtgtgt IS_IPV4()(12345)(12345 enter valid IPv4 address)gtgtgt IS_IPV4()(123123)(123123 enter valid IPv4 address)gtgtgt IS_IPV4()(1111234)(1111234 enter valid IPv4 address)gtgtgt IS_IPV4()(0111234)(0111234 enter valid IPv4 address)gtgtgt IS_IPV4()(256234)(256234 enter valid IPv4 address)gtgtgt IS_IPV4()(300234)(300234 enter valid IPv4 address)gtgtgt IS_IPV4(minip=1234 maxip=1234)(1234)(1234 None)gtgtgt IS_IPV4(minip=1235 maxip=1239 error_message=Bad ip)(1rarr˓234)(1234 bad ip)gtgtgt IS_IPV4(maxip=1234 invert=True)(127001)(127001 None)gtgtgt IS_IPV4(maxip=1234 invert=True)(1234)(1234 enter valid IPv4 address)gtgtgt IS_IPV4(is_localhost=True)(127001)(127001 None)gtgtgt IS_IPV4(is_localhost=True)(1234)(1234 enter valid IPv4 address)gtgtgt IS_IPV4(is_localhost=False)(127001)(127001 enter valid IPv4 address)

(continues on next page)

371 Validators 157

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_IPV4(maxip=100000 is_localhost=True)(127001)(127001 enter valid IPv4 address)

automatic = (2851995648L 2852061183L)

localhost = 2130706433

numbers = (16777216 65536 256 1)

private = ((2886729728L 2886795263L) (3232235520L 3232301055L))

regex = lt_sreSRE_Pattern object at 0x2e26320gt

class gluonvalidatorsIS_IPV6(is_private=None is_link_local=None is_reserved=Noneis_multicast=None is_routeable=None is_6to4=Noneis_teredo=None subnets=None error_message=rsquoEnter validIPv6 addressrsquo)

Bases gluonvalidatorsValidator

Checks if fieldrsquos value is an IP version 6 address First attempts to use the ipaddress library and falls back tocontribipaddrpy from Google (httpscodegooglecompipaddr-py)

Parameters

bull is_private ndash None (default) indifferent True (enforce) address must be in fc007range False (forbid) address must NOT be in fc007 range

bull is_link_local ndash Same as above but uses fe8010 range

bull is_reserved ndash Same as above but uses IETF reserved range

bull is_mulicast ndash Same as above but uses ff008 range

bull is_routeable ndash Similar to above but enforces not private link_local reserved or multi-cast

bull is_6to4 ndash Same as above but uses 200216 range

bull is_teredo ndash Same as above but uses 200132 range

bull subnets ndash value must be a member of at least one from list of subnets

Examples

Check for valid IPv6 address

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV6())

Check for valid IPv6 address is a link_local address

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV6(is_link_local=True))

Check for valid IPv6 address that is Internet routeable

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV6(is_routeable=True))

Check for valid IPv6 address in specified subnet

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV6(subnets=[lsquo200132rsquo])

158 Chapter 37 validators Module

web2py Documentation Release 2146-stable

gtgtgt IS_IPV6()(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPV6()(19216811)(19216811 enter valid IPv6 address)gtgtgt IS_IPV6(error_message=Bad ip)(19216811)(19216811 bad ip)gtgtgt IS_IPV6(is_link_local=True)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPV6(is_link_local=False)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(is_link_local=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(is_multicast=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(is_multicast=True)(ff00126c8ffafe22b3af)(ff00126c8ffafe22b3af None)gtgtgt IS_IPV6(is_routeable=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af None)gtgtgt IS_IPV6(is_routeable=True)(ff00126c8ffafe22b3af)(ff00126c8ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(subnets=200132)(20018ffafe22b3af)(20018ffafe22b3af None)gtgtgt IS_IPV6(subnets=fb008)(20018ffafe22b3af)(20018ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(subnets=[fc008200132])(20018ffafe22b3af)(20018ffafe22b3af None)gtgtgt IS_IPV6(subnets=invalidsubnet)(20018ffafe22b3af)(20018ffafe22b3af invalid subnet provided)

class gluonvalidatorsIS_IPADDRESS(minip=rsquo0000rsquo maxip=rsquo255255255255rsquo in-vert=False is_localhost=None is_private=Noneis_automatic=None is_ipv4=None is_link_local=Noneis_reserved=None is_multicast=Noneis_routeable=None is_6to4=None is_teredo=Nonesubnets=None is_ipv6=None error_message=rsquoEntervalid IP addressrsquo)

Bases gluonvalidatorsValidator

Checks if fieldrsquos value is an IP Address (v4 or v6) Can be set to force addresses from within a specific rangeChecks are done with the correct IS_IPV4 and IS_IPV6 validators

Uses ipaddress library if found falls back to PEP-3144 ipaddrpy from Google (in contrib)

Parameters

bull minip ndash lowest allowed address accepts str eg 19216801 list or tuple of octets eg[192 168 0 1]

bull maxip ndash highest allowed address same as above

bull invert ndash True to allow addresses only from outside of given range note that range bound-aries are not matched this way

IPv4 specific arguments

bull is_localhost localhost address treatment

ndash None (default) indifferent

ndash True (enforce) query address must match localhost address (127001)

371 Validators 159

web2py Documentation Release 2146-stable

ndash False (forbid) query address must not match localhost address

bull is_private same as above except that query address is checked against two address ranges 1721600 -17231255255 and 19216800 - 192168255255

bull is_automatic same as above except that query address is checked against one address range 16925400- 169254255255

bull is_ipv4 either

ndash None (default) indifferent

ndash True (enforce) must be an IPv4 address

ndash False (forbid) must NOT be an IPv4 address

IPv6 specific arguments

bull is_link_local Same as above but uses fe8010 range

bull is_reserved Same as above but uses IETF reserved range

bull is_mulicast Same as above but uses ff008 range

bull is_routeable Similar to above but enforces not private link_local reserved or multicast

bull is_6to4 Same as above but uses 200216 range

bull is_teredo Same as above but uses 200132 range

bull subnets value must be a member of at least one from list of subnets

bull is_ipv6 either

ndash None (default) indifferent

ndash True (enforce) must be an IPv6 address

ndash False (forbid) must NOT be an IPv6 address

Minip and maxip may also be lists or tuples of addresses in all above forms (str int list tuple) allowing setupof multiple address ranges

minip = (minip1 minip2 minipN)| | || | |

maxip = (maxip1 maxip2 maxipN)

Longer iterable will be truncated to match length of shorter one

gtgtgt IS_IPADDRESS()(19216815)(19216815 None)gtgtgt IS_IPADDRESS(is_ipv6=False)(19216815)(19216815 None)gtgtgt IS_IPADDRESS()(255255255255)(255255255255 None)gtgtgt IS_IPADDRESS()(19216815 )(19216815 enter valid IP address)gtgtgt IS_IPADDRESS()(192168115)(192168115 enter valid IP address)gtgtgt IS_IPADDRESS()(123123)(123123 enter valid IP address)gtgtgt IS_IPADDRESS()(1111234)(1111234 enter valid IP address)gtgtgt IS_IPADDRESS()(0111234)

(continues on next page)

160 Chapter 37 validators Module

web2py Documentation Release 2146-stable

(continued from previous page)

(0111234 enter valid IP address)gtgtgt IS_IPADDRESS()(256234)(256234 enter valid IP address)gtgtgt IS_IPADDRESS()(300234)(300234 enter valid IP address)gtgtgt IS_IPADDRESS(minip=19216810 maxip=1921681255)(1921681100)(1921681100 None)gtgtgt IS_IPADDRESS(minip=1235 maxip=1239 error_message=Bad ip)(123rarr˓4)(1234 bad ip)gtgtgt IS_IPADDRESS(maxip=1234 invert=True)(127001)(127001 None)gtgtgt IS_IPADDRESS(maxip=19216814 invert=True)(19216814)(19216814 enter valid IP address)gtgtgt IS_IPADDRESS(is_localhost=True)(127001)(127001 None)gtgtgt IS_IPADDRESS(is_localhost=True)(192168110)(192168110 enter valid IP address)gtgtgt IS_IPADDRESS(is_localhost=False)(127001)(127001 enter valid IP address)gtgtgt IS_IPADDRESS(maxip=100000 is_localhost=True)(127001)(127001 enter valid IP address)

gtgtgt IS_IPADDRESS()(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPADDRESS(is_ipv4=False)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPADDRESS()(fe80126c8ffafe22b3af )(fe80126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_ipv4=True)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_ipv6=True)(19216811)(19216811 enter valid IP address)gtgtgt IS_IPADDRESS(is_ipv6=True error_message=Bad ip)(19216811)(19216811 bad ip)gtgtgt IS_IPADDRESS(is_link_local=True)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPADDRESS(is_link_local=False)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_link_local=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_multicast=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_multicast=True)(ff00126c8ffafe22b3af)(ff00126c8ffafe22b3af None)gtgtgt IS_IPADDRESS(is_routeable=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af None)gtgtgt IS_IPADDRESS(is_routeable=True)(ff00126c8ffafe22b3af)(ff00126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(subnets=200132)(20018ffafe22b3af)(20018ffafe22b3af None)gtgtgt IS_IPADDRESS(subnets=fb008)(20018ffafe22b3af)(20018ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(subnets=[fc008200132])(20018ffafe22b3af)(20018ffafe22b3af None)gtgtgt IS_IPADDRESS(subnets=invalidsubnet)(20018ffafe22b3af)(20018ffafe22b3af invalid subnet provided)

371 Validators 161

web2py Documentation Release 2146-stable

class gluonvalidatorsIS_LENGTH(maxsize=255 minsize=0 error_message=rsquoEnter from(min)g to (max)g charactersrsquo)

Bases gluonvalidatorsValidator

Checks if length of fieldrsquos value fits between given boundaries Works for both text and file inputs

Parameters

bull maxsize ndash maximum allowed length size

bull minsize ndash minimum allowed length size

Examples

Check if text string is shorter than 33 characters

INPUT(_type=text _name=name requires=IS_LENGTH(32))

Check if password string is longer than 5 characters

INPUT(_type=password _name=name requires=IS_LENGTH(minsize=6))

Check if uploaded file has size between 1KB and 1MB

INPUT(_type=file _name=name requires=IS_LENGTH(1048576 1024))

Other examples

gtgtgt IS_LENGTH()()( None)gtgtgt IS_LENGTH()(1234567890)(1234567890 None)gtgtgt IS_LENGTH(maxsize=5 minsize=0)(1234567890) too long(1234567890 enter from 0 to 5 characters)gtgtgt IS_LENGTH(maxsize=50 minsize=20)(1234567890) too short(1234567890 enter from 20 to 50 characters)

class gluonvalidatorsIS_LIST_OF(other=None minimum=0 maximum=100 er-ror_message=None)

Bases gluonvalidatorsValidator

class gluonvalidatorsIS_LOWERBases gluonvalidatorsValidator

Converts to lower case

gtgtgt IS_LOWER()(ABC)(abc None)gtgtgt IS_LOWER()(Ntilde)(xc3xb1 None)

class gluonvalidatorsIS_MATCH(expression error_message=rsquoInvalid expressionrsquo strict=Falsesearch=False extract=False is_unicode=False)

Bases gluonvalidatorsValidator

Example

Used as

162 Chapter 37 validators Module

web2py Documentation Release 2146-stable

INPUT(_type=text _name=name requires=IS_MATCH(+))

The argument of IS_MATCH is a regular expression

gtgtgt IS_MATCH(+)(hello)(hello None)

gtgtgt IS_MATCH(hell)(hello)(hello None)

gtgtgt IS_MATCH(hell strict=False)(hello)(hello None)

gtgtgt IS_MATCH(hello)(shello)(shello invalid expression)

gtgtgt IS_MATCH(hello search=True)(shello)(shello None)

gtgtgt IS_MATCH(hello search=True strict=False)(shellox)(shellox None)

gtgtgt IS_MATCH(hello search=True strict=False)(shellox)(shellox None)

gtgtgt IS_MATCH(+)()( invalid expression)

class gluonvalidatorsIS_EQUAL_TO(expression error_message=rsquoNo matchrsquo)Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=password)INPUT(_type=text _name=password2

requires=IS_EQUAL_TO(requestvarspassword))

The argument of IS_EQUAL_TO is a string

gtgtgt IS_EQUAL_TO(aaa)(aaa)(aaa None)

gtgtgt IS_EQUAL_TO(aaa)(aab)(aab no match)

class gluonvalidatorsIS_NOT_EMPTY(error_message=rsquoEnter a valuersquo empty_regex=None)Bases gluonvalidatorsValidator

Example

Used as

371 Validators 163

web2py Documentation Release 2146-stable

INPUT(_type=text _name=name requires=IS_NOT_EMPTY())

gtgtgt IS_NOT_EMPTY()(1)(1 None)gtgtgt IS_NOT_EMPTY()(0)(0 None)gtgtgt IS_NOT_EMPTY()(x)(x None)gtgtgt IS_NOT_EMPTY()( x )(x None)gtgtgt IS_NOT_EMPTY()(None)(None enter a value)gtgtgt IS_NOT_EMPTY()()( enter a value)gtgtgt IS_NOT_EMPTY()( )( enter a value)gtgtgt IS_NOT_EMPTY()( nt)( enter a value)gtgtgt IS_NOT_EMPTY()([])([] enter a value)gtgtgt IS_NOT_EMPTY(empty_regex=def)(def)( enter a value)gtgtgt IS_NOT_EMPTY(empty_regex=de[fg])(deg)( enter a value)gtgtgt IS_NOT_EMPTY(empty_regex=def)(abc)(abc None)

class gluonvalidatorsIS_NOT_IN_DB(dbset field error_message=rsquoValue already indatabase or emptyrsquo allowed_override=[] ig-nore_common_filters=False)

Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=name requires=IS_NOT_IN_DB(db dbtable))

makes the field unique

set_self_id(id)

gluonvalidatorsIS_NULL_ORalias of gluonvalidatorsIS_EMPTY_OR

class gluonvalidatorsIS_SLUG(maxlen=80 check=False error_message=rsquoMust be slugrsquokeep_underscores=False)

Bases gluonvalidatorsValidator

converts arbitrary text string to a slug

gtgtgt IS_SLUG()(abc123)(abc123 None)gtgtgt IS_SLUG()(ABC123)(abc123 None)gtgtgt IS_SLUG()(abc-123)(abc-123 None)

(continues on next page)

164 Chapter 37 validators Module

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_SLUG()(abc--123)(abc-123 None)gtgtgt IS_SLUG()(abc 123)(abc-123 None)gtgtgt IS_SLUG()(abc _123)(abc-123 None)gtgtgt IS_SLUG()(-abc-)(abc None)gtgtgt IS_SLUG()(--a--b--_ -c--)(a-b-c None)gtgtgt IS_SLUG()(abcampamp123)(abc123 None)gtgtgt IS_SLUG()(abcampamp123ampampdef)(abc123def None)gtgtgt IS_SLUG()(ntilde)(n None)gtgtgt IS_SLUG(maxlen=4)(abc123)(abc1 None)gtgtgt IS_SLUG()(abc_123)(abc-123 None)gtgtgt IS_SLUG(keep_underscores=False)(abc_123)(abc-123 None)gtgtgt IS_SLUG(keep_underscores=True)(abc_123)(abc_123 None)gtgtgt IS_SLUG(check=False)(abc)(abc None)gtgtgt IS_SLUG(check=True)(abc)(abc None)gtgtgt IS_SLUG(check=False)(a bc)(a-bc None)gtgtgt IS_SLUG(check=True)(a bc)(a bc must be slug)

static urlify(value maxlen=80 keep_underscores=False)

class gluonvalidatorsIS_STRONG(min=None max=None upper=None lower=Nonenumber=None entropy=None special=Nonespecials=rsquo~$^amp()_+-=ltgt []|rsquo invalid=rsquorsquo error_message=None es=False)

Bases object

Examples

Use as

INPUT(_type=password _name=passwdrequires=IS_STRONG(min=10 special=2 upper=2))

enforces complexity requirements on a field

gtgtgt IS_STRONG(es=True)(Abcd1234)(Abcd1234Must include at least 1 of the following ~$^amp()_+-=ltgt[]|)gtgtgt IS_STRONG(es=True)(Abcd1234)(Abcd1234 None)

(continues on next page)

371 Validators 165

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_STRONG(es=True entropy=1)(a)(a None)gtgtgt IS_STRONG(es=True entropy=1 min=2)(a)(a Minimum length is 2)gtgtgt IS_STRONG(es=True entropy=100)(abc123)(abc123 Entropy (3235) less than required (100))gtgtgt IS_STRONG(es=True entropy=100)(and)(and Entropy (1457) less than required (100))gtgtgt IS_STRONG(es=True entropy=100)(aaa)(aaa Entropy (1442) less than required (100))gtgtgt IS_STRONG(es=True entropy=100)(a1d)(a1d Entropy (1597) less than required (100))gtgtgt IS_STRONG(es=True entropy=100)(antilded)(axc3xb1d Entropy (1813) less than required (100))

class gluonvalidatorsIS_TIME(error_message=rsquoEnter time as hhmmss (seconds am pm op-tional)rsquo)

Bases gluonvalidatorsValidator

Example

Use as

INPUT(_type=text _name=name requires=IS_TIME())

understands the following formats hhmmss [ampm] hhmm [ampm] hh [ampm]

[ampm] is optional lsquorsquo can be replaced by any other non-space non-digit

gtgtgt IS_TIME()(2130)(datetimetime(21 30) None)gtgtgt IS_TIME()(21-30)(datetimetime(21 30) None)gtgtgt IS_TIME()(2130)(datetimetime(21 30) None)gtgtgt IS_TIME()(213059)(datetimetime(21 30 59) None)gtgtgt IS_TIME()(530)(datetimetime(5 30) None)gtgtgt IS_TIME()(530 am)(datetimetime(5 30) None)gtgtgt IS_TIME()(530 pm)(datetimetime(17 30) None)gtgtgt IS_TIME()(530 whatever)(530 whatever enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()(530 20)(530 20 enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()(2430)(2430 enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()(2160)(2160 enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()(2130)(2130 enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()()( enter time as hhmmss (seconds am pm optional))ugrave

166 Chapter 37 validators Module

web2py Documentation Release 2146-stable

class gluonvalidatorsIS_UPLOAD_FILENAME(filename=None extension=None lastdot=Truecase=1 error_message=rsquoEnter valid filenamersquo)

Bases gluonvalidatorsValidator

Checks if name and extension of file uploaded through file input matches given criteria

Does not ensure the file type in any way Returns validation failure if no data was uploaded

Parameters

bull filename ndash filename (before dot) regex

bull extension ndash extension (after dot) regex

bull lastdot ndash which dot should be used as a filename extension separator True means lastdot eg filepng -gt file png False means first dot eg filetargz -gt file targz

bull case ndash 0 - keep the case 1 - transform the string into lowercase (default) 2 - transform thestring into uppercase

If there is no dot present extension checks will be done against empty string and filename checks against wholevalue

Examples

Check if file has a pdf extension (case insensitive)

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_UPLOAD_FILENAME(extension=rsquopdfrsquo))

Check if file has a targz extension and name starting with backup

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_UPLOAD_FILENAME(filename=rsquobackuprsquo exten-sion=rsquotargzrsquo lastdot=False))

Check if file has no extension and name matching README (case sensitive)

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_UPLOAD_FILENAME(filename=rsquo^README$rsquoextension=rsquo^$rsquo case=0)

class gluonvalidatorsIS_UPPERBases gluonvalidatorsValidator

Converts to upper case

gtgtgt IS_UPPER()(abc)(ABC None)gtgtgt IS_UPPER()(ntilde)(xc3x91 None)

class gluonvalidatorsIS_URL(error_message=rsquoEnter a valid URLrsquo mode=rsquohttprsquo al-lowed_schemes=None prepend_scheme=rsquohttprsquo al-lowed_tlds=None)

Bases gluonvalidatorsValidator

Rejects a URL string if any of the following is true

bull The string is empty or None

bull The string uses characters that are not allowed in a URL

bull The string breaks any of the HTTP syntactic rules

bull The URL scheme specified (if one is specified) is not lsquohttprsquo or lsquohttpsrsquo

371 Validators 167

web2py Documentation Release 2146-stable

bull The top-level domain (if a host name is specified) does not exist

(These rules are based on RFC 2616 httpwwwfaqsorgrfcsrfc2616html)

This function only checks the URLrsquos syntax It does not check that the URL points to a real document forexample or that it otherwise makes sense semantically This function does automatically prepend lsquohttprsquo infront of a URL in the case of an abbreviated URL (eg lsquogooglecarsquo)

If the parameter mode=rsquogenericrsquo is used then this functionrsquos behavior changes It then rejects a URL string ifany of the following is true

bull The string is empty or None

bull The string uses characters that are not allowed in a URL

bull The URL scheme specified (if one is specified) is not valid

(These rules are based on RFC 2396 httpwwwfaqsorgrfcsrfc2396html)

The list of allowed schemes is customizable with the allowed_schemes parameter If you exclude None fromthe list then abbreviated URLs (lacking a scheme such as lsquohttprsquo) will be rejected

The default prepended scheme is customizable with the prepend_scheme parameter If you set prepend_schemeto None then prepending will be disabled URLs that require prepending to parse will still be accepted but thereturn value will not be modified

IS_URL is compatible with the Internationalized Domain Name (IDN) standard specified in RFC 3490 (httptoolsietforghtmlrfc3490) As a result URLs can be regular strings or unicode strings If the URLrsquos domaincomponent (eg googleca) contains non-US-ASCII letters then the domain will be converted into Punycode(defined in RFC 3492 httptoolsietforghtmlrfc3492) IS_URL goes a bit beyond the standards and allowsnon-US-ASCII characters to be present in the path and query components of the URL as well These non-US-ASCII characters will be escaped using the standard lsquo20rsquo type syntax eg the unicode character with hexcode 0x4e86 will become lsquo4e86rsquo

Parameters

bull error_message ndash a string the error message to give the end user if the URL does notvalidate

bull allowed_schemes ndash a list containing strings or None Each element is a scheme theinputed URL is allowed to use

bull prepend_scheme ndash a string this scheme is prepended if itrsquos necessary to make the URLvalid

Code Examples

INPUT(_type=text _name=name requires=IS_URL())gtgtgt IS_URL()(abccom)(httpabccom None)

INPUT(_type=text _name=name requires=IS_URL(mode=generic))gtgtgt IS_URL(mode=generic)(abccom)(abccom None)

INPUT(_type=text _name=namerequires=IS_URL(allowed_schemes=[https] prepend_scheme=https))

gtgtgt IS_URL(allowed_schemes=[https] prepend_scheme=https)(httpsabccom)(httpsabccom None)

INPUT(_type=text _name=namerequires=IS_URL(prepend_scheme=https))

(continues on next page)

168 Chapter 37 validators Module

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_URL(prepend_scheme=https)(abccom)(httpsabccom None)

INPUT(_type=text _name=namerequires=IS_URL(mode=generic allowed_schemes=[ftps https]

prepend_scheme=https))gtgtgt IS_URL(mode=generic allowed_schemes=[ftps https] prepend_scheme=rarr˓https)(httpsabccom)(httpsabccom None)gtgtgt IS_URL(mode=generic allowed_schemes=[ftps https None] prepend_rarr˓scheme=https)(abccom)(abccom None)

author Jonathan Benn

class gluonvalidatorsIS_JSON(error_message=rsquoInvalid jsonrsquo native_json=False)Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=namerequires=IS_JSON(error_message=This is not a valid json input)

gtgtgt IS_JSON()(a 100)(ua 100 None)

gtgtgt IS_JSON()(spam1234)(spam1234 invalid json)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

371 Validators 169

web2py Documentation Release 2146-stable

170 Chapter 37 validators Module

CHAPTER 38

widget Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

381 The widget is called from web2py

class gluonwidgetIOBases object

write(data)

gluonwidgetcheck_existent_app(options appname)

gluonwidgetconsole()Defines the behavior of the console web2py execution

gluonwidgetget_code_for_scheduler(app options)

gluonwidgetget_url(host path=rsquorsquo proto=rsquohttprsquo port=80)

gluonwidgetrun_system_tests(options)Runs unittests for gluontests

gluonwidgetstart(cron=True)Starts server

gluonwidgetstart_browser(url startup=False)

gluonwidgetstart_schedulers(options)

class gluonwidgetweb2pyDialog(root options)Bases object

Main window dialog

171

web2py Documentation Release 2146-stable

checkTaskBar()Checks taskbar status

connect_pages()Connects pages

error(message)Shows error message

quit(justHide=False)Finishes the program execution

server_ready()

start()Starts web2py server

start_schedulers(app)

stop()Stops web2py server

try_start_scheduler(app)

try_stop_scheduler(app)

update(text)Updates app text

update_canvas()Updates canvas

update_schedulers(start=False)

172 Chapter 38 widget Module

CHAPTER 39

xmlrpc Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

gluonxmlrpchandler(request response methods)

173

web2py Documentation Release 2146-stable

174 Chapter 39 xmlrpc Module

CHAPTER 40

Indices and tables

bull genindex

bull modindex

bull search

175

web2py Documentation Release 2146-stable

176 Chapter 40 Indices and tables

Python Module Index

ggluonadmin 3gluoncache 7gluoncfs 9gluoncompileapp 11gluoncontenttype 15gluoncustom_import 17gluondal 19gluondebug 21gluondecoder 23gluonfileutils 25gluonglobals 27gluonhighlight 33gluonhtml 35gluonhttp 51gluonlanguages 53gluonmain 57gluonmessageboxhandler 59gluonmyregex 61gluonnewcron 63gluonportalocker 65gluonrecfile 67gluonrestricted 69gluonrewrite 71gluonsanitizer 75gluonscheduler 77gluonserializers 83gluonsettings 85gluonshell 87gluonsql 89gluonsqlhtml 97gluonstorage 107gluonstreamer 111gluontemplate 113gluontools 117gluonutf8 139gluonutils 143gluonvalidators 145gluonwidget 171

gluonxmlrpc 173

177

web2py Documentation Release 2146-stable

178 Python Module Index

Index

AA (class in gluonhtml) 35absolute_path_link() (in module gluonnewcron) 63abspath() (in module gluonfileutils) 25accepts() (gluonhtmlFORM method) 41accepts() (gluonsqlhtmlSQLFORM method) 101accessible_query() (gluontoolsAuth method) 121acf() (gluonrewriteMapUrlOut method) 72acquire() (gluonnewcronToken method) 63action() (gluoncacheCache method) 7add_button() (gluonhtmlFORM method) 41add_class() (in module gluonsqlhtml) 104add_deps() (gluonschedulerJobGraph method) 77add_group() (gluontoolsAuth method) 121add_membership() (gluontoolsAuth method) 121add_path_first() (in module gluonadmin) 3add_permission() (gluontoolsAuth method) 122adj_hibernation() (gluonschedulerScheduler method)

79AES_new() (in module gluonutils) 143allows_jwt() (gluontoolsAuth method) 122amfrpc() (gluontoolsService method) 131amfrpc3() (gluontoolsService method) 131ANY_OF (class in gluonvalidators) 145apath() (in module gluonadmin) 3API_SERVER (gluontoolsRecaptcha attribute) 129API_SSL_SERVER (gluontoolsRecaptcha attribute)

129API_URI (gluontoolsRecaptcha2 attribute) 130app_cleanup() (in module gluonadmin) 3app_compile() (in module gluonadmin) 3app_create() (in module gluonadmin) 4app_install() (in module gluonadmin) 4app_pack() (in module gluonadmin) 4app_pack_compiled() (in module gluonadmin) 4app_uninstall() (in module gluonadmin) 4append() (gluonhtmlDIV method) 37append() (gluontemplateBlockNode method) 113append() (gluontemplateContent method) 114

appfactory() (in module gluonmain) 58apply_filter() (gluonlanguagestranslator method) 53archive() (gluontoolsAuth static method) 122archive() (gluontoolsCrud static method) 130arg0 (gluonrewriteMapUrlIn attribute) 71as_dict() (gluonhtmlFORM method) 41as_dict() (gluonsqlDAL method) 92as_dict() (gluonsqlDALField method) 91as_dict() (gluonsqlDALRow method) 91as_dict() (gluonsqlDALTable method) 92as_dict() (gluonsqlField method) 96as_json() (gluonhtmlFORM method) 41as_json() (gluonsqlDALRow method) 91as_xml() (gluonhtmlFORM method) 41as_xml() (gluonsqlDALRow method) 91as_yaml() (gluonhtmlFORM method) 41assert_status() (gluonhtmlFORM method) 41assert_status() (gluonsqlhtmlSQLFORM method) 101assign_tasks() (gluonschedulerScheduler method) 79ASSIGNJS() (in module gluonhtml) 35async() (gluonschedulerMetaScheduler method) 77Auth (class in gluontools) 121AutocompleteWidget (class in gluonsqlhtml) 97autoDetectXMLEncoding() (in module gluondecoder)

23autokey (gluoncacheCache attribute) 8automatic (gluonvalidatorsIS_IPV4 attribute) 158automenu() (gluontoolsWiki method) 135AUTOTYPES (gluonsqlhtmlSQLFORM attribute) 101

BB (class in gluonhtml) 36basic() (gluontoolsAuth method) 122BEAUTIFY (class in gluonhtml) 36being_a_ticker() (gluonschedulerScheduler method) 79BlockNode (class in gluontemplate) 113BODY (class in gluonhtml) 36body (gluonglobalsRequest attribute) 28BooleanWidget (class in gluonsqlhtml) 97BR (class in gluonhtml) 36

179

web2py Documentation Release 2146-stable

build_acf() (gluonrewriteMapUrlOut method) 72build_environment() (in module gluoncompileapp) 12build_query() (gluonsqlhtmlSQLFORM static method)

101build_set() (gluonvalidatorsIS_IN_DB method) 154bulk_insert() (gluonsqlDALTable method) 92bulk_register() (gluontoolsAuth method) 123BUTTON (class in gluonhtml) 36

CCache (class in gluoncache) 7CacheRepresenter (class in gluonsqlhtml) 97callback() (gluonsqlhtmlAutocompleteWidget method)

97can_edit() (gluontoolsWiki method) 135can_join() (gluonsqlDAL method) 92can_manage() (gluontoolsWiki method) 135can_read() (gluontoolsWiki method) 135can_search() (gluontoolsWiki method) 135can_see_menu() (gluontoolsWiki method) 135capitalize() (gluonutf8Utf8 method) 139cas_login() (gluontoolsAuth method) 123cas_validate() (gluontoolsAuth method) 123cast_keys() (in module gluonserializers) 83CAT (class in gluonhtml) 36CENTER (class in gluonhtml) 36center() (gluonutf8Utf8 method) 139change_password() (gluontoolsAuth method) 123check_credentials() (in module gluonfileutils) 26check_existent_app() (in module gluonwidget) 171check_interaction() (in module gluondebug) 22check_new_version() (in module gluonadmin) 4check_reserved_keyword() (gluonsqlDAL method) 92CheckboxesWidget (class in gluonsqlhtml) 97checkTaskBar() (gluonwidgetweb2pyDialog method)

171cleanpath() (in module gluonfileutils) 25CLEANUP (class in gluonvalidators) 145clear() (gluonglobalsSession method) 30clear_content() (gluontemplateContent method) 114clear_interaction() (gluondebugWebDebugger method)

21clear_session_cookies() (gluonglobalsSession method)

30clone() (gluonsqlDALField method) 91clone() (gluonsqlField method) 96close() (gluonportalockerLockedFile method) 65close() (gluonsqlDAL method) 92cloud() (gluontoolsWiki method) 135CODE (class in gluonhtml) 36COL (class in gluonhtml) 37COLGROUP (class in gluonhtml) 37commit() (gluonsqlDAL method) 92communicate() (in module gluondebug) 22

compare() (in module gluonutils) 143compile2() (in module gluonrestricted) 69compile_application() (in module gluoncompileapp) 12compile_controllers() (in module gluoncompileapp) 12compile_models() (in module gluoncompileapp) 12compile_regex() (in module gluonrewrite) 72compile_views() (in module gluoncompileapp) 12component() (gluontoolsWiki static method) 135compute_uuid() (gluonglobalsRequest method) 28confirm() (gluonhtmlFORM static method) 41confirm_registration() (gluontoolsAuth method) 123connect() (gluonglobalsSession method) 30connect_pages() (gluonwidgetweb2pyDialog method)

172console() (in module gluonwidget) 171Content (class in gluontemplate) 114content_type (gluonsqlhtmlExportClass attribute) 98content_type (gluonsqlhtmlExporterCSV attribute) 98content_type (gluonsqlhtmlExporterCSV_hidden

attribute) 98content_type (gluonsqlhtmlExporterHTML attribute)

98content_type (gluonsqlhtmlExporterJSON attribute) 98content_type (gluonsqlhtmlExporterTSV attribute) 99content_type (gluonsqlhtmlExporterXML attribute) 99contenttype() (in module gluoncontenttype) 15cookies2headers() (gluonhttpHTTP method) 51count() (gluonsqlDALField method) 91count() (gluonsqlField method) 96count() (gluonutf8Utf8 method) 139create() (gluontoolsCrud method) 130create() (gluontoolsWiki method) 135create_missing_app_folders() (in module gluonadmin) 5create_missing_folders() (in module gluonadmin) 5createform() (gluonsqlhtmlSQLFORM method) 102crondance() (in module gluonnewcron) 63cronlauncher (class in gluonnewcron) 63Crud (class in gluontools) 130CRYPT (class in gluonvalidators) 146csv() (gluontoolsService method) 132csv() (in module gluonserializers) 83custom_import_install() (in module

gluoncustom_import) 17custom_importer() (in module gluoncustom_import) 17custom_json() (in module gluonserializers) 83CustomImportException 17

DDAL (class in gluonsql) 89DALField (class in gluonsql) 91DALRow (class in gluonsql) 91DALTable (class in gluonsql) 92DatetimeWidget (class in gluonsqlhtml) 98DateWidget (class in gluonsqlhtml) 98

180 Index

web2py Documentation Release 2146-stable

DecimalWidget (class in gluonsqlhtml) 98decode() (gluonutf8Utf8 method) 139decoder() (in module gluondecoder) 23default_delimiters (gluontemplateTemplateParser

attribute) 115default_messages (gluontoolsAuth attribute) 123default_settings (gluontoolsAuth attribute) 124DEFAULT_WIDTH (gluonsqlhtmlUploadWidget

attribute) 104define_signature() (gluontoolsAuth method) 125define_table() (gluonsqlDAL method) 93define_tables() (gluonschedulerScheduler method) 79define_tables() (gluontoolsAuth method) 125del_group() (gluontoolsAuth method) 125del_membership() (gluontoolsAuth method) 125del_permission() (gluontoolsAuth method) 125delete() (gluontoolsCrud method) 130DELETE_FILE (gluonsqlhtmlUploadWidget attribute)

104dictform() (gluonsqlhtmlSQLFORM static method) 102die() (gluonschedulerMetaScheduler method) 78die() (in module gluonshell) 87disable() (gluonschedulerScheduler method) 79distributed_transaction_begin() (gluonsqlDAL static

method) 93distributed_transaction_commit() (gluonsqlDAL static

method) 93DIV (class in gluonhtml) 37do_continue() (gluondebugWebDebugger method) 21do_exec() (gluondebugWebDebugger method) 21do_next() (gluondebugWebDebugger method) 21do_quit() (gluondebugWebDebugger method) 21do_return() (gluondebugWebDebugger method) 21do_step() (gluondebugWebDebugger method) 21DoubleWidget (class in gluonsqlhtml) 98download() (gluonglobalsResponse method) 28drop() (gluonsqlDALTable method) 92DummyResponse (class in gluontemplate) 114

Eedit() (gluontoolsWiki method) 135editmedia() (gluontoolsWiki method) 135element() (gluonhtmlDIV method) 38elements() (gluonhtmlDIV method) 38elements() (gluonhtmlXML method) 49EM (class in gluonhtml) 40email_registration() (gluontoolsAuth method) 125email_reset_password() (gluontoolsAuth method) 125EMBED (class in gluonhtml) 40embed64() (in module gluonhtml) 50emit() (gluonmessageboxhandlerMessageBoxHandler

method) 59emit() (gluonmessageboxhandlerNotifySendHandler

method) 59

enable_autocomplete_and_history() (in modulegluonshell) 87

enable_record_versioning() (gluontoolsAuth method)125

encode() (gluonutf8Utf8 method) 140endswith() (gluonutf8Utf8 method) 140env() (in module gluonshell) 87error() (gluontoolsService method) 132error() (gluonwidgetweb2pyDialog method) 172everybody (gluontoolsWiki attribute) 135exception() (gluondebugWebDebugger method) 21exec_environment() (in module gluonshell) 87exec_pythonrc() (in module gluonshell) 87execute_from_command_line() (in module gluonshell)

87executesql() (gluonsqlDAL method) 93executor() (in module gluonscheduler) 82exists() (in module gluonrecfile) 67expandtabs() (gluonutf8Utf8 method) 140export() (gluonsqlhtmlExportClass method) 98export() (gluonsqlhtmlExporterCSV method) 98export() (gluonsqlhtmlExporterCSV_hidden method)

98export() (gluonsqlhtmlExporterHTML method) 98export() (gluonsqlhtmlExporterJSON method) 98export() (gluonsqlhtmlExporterTSV method) 99export() (gluonsqlhtmlExporterXML method) 99export_to_csv_file() (gluonsqlDAL method) 93ExportClass (class in gluonsqlhtml) 98ExporterCSV (class in gluonsqlhtml) 98ExporterCSV_hidden (class in gluonsqlhtml) 98ExporterHTML (class in gluonsqlhtml) 98ExporterJSON (class in gluonsqlhtml) 98ExporterTSV (class in gluonsqlhtml) 99ExporterXML (class in gluonsqlhtml) 99extcron (class in gluonnewcron) 63extend() (gluontemplateBlockNode method) 113extend() (gluontemplateContent method) 114extend() (gluontemplateTemplateParser method) 115

Ffactory() (gluonsqlhtmlSQLFORM static method) 102fast_urandom16() (in module gluonutils) 143fetch() (in module gluontools) 137Field (class in gluonsql) 95FIELDKEY_DELETE_RECORD

(gluonsqlhtmlSQLFORM attribute) 101FIELDNAME_REQUEST_DELETE

(gluonsqlhtmlSQLFORM attribute) 101fields (gluonsqlDALTable attribute) 92FIELDSET (class in gluonhtml) 40file_ext (gluonsqlhtmlExportClass attribute) 98file_ext (gluonsqlhtmlExporterCSV attribute) 98

Index 181

web2py Documentation Release 2146-stable

file_ext (gluonsqlhtmlExporterCSV_hidden attribute)98

file_ext (gluonsqlhtmlExporterHTML attribute) 98file_ext (gluonsqlhtmlExporterJSON attribute) 98file_ext (gluonsqlhtmlExporterTSV attribute) 99file_ext (gluonsqlhtmlExporterXML attribute) 99filter_err() (in module gluonrewrite) 72filter_url() (in module gluonrewrite) 72find() (gluonutf8Utf8 method) 140find_exposed_functions() (in module gluoncompileapp)

12findT() (in module gluonlanguages) 55first_paragraph() (gluontoolsWiki method) 135fix_hostname() (gluontoolsWiki method) 135fix_newlines() (in module gluonfileutils) 26fixup_missing_path_info() (in module gluonrewrite) 72flatten() (gluonhtmlDIV method) 39flatten() (gluonhtmlMARKMIN method) 44flatten() (gluonhtmlXML method) 49flush() (gluondebugPipe method) 21force() (gluonlanguagestranslator method) 53forget() (gluonglobalsSession method) 30FORM (class in gluonhtml) 40form_factory() (in module gluonsqlhtml) 104format() (gluonutf8Utf8 method) 140formatter() (gluonsqlDALField method) 91formatter() (gluonsqlField method) 96formatter() (gluonvalidatorsANY_OF method) 145formatter() (gluonvalidatorsIS_DATE method) 148formatter() (gluonvalidatorsIS_DATETIME method)

149formatter() (gluonvalidatorsIS_DECIMAL_IN_RANGE

method) 150formatter() (gluonvalidatorsIS_EMPTY_OR method)

152formatter() (gluonvalidatorsIS_FLOAT_IN_RANGE

method) 153formatter() (gluonvalidatorsIS_JSON method) 169formatter() (gluonvalidatorsIS_LIST_OF_EMAILS

method) 152formstyle_bootstrap() (in module gluonsqlhtml) 105formstyle_bootstrap3_inline_factory() (in module

gluonsqlhtml) 105formstyle_bootstrap3_stacked() (in module

gluonsqlhtml) 105formstyle_divs() (in module gluonsqlhtml) 105formstyle_inline() (in module gluonsqlhtml) 105formstyle_table2cols() (in module gluonsqlhtml) 105formstyle_table3cols() (in module gluonsqlhtml) 105formstyle_ul() (in module gluonsqlhtml) 105formstyles (gluonsqlhtmlSQLFORM attribute) 102FormWidget (class in gluonsqlhtml) 99frameset (gluonhtmlHTML attribute) 43frameset (gluonhtmlXHTML attribute) 49

Ggenerate() (in module gluonrecfile) 67GENERIC_DESCRIPTION

(gluonsqlhtmlUploadWidget attribute)104

geocode() (in module gluontools) 137get() (gluonhtmlDIV method) 39get() (gluonsqlDALRow method) 91get_callable_argspec() (in module gluonutils) 143get_code_for_scheduler() (in module gluonwidget) 171get_digest() (in module gluonutils) 143get_effective_router() (in module gluonrewrite) 72get_format() (gluontoolsCrud method) 130get_instances() (gluonsqlDAL static method) 93get_or_create_key() (gluontoolsAuth static method)

125get_or_create_user() (gluontoolsAuth method) 125get_parsed() (in module gluontemplate) 115get_possible_languages() (gluonlanguagestranslator

method) 54get_possible_languages_info()

(gluonlanguagestranslator method) 54get_query() (gluontoolsCrud method) 130get_renderer() (gluontoolsWiki method) 135get_session() (in module gluonfileutils) 26get_t() (gluonlanguagestranslator method) 54get_url() (in module gluonwidget) 171get_usage() (in module gluonshell) 87get_vars (gluonglobalsRequest attribute) 28get_vars_next() (gluontoolsAuth method) 126get_workers() (gluonschedulerScheduler method) 79getcfs() (in module gluoncfs) 9getfirst() (gluonstorageStorage method) 108getipaddrinfo() (in module gluonutils) 143getlast() (gluonstorageStorage method) 108getlist() (gluonstorageStorage method) 108give_up() (gluonschedulerMetaScheduler method) 78gluonadmin (module) 3gluoncache (module) 7gluoncfs (module) 9gluoncompileapp (module) 11gluoncontenttype (module) 15gluoncustom_import (module) 17gluondal (module) 19gluondebug (module) 21gluondecoder (module) 23gluonfileutils (module) 25gluonglobals (module) 27gluonhighlight (module) 33gluonhtml (module) 35gluonhttp (module) 51gluonlanguages (module) 53gluonmain (module) 57gluonmessageboxhandler (module) 59

182 Index

web2py Documentation Release 2146-stable

gluonmyregex (module) 61gluonnewcron (module) 63gluonportalocker (module) 65gluonrecfile (module) 67gluonrestricted (module) 69gluonrewrite (module) 71gluonsanitizer (module) 75gluonscheduler (module) 77gluonserializers (module) 83gluonsettings (module) 85gluonshell (module) 87gluonsql (module) 89gluonsqlhtml (module) 97gluonstorage (module) 107gluonstreamer (module) 111gluontemplate (module) 113gluontools (module) 117gluonutf8 (module) 139gluonutils (module) 143gluonvalidators (module) 145gluonwidget (module) 171gluonxmlrpc (module) 173grid() (gluonsqlhtmlSQLFORM static method) 102groups() (gluontoolsAuth method) 126

HH1 (class in gluonhtml) 42H2 (class in gluonhtml) 42H3 (class in gluonhtml) 42H4 (class in gluonhtml) 42H5 (class in gluonhtml) 42H6 (class in gluonhtml) 42handler() (in module gluonxmlrpc) 173hardcron (class in gluonnewcron) 64harg0 (gluonrewriteMapUrlIn attribute) 71has_membership() (gluontoolsAuth method) 126has_options() (gluonsqlhtmlOptionsWidget static

method) 100has_permission() (gluontoolsAuth method) 126has_permission() (gluontoolsCrud method) 130has_representer() (gluonsqlDAL method) 94HEAD (class in gluonhtml) 42here() (gluontoolsAuth method) 126hidden_fields() (gluonhtmlFORM method) 41highlight() (in module gluonhighlight) 33HR (class in gluonhtml) 42HTML (class in gluonhtml) 42html5 (gluonhtmlHTML attribute) 43html_render() (gluontoolsWiki method) 135HTTP 51HttpServer (class in gluonmain) 58

II (class in gluonhtml) 43

ics() (in module gluonserializers) 83ID_DELETE_SUFFIX (gluonsqlhtmlUploadWidget at-

tribute) 104id_group() (gluontoolsAuth method) 126ID_LABEL_SUFFIX (gluonsqlhtmlSQLFORM at-

tribute) 101ID_ROW_SUFFIX (gluonsqlhtmlSQLFORM attribute)

101IFRAME (class in gluonhtml) 43IMG (class in gluonhtml) 43impersonate() (gluontoolsAuth method) 126import_from_csv_file() (gluonsqlDAL method) 94import_from_csv_file() (gluonsqlDALTable method)

92import_table_definitions() (gluonsqlDAL method) 94include() (gluontemplateTemplateParser method) 115include_files() (gluonglobalsResponse method) 28include_meta() (gluonglobalsResponse method) 28index() (gluonutf8Utf8 method) 140initialize_urandom() (in module gluonutils) 143INPUT (class in gluonhtml) 43insert() (gluonhtmlDIV method) 40insert() (gluonsqlDALTable method) 92insert() (gluontemplateContent method) 114instances (gluontoolsPluginManager attribute) 137IntegerWidget (class in gluonsqlhtml) 99interaction() (gluondebugWebDebugger method) 22invalid_url() (in module gluonrewrite) 72IO (class in gluonwidget) 171IS_ALPHANUMERIC (class in gluonvalidators) 147IS_DATE (class in gluonvalidators) 148IS_DATE_IN_RANGE (class in gluonvalidators) 147IS_DATETIME (class in gluonvalidators) 148IS_DATETIME_IN_RANGE (class in gluonvalidators)

148IS_DECIMAL_IN_RANGE (class in gluonvalidators)

149IS_EMAIL (class in gluonvalidators) 150IS_EMPTY_OR (class in gluonvalidators) 152IS_EQUAL_TO (class in gluonvalidators) 163is_expired() (gluonglobalsSession method) 30IS_EXPR (class in gluonvalidators) 152IS_FLOAT_IN_RANGE (class in gluonvalidators) 153IS_IMAGE (class in gluonvalidators) 153is_image() (gluonsqlhtmlUploadWidget static method)

104is_impersonating() (gluontoolsAuth method) 126IS_IN_DB (class in gluonvalidators) 154IS_IN_SET (class in gluonvalidators) 154IS_INT_IN_RANGE (class in gluonvalidators) 155IS_IPADDRESS (class in gluonvalidators) 159IS_IPV4 (class in gluonvalidators) 156IS_IPV6 (class in gluonvalidators) 158IS_JSON (class in gluonvalidators) 169

Index 183

web2py Documentation Release 2146-stable

IS_LENGTH (class in gluonvalidators) 161IS_LIST_OF (class in gluonvalidators) 162IS_LIST_OF_EMAILS (class in gluonvalidators) 152is_logged_in() (gluontoolsAuth method) 126is_loopback_ip_address() (in module gluonutils) 144IS_LOWER (class in gluonvalidators) 162IS_MATCH (class in gluonvalidators) 162is_new() (gluonglobalsSession method) 30IS_NOT_EMPTY (class in gluonvalidators) 163IS_NOT_IN_DB (class in gluonvalidators) 164IS_NULL_OR (in module gluonvalidators) 164IS_SLUG (class in gluonvalidators) 164IS_STRONG (class in gluonvalidators) 165IS_TIME (class in gluonvalidators) 166is_tracking_changes() (in module gluoncustom_import)

17IS_UPLOAD_FILENAME (class in gluonvalidators)

166IS_UPPER (class in gluonvalidators) 167IS_URL (class in gluonvalidators) 167is_valid_ip_address() (in module gluonutils) 144isalnum() (gluonutf8Utf8 method) 140isalpha() (gluonutf8Utf8 method) 140isdigit() (gluonutf8Utf8 method) 140islower() (gluonutf8Utf8 method) 140isodatetime (gluonvalidatorsIS_DATETIME attribute)

149isspace() (gluonutf8Utf8 method) 140istitle() (gluonutf8Utf8 method) 140isupper() (gluonutf8Utf8 method) 140

JJobGraph (class in gluonscheduler) 77join() (gluonutf8Utf8 method) 140json() (gluonglobalsResponse method) 28json() (gluontoolsService method) 132json() (in module gluonserializers) 83jsonrpc() (gluontoolsService method) 132jsonrpc2() (gluontoolsService method) 132jsonrpc_errors (gluontoolsService attribute) 133JSONWidget (class in gluonsqlhtml) 99jwt() (gluontoolsAuth method) 126

Kkeys() (gluontoolsPluginManager method) 137kill() (gluonschedulerScheduler method) 79

LLABEL (class in gluonhtml) 44label (gluonsqlhtmlExportClass attribute) 98label (gluonsqlhtmlExporterCSV attribute) 98label (gluonsqlhtmlExporterCSV_hidden attribute) 98label (gluonsqlhtmlExporterHTML attribute) 98label (gluonsqlhtmlExporterJSON attribute) 98

label (gluonsqlhtmlExporterTSV attribute) 99label (gluonsqlhtmlExporterXML attribute) 99launch() (gluonnewcronhardcron method) 64Lazy (gluonsqlDALField attribute) 91Lazy (gluonsqlField attribute) 95lazy_cache() (in module gluoncache) 8lazy_define_table() (gluonsqlDAL method) 94LEGEND (class in gluonhtml) 44LI (class in gluonhtml) 44LINK (class in gluonhtml) 44List (class in gluonstorage) 107listdir() (in module gluonfileutils) 25ListWidget (class in gluonsqlhtml) 99ljust() (gluonutf8Utf8 method) 140load() (gluonrestrictedRestrictedError method) 69load() (gluonrestrictedTicketStorage method) 69LOAD() (in module gluoncompileapp) 11load() (in module gluonrewrite) 72load_routers() (in module gluonrewrite) 73load_storage() (in module gluonstorage) 109LoadFactory (class in gluoncompileapp) 12loads_json() (in module gluonserializers) 83loads_yaml() (in module gluonserializers) 83local_import_aux() (in module gluoncompileapp) 12localhost (gluonvalidatorsIS_IPV4 attribute) 158lock() (in module gluonportalocker) 66LockedFile (class in gluonportalocker) 65log() (gluonrestrictedRestrictedError method) 69log_event() (gluontoolsAuth method) 127log_event() (gluontoolsCrud method) 130log_rewrite() (in module gluonrewrite) 73logger (gluonsqlDAL attribute) 94login() (gluontoolsAuth method) 127login_bare() (gluontoolsAuth method) 127login_user() (gluontoolsAuth method) 127logout() (gluontoolsAuth method) 127logout_bare() (gluontoolsAuth method) 127loop() (gluonschedulerMetaScheduler method) 78loop() (gluonschedulerScheduler method) 79lower() (gluonutf8Utf8 method) 141lstrip() (gluonutf8Utf8 method) 141

MM() (gluonlanguagestranslator method) 53Mail (class in gluontools) 117MailAttachment (class in gluontools) 118main() (in module gluonscheduler) 82make_fake_file_like_object() (in module gluonfileutils)

26manage_tokens() (gluontoolsAuth method) 127map_app() (gluonrewriteMapUrlIn method) 71map_controller() (gluonrewriteMapUrlIn method) 71map_function() (gluonrewriteMapUrlIn method) 71map_language() (gluonrewriteMapUrlIn method) 71

184 Index

web2py Documentation Release 2146-stable

map_prefix() (gluonrewriteMapUrlIn method) 71map_root_static() (gluonrewriteMapUrlIn method) 72map_static() (gluonrewriteMapUrlIn method) 72map_url_in() (in module gluonrewrite) 73map_url_out() (in module gluonrewrite) 73MapUrlIn (class in gluonrewrite) 71MapUrlOut (class in gluonrewrite) 72MARKMIN (class in gluonhtml) 44markmin_base() (gluontoolsWiki method) 135markmin_render() (gluontoolsWiki method) 135maybe_add() (gluonvalidatorsIS_IN_DB method) 154md5_hash() (in module gluonutils) 144media() (gluontoolsWiki method) 135MENU (class in gluonhtml) 44menu() (gluontoolsWiki method) 135message (gluonhttpHTTP attribute) 51MessageBoxHandler (class in

gluonmessageboxhandler) 59Messages (class in gluonstorage) 108META (class in gluonhtml) 45MetaScheduler (class in gluonscheduler) 77Method (gluonsqlDALField attribute) 91Method (gluonsqlField attribute) 95mktree() (in module gluonfileutils) 25model_cmp() (in module gluoncompileapp) 12model_cmp_sep() (in module gluoncompileapp) 12MultipleOptionsWidget (class in gluonsqlhtml) 99mybuiltin (class in gluoncompileapp) 12

Nnavbar() (gluontoolsAuth method) 127nice() (gluonvalidatorsIS_DATETIME static method)

149no_underscore() (gluonhtmlBEAUTIFY static method)

36Node (class in gluontemplate) 114NOESCAPE (class in gluontemplate) 114not_authorized() (gluontoolsAuth method) 127not_authorized() (gluontoolsWiki method) 135NotifySendHandler (class in gluonmessageboxhandler)

59now() (gluonschedulerScheduler method) 79numbers (gluonvalidatorsIS_IPV4 attribute) 158

OOBJECT (class in gluonhtml) 45OL (class in gluonhtml) 44omit_acf() (gluonrewriteMapUrlOut method) 72omit_lang() (gluonrewriteMapUrlOut method) 72on() (gluonsqlDALTable method) 92open() (in module gluonrecfile) 67OPTGROUP (class in gluonhtml) 45OPTION (class in gluonhtml) 45options() (gluonvalidatorsIS_IN_DB method) 154

options() (gluonvalidatorsIS_IN_SET method) 155OptionsWidget (class in gluonsqlhtml) 100output() (gluontemplateBlockNode method) 113output_aux() (in module gluontemplate) 115

PP (class in gluonhtml) 45PACKAGE_PATH_SUFFIX

(gluoncustom_importTrackImporter at-tribute) 17

pad() (in module gluonutils) 144pages() (gluontoolsWiki method) 136params_substitution() (gluonlanguagestranslator

method) 54parse() (gluontemplateTemplateParser method) 115parse_all_vars() (gluonglobalsRequest method) 28parse_as_rest() (gluonsqlDAL method) 94parse_get_vars() (gluonglobalsRequest method) 28parse_path_info() (in module gluonshell) 87parse_post_vars() (gluonglobalsRequest method) 28parse_template() (in module gluontemplate) 115parse_version() (in module gluonfileutils) 25parsecronline() (in module gluonnewcron) 64partition() (gluonutf8Utf8 method) 141PasswordWidget (class in gluonsqlhtml) 100pbkdf2_hex() (in module gluonutils) 144Pipe (class in gluondebug) 21plugin_install() (in module gluonadmin) 5plugin_pack() (in module gluonadmin) 5PluginManager (class in gluontools) 136plural() (gluonlanguagestranslator method) 55pop_arg_if() (gluonrewriteMapUrlIn method) 72pop_task() (gluonschedulerMetaScheduler method) 78pop_task() (gluonschedulerScheduler method) 79post_vars (gluonglobalsRequest attribute) 28PRE (class in gluonhtml) 45prettydate() (in module gluontools) 137preview() (gluontoolsWiki method) 136private (gluonvalidatorsIS_IPV4 attribute) 158process() (gluonhtmlFORM method) 41profile() (gluontoolsAuth method) 127

Qqueue_task() (gluonschedulerScheduler method) 79quit() (gluonwidgetweb2pyDialog method) 172

Rr_multiline (gluontemplateTemplateParser attribute)

115r_tag (gluontemplateTemplateParser attribute) 115RadioWidget (class in gluonsqlhtml) 100random_password() (gluontoolsAuth method) 127rangetolist() (in module gluonnewcron) 64re_block (gluontemplateTemplateParser attribute) 115

Index 185

web2py Documentation Release 2146-stable

re_compile() (in module gluoncompileapp) 12re_pass (gluontemplateTemplateParser attribute) 115re_unblock (gluontemplateTemplateParser attribute)

115read() (gluondebugPipe method) 21read() (gluonportalockerLockedFile method) 66read() (gluontoolsCrud method) 130read() (gluontoolsWiki method) 136read_file() (in module gluonfileutils) 25read_locked() (in module gluonportalocker) 66read_pyc() (in module gluoncompileapp) 12readline() (gluondebugPipe method) 21readline() (gluonportalockerLockedFile method) 66readlines() (gluonportalockerLockedFile method) 66readlines_file() (in module gluonfileutils) 25Recaptcha (class in gluontools) 129Recaptcha2 (class in gluontools) 129recursive_unlink() (in module gluonfileutils) 25redirect() (in module gluonhttp) 51REDIRECT_JS (gluonhtmlFORM attribute) 41regex (gluonvalidatorsIS_EMAIL attribute) 151regex (gluonvalidatorsIS_IPV4 attribute) 158regex_attr (gluonhtmlDIV attribute) 40regex_class (gluonhtmlDIV attribute) 40REGEX_CLEANUP (gluonvalidatorsCLEANUP

attribute) 146regex_filter_in() (in module gluonrewrite) 73regex_filter_out() (in module gluonrewrite) 73regex_id (gluonhtmlDIV attribute) 40regex_proposed_but_failed (gluonvalidatorsIS_EMAIL

attribute) 151regex_select() (in module gluonrewrite) 73regex_tag (gluonhtmlDIV attribute) 40regex_uri() (in module gluonrewrite) 73regex_url_in() (in module gluonrewrite) 73register() (gluontoolsAuth method) 127register_bare() (gluontoolsAuth method) 127reindent() (gluontemplateTemplateParser method) 115release() (gluonnewcronToken method) 63remove() (in module gluonrecfile) 67remove_compiled_application() (in module

gluoncompileapp) 12render() (gluonglobalsResponse method) 28render() (in module gluontemplate) 115render_tags() (gluontoolsWiki method) 136renew() (gluonglobalsSession method) 30replace() (gluonutf8Utf8 method) 141report_task() (gluonschedulerMetaScheduler method)

78report_task() (gluonschedulerScheduler method) 80represent() (gluonsqlDAL method) 94represent() (gluonsqlhtmlUploadWidget class method)

104represent() (in module gluonsqlhtml) 105

represented() (gluonsqlhtmlExportClass method) 98representers (gluonsqlDAL attribute) 94Request (class in gluonglobals) 27request_reset_password() (gluontoolsAuth method) 127requires() (gluontoolsAuth method) 127requires_https() (gluonglobalsRequest method) 28requires_login() (gluontoolsAuth method) 127requires_login_or_token() (gluontoolsAuth method)

127requires_membership() (gluontoolsAuth method) 128requires_permission() (gluontoolsAuth method) 128requires_signature() (gluontoolsAuth method) 128reset_password() (gluontoolsAuth method) 128reset_password_deprecated() (gluontoolsAuth method)

128Response (class in gluonglobals) 28restful() (gluonglobalsRequest method) 28restricted() (in module gluonrestricted) 69RestrictedError 69resume() (gluonschedulerScheduler method) 80retrieve() (gluonsqlDALField method) 91retrieve() (gluonsqlField method) 96retrieve_file_properties() (gluonsqlDALField method)

91retrieve_file_properties() (gluonsqlField method) 96retrieve_password() (gluontoolsAuth method) 128retrieve_username() (gluontoolsAuth method) 128reverse_geocode() (in module gluontools) 137rfind() (gluonutf8Utf8 method) 141rindex() (gluonutf8Utf8 method) 141rjust() (gluonutf8Utf8 method) 141rollback() (gluonsqlDAL method) 94rows() (gluontoolsCrud method) 130rows_page (gluontoolsWiki attribute) 136rpartition() (gluonutf8Utf8 method) 141rsplit() (gluonutf8Utf8 method) 141rss() (gluontoolsService method) 133rss() (in module gluonserializers) 83rstrip() (gluonutf8Utf8 method) 141run() (gluondebugWebDebugger method) 22run() (gluonnewcroncronlauncher method) 63run() (gluonnewcronextcron method) 64run() (gluonnewcronhardcron method) 64run() (gluonnewcronsoftcron method) 64run() (gluonschedulerMetaScheduler method) 78run() (gluontoolsService method) 133run() (in module gluonshell) 88run_controller_in() (in module gluoncompileapp) 13run_login_onaccept() (gluontoolsAuth method) 128run_models_in() (in module gluoncompileapp) 13run_system_tests() (in module gluonwidget) 171run_view_in() (in module gluoncompileapp) 13

186 Index

web2py Documentation Release 2146-stable

Ssafe_encode() (in module gluonserializers) 83safe_float() (in module gluonsqlhtml) 105safe_int() (in module gluonsqlhtml) 105sanitize() (in module gluonsanitizer) 75save_password() (in module gluonmain) 58save_pyc() (in module gluoncompileapp) 13save_session_id_cookie() (gluonglobalsSession

method) 31save_storage() (in module gluonstorage) 109Scheduler (class in gluonscheduler) 78SCRIPT (class in gluonhtml) 45search() (gluontoolsCrud method) 130search() (gluontoolsWiki method) 136search_menu() (gluonsqlhtmlSQLFORM static

method) 102secure() (gluonglobalsSession method) 31secure_dumps() (in module gluonutils) 144secure_loads() (in module gluonutils) 144SELECT (class in gluonhtml) 45select() (gluontoolsCrud method) 131select_host() (gluontoolsAuth method) 128send() (gluontoolsMail method) 119send_heartbeat() (gluonschedulerMetaScheduler

method) 78send_heartbeat() (gluonschedulerScheduler method) 80serialize() (gluonhtmlMENU method) 45serialize_mobile() (gluonhtmlMENU method) 45serializers (gluonsqlDAL attribute) 95serve_amfrpc() (gluontoolsService method) 133serve_csv() (gluontoolsService method) 134serve_json() (gluontoolsService method) 134serve_jsonrpc() (gluontoolsService method) 134serve_jsonrpc2() (gluontoolsService method) 134serve_rss() (gluontoolsService method) 134serve_run() (gluontoolsService method) 134serve_soap() (gluontoolsService method) 134serve_xml() (gluontoolsService method) 134serve_xmlrpc() (gluontoolsService method) 134server_ready() (gluonwidgetweb2pyDialog method)

172Service (class in gluontools) 131ServiceJsonRpcException 131Session (class in gluonglobals) 29set_attributes() (gluonsqlDALField method) 91set_attributes() (gluonsqlField method) 96set_current_languages() (gluonlanguagestranslator

method) 55set_folder() (gluonsqlDAL static method) 95set_requirements() (gluonschedulerScheduler method)

80set_self_id() (gluonvalidatorsIS_EMPTY_OR method)

152set_self_id() (gluonvalidatorsIS_IN_DB method) 154

set_self_id() (gluonvalidatorsIS_NOT_IN_DB method)164

set_trace() (in module gluondebug) 22set_worker_status() (gluonschedulerScheduler method)

80Settings (class in gluonstorage) 108show_if() (in module gluonsqlhtml) 105sibling() (gluonhtmlDIV method) 40siblings() (gluonhtmlDIV method) 40simple_hash() (in module gluonutils) 144sleep() (gluonschedulerMetaScheduler method) 78sleep() (gluonschedulerScheduler method) 80sluggify() (gluonrewriteMapUrlIn method) 72sluggify() (in module gluonrewrite) 73smart_query() (gluonsqlDAL method) 95smartdictform() (gluonsqlhtmlSQLFORM static

method) 102smartgrid() (gluonsqlhtmlSQLFORM static method)

102soap() (gluontoolsService method) 134softcron (class in gluonnewcron) 64SPAN (class in gluonhtml) 46split() (gluonutf8Utf8 method) 141split_emails (gluonvalidatorsIS_LIST_OF_EMAILS at-

tribute) 152splitlines() (gluonutf8Utf8 method) 141SQLFORM (class in gluonsqlhtml) 100sqlsafe (gluonsqlDALField attribute) 91sqlsafe (gluonsqlDALTable attribute) 92sqlsafe (gluonsqlField attribute) 96sqlsafe_alias (gluonsqlDALTable attribute) 92sqlsafe_name (gluonsqlDALField attribute) 91sqlsafe_name (gluonsqlField attribute) 96SQLTABLE (class in gluonsqlhtml) 103start() (gluonmainHttpServer method) 58start() (gluonwidgetweb2pyDialog method) 172start() (in module gluonwidget) 171start_browser() (in module gluonwidget) 171start_heartbeats() (gluonschedulerMetaScheduler

method) 78start_schedulers() (gluonwidgetweb2pyDialog method)

172start_schedulers() (in module gluonwidget) 171startswith() (gluonutf8Utf8 method) 141stop() (gluonmainHttpServer method) 58stop() (gluonwidgetweb2pyDialog method) 172stop_task() (gluonschedulerScheduler method) 80stop_trace() (in module gluondebug) 22stopcron() (in module gluonnewcron) 64Storage (class in gluonstorage) 107StorageList (class in gluonstorage) 109store() (gluonrestrictedTicketStorage method) 69store() (gluonsqlDALField method) 91store() (gluonsqlField method) 96

Index 187

web2py Documentation Release 2146-stable

stream() (gluonglobalsResponse method) 28stream_file_or_304_or_206() (in module

gluonstreamer) 111streamer() (in module gluonstreamer) 111strict (gluonhtmlHTML attribute) 43strict (gluonhtmlXHTML attribute) 49StringWidget (class in gluonsqlhtml) 103strip() (gluonutf8Utf8 method) 141STRONG (class in gluonhtml) 46STYLE (class in gluonhtml) 46style() (gluonsqlhtmlSQLTABLE method) 103SuperNode (class in gluontemplate) 114swapcase() (gluonutf8Utf8 method) 142

TTABLE (class in gluonhtml) 46table_cas() (gluontoolsAuth method) 128table_event() (gluontoolsAuth method) 128table_group() (gluontoolsAuth method) 128table_membership() (gluontoolsAuth method) 128table_permission() (gluontoolsAuth method) 128table_token() (gluontoolsAuth method) 128table_user() (gluontoolsAuth method) 128tables (gluonsqlDAL attribute) 95tables() (gluontoolsCrud method) 131tag (gluonhtmlA attribute) 35tag (gluonhtmlB attribute) 36tag (gluonhtmlBEAUTIFY attribute) 36tag (gluonhtmlBODY attribute) 36tag (gluonhtmlBR attribute) 36tag (gluonhtmlBUTTON attribute) 36tag (gluonhtmlCAT attribute) 36tag (gluonhtmlCENTER attribute) 36tag (gluonhtmlCOL attribute) 37tag (gluonhtmlCOLGROUP attribute) 37tag (gluonhtmlDIV attribute) 40tag (gluonhtmlEM attribute) 40tag (gluonhtmlEMBED attribute) 40tag (gluonhtmlFIELDSET attribute) 40tag (gluonhtmlFORM attribute) 41tag (gluonhtmlH1 attribute) 42tag (gluonhtmlH2 attribute) 42tag (gluonhtmlH3 attribute) 42tag (gluonhtmlH4 attribute) 42tag (gluonhtmlH5 attribute) 42tag (gluonhtmlH6 attribute) 42tag (gluonhtmlHEAD attribute) 42tag (gluonhtmlHR attribute) 42tag (gluonhtmlHTML attribute) 43tag (gluonhtmlI attribute) 43tag (gluonhtmlIFRAME attribute) 43tag (gluonhtmlIMG attribute) 43tag (gluonhtmlINPUT attribute) 44tag (gluonhtmlLABEL attribute) 44

tag (gluonhtmlLEGEND attribute) 44tag (gluonhtmlLI attribute) 44tag (gluonhtmlLINK attribute) 44tag (gluonhtmlMENU attribute) 45tag (gluonhtmlMETA attribute) 45tag (gluonhtmlOBJECT attribute) 45tag (gluonhtmlOL attribute) 44tag (gluonhtmlOPTGROUP attribute) 45tag (gluonhtmlOPTION attribute) 45tag (gluonhtmlP attribute) 45tag (gluonhtmlPRE attribute) 45tag (gluonhtmlSCRIPT attribute) 45tag (gluonhtmlSELECT attribute) 46tag (gluonhtmlSPAN attribute) 46tag (gluonhtmlSTRONG attribute) 46tag (gluonhtmlSTYLE attribute) 46tag (gluonhtmlTABLE attribute) 46tag (gluonhtmlTBODY attribute) 47tag (gluonhtmlTD attribute) 46tag (gluonhtmlTEXTAREA attribute) 46tag (gluonhtmlTFOOT attribute) 47tag (gluonhtmlTH attribute) 47tag (gluonhtmlTHEAD attribute) 47tag (gluonhtmlTITLE attribute) 47tag (gluonhtmlTR attribute) 47tag (gluonhtmlTT attribute) 47tag (gluonhtmlUL attribute) 44tag (gluonhtmlXHTML attribute) 49TAG (in module gluonhtml) 46tar() (in module gluonfileutils) 26tar_compiled() (in module gluonfileutils) 26Task (class in gluonscheduler) 81task_status() (gluonschedulerScheduler method) 81TaskReport (class in gluonscheduler) 82TBODY (class in gluonhtml) 47TD (class in gluonhtml) 46TemplateParser (class in gluontemplate) 114terminate() (gluonschedulerScheduler method) 81terminate_process() (gluonschedulerMetaScheduler

method) 78test() (in module gluoncompileapp) 13test() (in module gluonshell) 88TEXTAREA (class in gluonhtml) 46TextWidget (class in gluonsqlhtml) 103TFOOT (class in gluonhtml) 47TH (class in gluonhtml) 46THEAD (class in gluonhtml) 47THREAD_LOCAL (gluoncustom_importTrackImporter

attribute) 17TicketStorage (class in gluonrestricted) 69TimeWidget (class in gluonsqlhtml) 104TITLE (class in gluonhtml) 47title() (gluonutf8Utf8 method) 142to() (gluonhttpHTTP method) 51

188 Index

web2py Documentation Release 2146-stable

to_string() (gluontemplateTemplateParser method) 115Token (class in gluonnewcron) 63toolbar() (gluonglobalsResponse method) 29total_seconds() (gluonschedulerScheduler static

method) 81TR (class in gluonhtml) 47track_changes() (in module gluoncustom_import) 17TrackImporter (class in gluoncustom_import) 17transitional (gluonhtmlHTML attribute) 43transitional (gluonhtmlXHTML attribute) 49translate() (gluonlanguagestranslator method) 55translate() (gluonutf8Utf8 method) 142translator (class in gluonlanguages) 53truncate() (gluonsqlDALTable method) 92try_redirect_on_error() (in module gluonrewrite) 73try_rewrite_on_error() (in module gluonrewrite) 73try_start_scheduler() (gluonwidgetweb2pyDialog

method) 172try_stop_scheduler() (gluonwidgetweb2pyDialog

method) 172TT (class in gluonhtml) 47TYPE (class in gluonscheduler) 81

UUL (class in gluonhtml) 44unlock() (in module gluonportalocker) 66untar() (in module gluonfileutils) 26unzip() (in module gluonadmin) 5up() (in module gluonfileutils) 25update() (gluonhtmlDIV method) 40update() (gluonsqlDALTable method) 92update() (gluontoolsCrud method) 131update() (gluonwidgetweb2pyDialog method) 172update_all_languages() (in module gluonlanguages) 55update_canvas() (gluonwidgetweb2pyDialog method)

172update_dependencies() (gluonschedulerScheduler

method) 81update_groups() (gluontoolsAuth method) 128update_or_insert() (gluonsqlDALTable method) 92update_request() (gluonrewriteMapUrlIn method) 72update_schedulers() (gluonwidgetweb2pyDialog

method) 172upgrade() (in module gluonadmin) 5UploadWidget (class in gluonsqlhtml) 104upper() (gluonutf8Utf8 method) 142url() (gluontoolsAuth method) 128url() (gluontoolsCrud method) 131URL() (in module gluonhtml) 47url_in() (in module gluonrewrite) 73url_out() (in module gluonrewrite) 73urlify() (gluonvalidatorsIS_SLUG static method) 165user_agent() (gluonglobalsRequest method) 28user_group() (gluontoolsAuth method) 128

user_group_role() (gluontoolsAuth method) 128user_id (gluontoolsAuth attribute) 128Utf8 (class in gluonutf8) 139uuid (gluonglobalsRequest attribute) 28uuid() (gluonsqlDAL method) 95

Vvalidate() (gluonhtmlFORM method) 41validate() (gluonschedulerJobGraph method) 77validate() (gluonsqlDALField method) 91validate() (gluonsqlField method) 96validate_and_insert() (gluonsqlDALTable method) 92validate_and_update() (gluonsqlDALTable method) 92validate_and_update_or_insert() (gluonsqlDALTable

method) 92validate_args() (gluonrewriteMapUrlIn method) 72validators (gluonsqlDAL attribute) 95validators_method() (gluonsqlDAL method) 95vars (gluonglobalsRequest attribute) 28verify_email() (gluontoolsAuth method) 128VERIFY_SERVER (gluontoolsRecaptcha attribute)

129VERIFY_SERVER (gluontoolsRecaptcha2 attribute)

130Virtual (gluonsqlDALField attribute) 91Virtual (gluonsqlField attribute) 96

Ww2p_pack() (in module gluonfileutils) 26w2p_pack_plugin() (in module gluonfileutils) 26w2p_unpack() (in module gluonfileutils) 26w2p_unpack_plugin() (in module gluonfileutils) 26web2py_uuid() (in module gluonutils) 144web2pyDialog (class in gluonwidget) 171WebDebugger (class in gluondebug) 21when_is_logged_in_bypass_next_in_url()

(gluontoolsAuth method) 128where() (gluonsqlDAL method) 95widget() (gluonsqlhtmlBooleanWidget class method)

97widget() (gluonsqlhtmlCheckboxesWidget class

method) 97widget() (gluonsqlhtmlFormWidget class method) 99widget() (gluonsqlhtmlJSONWidget class method) 99widget() (gluonsqlhtmlListWidget class method) 99widget() (gluonsqlhtmlMultipleOptionsWidget class

method) 100widget() (gluonsqlhtmlOptionsWidget class method)

100widget() (gluonsqlhtmlPasswordWidget class method)

100widget() (gluonsqlhtmlRadioWidget class method) 100widget() (gluonsqlhtmlStringWidget class method) 103widget() (gluonsqlhtmlTextWidget class method) 104

Index 189

web2py Documentation Release 2146-stable

widget() (gluonsqlhtmlUploadWidget class method)104

widgets (gluonsqlhtmlSQLFORM attribute) 103Wiki (class in gluontools) 135wiki() (gluontoolsAuth method) 129wikimenu() (gluontoolsAuth method) 129with_alias() (gluonsqlDALTable method) 92with_prefix() (gluoncacheCache static method) 8wrapped_assign_tasks() (gluonschedulerScheduler

method) 81wrapped_pop_task() (gluonschedulerScheduler

method) 81wrapped_report_task() (gluonschedulerScheduler

method) 81write() (gluondebugPipe method) 21write() (gluonglobalsResponse method) 29write() (gluonportalockerLockedFile method) 66write() (gluontemplateDummyResponse method) 114write() (gluonwidgetIO method) 171write_file() (in module gluonfileutils) 25write_locked() (in module gluonportalocker) 66wsgibase() (in module gluonmain) 57

XXHTML (class in gluonhtml) 49XML (class in gluonhtml) 49xml() (gluonhtmlA method) 35xml() (gluonhtmlCODE method) 37xml() (gluonhtmlDIV method) 40xml() (gluonhtmlFORM method) 42xml() (gluonhtmlHTML method) 43xml() (gluonhtmlINPUT method) 44xml() (gluonhtmlMARKMIN method) 44xml() (gluonhtmlMENU method) 45xml() (gluonhtmlP method) 45xml() (gluonhtmlSCRIPT method) 45xml() (gluonhtmlSTYLE method) 46xml() (gluonhtmlXHTML method) 49xml() (gluonhtmlXML method) 50xml() (gluontemplateNOESCAPE method) 114xml() (gluontoolsRecaptcha method) 129xml() (gluontoolsRecaptcha2 method) 130xml() (gluontoolsService method) 134xml() (in module gluonserializers) 83xml_rec() (in module gluonserializers) 83xmlescape() (in module gluonhtml) 50xmlns (gluonhtmlXHTML attribute) 49xmlrpc() (gluonglobalsResponse method) 29xmlrpc() (gluontoolsService method) 134

Yyaml() (in module gluonserializers) 83

Zzfill() (gluonutf8Utf8 method) 142

190 Index

  • admin Module
    • Utility functions for the Admin application
      • cache Module
        • Basic caching classes and methods
          • cfs Module
            • Functions required to execute app components
              • compileapp Module
                • Functions required to execute app components
                  • contenttype Module
                  • custom_import Module
                    • Support for smart import syntax for web2py applications
                      • dal Module
                        • Takes care of adapting pyDAL to web2pyrsquos needs
                          • debug Module
                            • Debugger support classes
                              • decoder Module
                              • fileutils Module
                                • File operations
                                  • globals Module
                                  • highlight Module
                                  • html Module
                                    • Template helpers
                                      • http Module
                                        • HTTP statuses helpers
                                          • languages Module
                                            • Translation system
                                              • main Module
                                                • The gluon wsgi application
                                                  • messageboxhandler Module
                                                  • myregex Module
                                                    • Useful regexes
                                                      • newcron Module
                                                      • portalocker Module
                                                      • recfile Module
                                                        • Generates names for cache and session files
                                                          • restricted Module
                                                            • Restricted environment to execute applicationrsquos code
                                                              • rewrite Module
                                                              • sanitizer Module
                                                                • Cross-site scripting (XSS) defense
                                                                  • scheduler Module
                                                                    • Background processes made simple
                                                                      • serializers Module
                                                                      • settings Module
                                                                      • shell Module
                                                                        • Web2py environment in the shell
                                                                          • sql Module
                                                                            • Just for backward compatibility
                                                                              • sqlhtml Module
                                                                              • storage Module
                                                                              • streamer Module
                                                                                • Facilities to handle file streaming
                                                                                  • template Module
                                                                                    • Templating syntax
                                                                                      • tools Module
                                                                                        • Auth Mail PluginManager and various utilities
                                                                                          • utf8 Module
                                                                                            • Utilities and class for UTF8 strings managing
                                                                                              • utils Module
                                                                                                • This file specifically includes utilities for security
                                                                                                  • validators Module
                                                                                                    • Validators
                                                                                                      • widget Module
                                                                                                        • The widget is called from web2py
                                                                                                          • xmlrpc Module
                                                                                                          • Indices and tables
                                                                                                          • Python Module Index
Page 2: web2py Documentation - Read the Docs

Contents

1 admin Module 311 Utility functions for the Admin application 3

2 cache Module 721 Basic caching classes and methods 7

3 cfs Module 931 Functions required to execute app components 9

4 compileapp Module 1141 Functions required to execute app components 11

5 contenttype Module 15

6 custom_import Module 1761 Support for smart import syntax for web2py applications 17

7 dal Module 1971 Takes care of adapting pyDAL to web2pyrsquos needs 19

8 debug Module 2181 Debugger support classes 21

9 decoder Module 23

10 fileutils Module 25101 File operations 25

11 globals Module 27

12 highlight Module 33

13 html Module 35131 Template helpers 35

14 http Module 51141 HTTP statuses helpers 51

i

15 languages Module 53151 Translation system 53

16 main Module 57161 The gluon wsgi application 57

17 messageboxhandler Module 59

18 myregex Module 61181 Useful regexes 61

19 newcron Module 63

20 portalocker Module 65

21 recfile Module 67211 Generates names for cache and session files 67

22 restricted Module 69221 Restricted environment to execute applicationrsquos code 69

23 rewrite Module 71

24 sanitizer Module 75241 Cross-site scripting (XSS) defense 75

25 scheduler Module 77251 Background processes made simple 77

26 serializers Module 83

27 settings Module 85

28 shell Module 87281 Web2py environment in the shell 87

29 sql Module 89291 Just for backward compatibility 89

30 sqlhtml Module 97

31 storage Module 107

32 streamer Module 111321 Facilities to handle file streaming 111

33 template Module 113331 Templating syntax 113

34 tools Module 117341 Auth Mail PluginManager and various utilities 117

35 utf8 Module 139351 Utilities and class for UTF8 strings managing 139

36 utils Module 143361 This file specifically includes utilities for security 143

ii

37 validators Module 145371 Validators 145

38 widget Module 171381 The widget is called from web2py 171

39 xmlrpc Module 173

40 Indices and tables 175

Python Module Index 177

iii

iv

web2py Documentation Release 2146-stable

Contents

Contents 1

web2py Documentation Release 2146-stable

2 Contents

CHAPTER 1

admin Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

11 Utility functions for the Admin application

gluonadminadd_path_first(path)

gluonadminapath(path=rdquo r=None)Builds a path inside an application folder

Parameters

bull path (str) ndash path within the application folder

bull r ndash the global request object

gluonadminapp_cleanup(app request)Removes session cache and error files

Parameters

bull app (str) ndash application name

bull request ndash the global request object

Returns True if everything went ok False otherwise

gluonadminapp_compile(app request skip_failed_views=False)Compiles the application

Parameters

bull app (str) ndash application name

bull request ndash the global request object

3

web2py Documentation Release 2146-stable

Returns None if everything went ok traceback text if errors are found

gluonadminapp_create(app request force=False key=None info=False)Create a copy of welcomew2p (scaffolding) app

Parameters

bull app (str) ndash application name

bull request ndash the global request object

gluonadminapp_install(app fobj request filename overwrite=None)Installs an application

bull Identifies file type by filename

bull Writes fobj contents to the deposit folder

bull Calls w2p_unpack() to do the job

Parameters

bull app (str) ndash new application name

bull fobj (obj) ndash file object containing the application to be installed

bull request ndash the global request object

bull filename (str) ndash original filename of the fobj required to determine extension

bull overwrite (bool) ndash force overwrite of existing application

Returns name of the file where app is temporarily stored or None on failure

gluonadminapp_pack(app request raise_ex=False filenames=None)Builds a w2p package for the application

Parameters

bull app (str) ndash application name

bull request ndash the global request object

Returns filename of the w2p file or None on error

gluonadminapp_pack_compiled(app request raise_ex=False)Builds a w2p bytecode-compiled package for the application

Parameters

bull app (str) ndash application name

bull request ndash the global request object

Returns filename of the w2p file or None on error

gluonadminapp_uninstall(app request)Uninstalls the application

Parameters

bull app (str) ndash application name

bull request ndash the global request object

Returns True on success False on failure

4 Chapter 1 admin Module

web2py Documentation Release 2146-stable

gluonadmincheck_new_version(myversion version_url)Compares current web2pyrsquos version with the latest stable web2py version

Parameters

bull myversion ndash the current version as stored in file web2pyVERSION

bull version_URL ndash the URL that contains the version of the latest stable release

Returns

state version

bull state True if upgrade available False if current version is up-to-date -1 on error

bull version the most up-to-version available

Return type tuple

gluonadmincreate_missing_app_folders(request)

gluonadmincreate_missing_folders()

gluonadminplugin_install(app fobj request filename)Installs a plugin

bull Identifies file type by filename

bull Writes fobj contents to the deposit folder

bull Calls w2p_unpack_plugin() to do the job

Parameters

bull app (str) ndash new application name

bull fobj ndash file object containing the application to be installed

bull request ndash the global request object

bull filename ndash original filename of the fobj required to determine extension

Returns name of the file where plugin is temporarily stored or False on failure

gluonadminplugin_pack(app plugin_name request)Builds a w2p package for the plugin

Parameters

bull app (str) ndash application name

bull plugin_name (str) ndash the name of the plugin without plugin_ prefix

bull request ndash the current request app

Returns filename of the w2p file or False on error

gluonadminunzip(filename dir subfolder=rdquo)Unzips filename into dir (zip only no gz etc)

Parameters

bull filename (str) ndash archive

bull dir (str) ndash destination

bull subfolder (str) ndash if = lsquorsquo unzips only files in subfolder

11 Utility functions for the Admin application 5

web2py Documentation Release 2146-stable

gluonadminupgrade(request url=rsquohttpweb2pycomrsquo)Upgrades web2py (src osx win) if a new version is posted It detects whether src osx or win is running anddownloads the right one

Parameters

bull request ndash the current request object (required to determine version and path)

bull url ndash the incomplete url where to locate the latest web2py (actual url isurl+rsquoexamplesstaticweb2py_(src|osx|win)ziprsquo)

Returns tuple completed traceback

bull completed True on success False on failure (network problem or old version)

bull traceback None on success raised exception details on failure

6 Chapter 1 admin Module

CHAPTER 2

cache Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

21 Basic caching classes and methods

bull Cache - The generic caching object interfacing with the others

bull CacheInRam - providing caching in ram

bull CacheOnDisk - provides caches on disk

Memcache is also available via a different module (see gluoncontribmemcache)

When web2py is running on Google App Engine caching will be provided by the GAE memcache (seegluoncontribgae_memcache)

class gluoncacheCache(request)Bases object

Sets up generic caching creating an instance of both CacheInRam and CacheOnDisk In case of GAE will makeuse of gluoncontribgae_memcache

bull selfram is an instance of CacheInRam

bull selfdisk is an instance of CacheOnDisk

action(time_expire=300 cache_model=None prefix=None session=False vars=True lang=Trueuser_agent=False public=True valid_statuses=None quick=None)

Better fit for caching an action

Warning Experimental

7

web2py Documentation Release 2146-stable

Currently only HTTP 11 compliant reference httpcodegooglecompdoctype-mirrorwikiArticleHttpCaching

Parameters

bull time_expire (int) ndash same as cache

bull cache_model (str) ndash same as cache

bull prefix (str) ndash add a prefix to the calculated key

bull session (bool) ndash adds responsesession_id to the key

bull vars (bool) ndash adds requestenvquery_string

bull lang (bool) ndash adds Taccepted_language

bull user_agent (bool or dict) ndash if True adds is_mobile and is_tablet tothe key Pass a dict to use all the needed values (uses str(items())) (eguser_agent=requestuser_agent()) Used only if session is not True

bull public (bool) ndash if False forces the Cache-Control to be lsquoprivatersquo

bull valid_statuses ndash by default only status codes starting with 123 will be cached passan explicit list of statuses on which turn the cache on

bull quick ndash SessionVarsLangUser-agentPublic fast overrides with initials eg lsquoSVLPrsquoor lsquoVLPrsquo or lsquoVLPrsquo

autokey = (name)s(args)s(vars)s

static with_prefix(cache_model prefix)allow replacing cacheram with cachewith_prefix(cacheramrsquoprefixrsquo) it will add prefix to all the cachekeys used

gluoncachelazy_cache(key=None time_expire=None cache_model=rsquoramrsquo)Can be used to cache any function including ones in modules as long as the cached function is only calledwithin a web2py request

If a key is not provided one is generated from the function name time_expire defaults to None (no cacheexpiration)

If cache_model is ldquoramrdquo then the model is currentcacheram etc

8 Chapter 2 cache Module

CHAPTER 3

cfs Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

31 Functions required to execute app components

Note FOR INTERNAL USE ONLY

gluoncfsgetcfs(key filename filter=None)Caches the filtered file filename with key until the file is modified

Parameters

bull key (str) ndash the cache key

bull filename ndash the file to cache

bull filter ndash is the function used for filtering Normally filename is a py file and filter is afunction that bytecode compiles the file In this way the bytecode compiled file is cached(Default = None)

This is used on Google App Engine since pyc files cannot be saved

9

web2py Documentation Release 2146-stable

10 Chapter 3 cfs Module

CHAPTER 4

compileapp Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

41 Functions required to execute app components

Note FOR INTERNAL USE ONLY

gluoncompileappLOAD(c=None f=rsquoindexrsquo args=None vars=None extension=None target=Noneajax=False ajax_trap=False url=None user_signature=False time-out=None times=1 content=rsquoloadingrsquo post_vars= attr)

LOADs a component into the actionrsquos document

Parameters

bull c (str) ndash controller

bull f (str) ndash function

bull args (tuple or list) ndash arguments

bull vars (dict) ndash vars

bull extension (str) ndash extension

bull target (str) ndash id of the target

bull ajax (bool) ndash True to enable AJAX bahaviour

bull ajax_trap (bool) ndash True if ajax is set to True traps both links and forms ldquoinsiderdquo thetarget

bull url (str) ndash overrides clsquoflsquolsquoargslsquo and vars

11

web2py Documentation Release 2146-stable

bull user_signature (bool) ndash adds hmac signature to all links with a key that is differentfor every user

bull timeout (int) ndash in milliseconds specifies the time to wait before starting the request orthe frequency if times is greater than 1 or ldquoinfinityrdquo

bull times (integer or str) ndash how many times the component will be requested ldquoinfin-ityrdquo or ldquocontinuousrdquo are accepted to reload indefinitely the component

class gluoncompileappLoadFactory(environment)Bases object

Attention this helper is new and experimental

gluoncompileappbuild_environment(request response session store_current=True)Build the environment dictionary into which web2py files are executed

gluoncompileappcompile_application(folder skip_failed_views=False)Compiles all models views controller for the application in folder

gluoncompileappcompile_controllers(folder)Compiles all the controllers in the application specified by folder

gluoncompileappcompile_models(folder)Compiles all the models in the application specified by folder

gluoncompileappcompile_views(folder skip_failed_views=False)Compiles all the views in the application specified by folder

gluoncompileappfind_exposed_functions(data)

gluoncompileapplocal_import_aux(name reload_force=False app=rsquowelcomersquo)In apps instead of importing a local module (in applicationsappmodules) with

import abc as d

you should do

d = local_import(abc)

or (to force a reload)

d = local_import(lsquoabcrsquo reload=True)

This prevents conflict between applications and un-necessary execs It can be used to import any moduleincluding regular Python modules

gluoncompileappmodel_cmp(a b sep=rsquorsquo)

gluoncompileappmodel_cmp_sep(a b sep=rsquorsquo)

class gluoncompileappmybuiltinBases object

NOTE could simple use a dict and populate it NOTE not sure if this changes things though if monkey patchingimport

gluoncompileappre_compile(regex)

gluoncompileappread_pyc(filename)Read the code inside a bytecode compiled file if the MAGIC number is compatible

Returns a code object

12 Chapter 4 compileapp Module

web2py Documentation Release 2146-stable

gluoncompileappremove_compiled_application(folder)Deletes the folder compiled containing the compiled application

gluoncompileapprun_controller_in(controller function environment)Runs the controllerfunction() (for the app specified by the current folder) It tries pre-compiled con-troller_functionpyc first before compiling it

gluoncompileapprun_models_in(environment)Runs all models (in the app specified by the current folder) It tries pre-compiled models first before compilingthem

gluoncompileapprun_view_in(environment)Executes the view for the requested action The view is the one specified in responseview or determined by theurl or viewgenericextension It tries the pre-compiled views_controller_functionpyc before compiling it

gluoncompileappsave_pyc(filename)Bytecode compiles the file filename

gluoncompileapptest()Example

gtgtgt import traceback typesgtgtgt environment=x1gtgtgt open(apy w)write(print 1x)gtgtgt save_pyc(apy)gtgtgt osunlink(apy)gtgtgt if type(read_pyc(apyc))==typesCodeType print codecodegtgtgt exec read_pyc(apyc) in environment1

41 Functions required to execute app components 13

web2py Documentation Release 2146-stable

14 Chapter 4 compileapp Module

CHAPTER 5

contenttype Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

CONTENT_TYPE dictionary created against freedesktoporgrsquos shared mime info database version 11

Deviations from official standards

bull md applicationx-genesis-rom ndashgt textx-markdown

bull png imagex-apple-ios-png ndashgt imagepng

Additions

bull load texthtml

bull json applicationjson

bull jsonp applicationjsonp

bull pickle applicationpython-pickle

bull w2prsquo applicationw2p

gluoncontenttypecontenttype(filename default=rsquotextplainrsquo)Returns the Content-Type string matching extension of the given filename

15

web2py Documentation Release 2146-stable

16 Chapter 5 contenttype Module

CHAPTER 6

custom_import Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

61 Support for smart import syntax for web2py applications

exception gluoncustom_importCustomImportExceptionBases exceptionsImportError

class gluoncustom_importTrackImporterBases object

An importer tracking the date of the module files and reloading them when they are changed

PACKAGE_PATH_SUFFIX = __init__py

THREAD_LOCAL = ltthread_local objectgt

gluoncustom_importcustom_import_install()

gluoncustom_importcustom_importer(name globals=None locals=None fromlist=Nonelevel=-1)

web2pyrsquos custom importer It behaves like the standard Python importer but it tries to transform importstatements as something like ldquoimport applicationsapp_namemodulesxrdquo If the import fails it falls back onnaive_importer

gluoncustom_importis_tracking_changes()

gluoncustom_importtrack_changes(track=True)

17

web2py Documentation Release 2146-stable

18 Chapter 6 custom_import Module

CHAPTER 7

dal Module

Go to httppydalreadthedocsorgenlatest for docs on pyDAL

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

71 Takes care of adapting pyDAL to web2pyrsquos needs

19

web2py Documentation Release 2146-stable

20 Chapter 7 dal Module

CHAPTER 8

debug Module

This file is part of the web2py Web FrameworkDeveloped by Massimo Di Pierro ltmdipierrocsdepauledugtlimodou ltlimodougmailcomgt and srackham ltsrackhamgmailcomgtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

81 Debugger support classes

class gluondebugPipe(name mode=rsquorrsquo args kwargs)Bases QueueQueue

flush()

read(count=None timeout=None)

readline()

write(data)

class gluondebugWebDebugger(pipe completekey=rsquotabrsquo stdin=None stdout=None)Bases gluoncontribqdbFrontend

Qdb web2py interface

clear_interaction()

do_continue(args kwargs)

do_exec(statement)

do_next(args kwargs)

do_quit(args kwargs)

do_return(args kwargs)

do_step(args kwargs)

21

web2py Documentation Release 2146-stable

exception(title extype exvalue trace request)Show a user_exception

interaction(filename lineno line context)

run()Main method dispatcher (infinite loop)

gluondebugcheck_interaction(fn)Decorator to clean and prevent interaction when not available

gluondebugcommunicate(command=None)send command to debbuger wait result

gluondebugset_trace()breakpoint shortcut (like pdb)

gluondebugstop_trace()stop waiting for the debugger (called atexit)

22 Chapter 8 debug Module

CHAPTER 9

decoder Module

Caller will hand this library a buffer and ask it to either convert it or auto-detect the type

Based on httpcodeactivestatecomrecipes52257

Licensed under the PSF License

gluondecoderautoDetectXMLEncoding(buffer)buffer -gt encoding_name The buffer should be at least 4 bytes long Returns None if encoding cannot bedetected Note that encoding_name might not have an installed decoder (eg EBCDIC)

gluondecoderdecoder(buffer)

23

web2py Documentation Release 2146-stable

24 Chapter 9 decoder Module

CHAPTER 10

fileutils Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

101 File operations

gluonfileutilsparse_version(version)Attempts to parse SemVer fallbacks on legacy

gluonfileutilsread_file(filename mode=rsquorrsquo)Returns content from filename making sure to close the file explicitly on exit

gluonfileutilswrite_file(filename value mode=rsquowrsquo)Writes ltvaluegt to filename making sure to close the file explicitly on exit

gluonfileutilsreadlines_file(filename mode=rsquorrsquo)Applies split(lsquo lsquo) to the output of read_file()

gluonfileutilsup(path)

gluonfileutilsabspath(relpath base)Converts relative path to absolute path based (by default) on applications_parent

gluonfileutilsmktree(path)

gluonfileutilslistdir(path expression=rsquo^+$rsquo drop=True add_dirs=False sort=Truemaxnum=None exclude_content_from=None)

Like oslistdir() but you can specify a regex pattern to filter files If add_dirs is True the returned items willhave the full path

gluonfileutilsrecursive_unlink(f)Deletes f If itrsquos a folder also its contents will be deleted

gluonfileutilscleanpath(path)Turns any expressionpath into a valid filename replaces with _ and removes special characters

25

web2py Documentation Release 2146-stable

gluonfileutilstar(file dir expression=rsquo^+$rsquo filenames=None exclude_content_from=None)Tars dir into file only tars file that match expression

gluonfileutilsuntar(file dir)Untar file into dir

gluonfileutilstar_compiled(file dir expression=rsquo^+$rsquo exclude_content_from=None)Used to tar a compiled application The content of models views controllers is not stored in the tar file

gluonfileutilsget_session(request other_application=rsquoadminrsquo)Checks that user is authorized to access other_application

gluonfileutilscheck_credentials(request other_application=rsquoadminrsquo expiration=3600gae_login=True)

Checks that user is authorized to access other_application

gluonfileutilsw2p_pack(filename path compiled=False filenames=None)Packs a web2py application

Parameters

bull filename (str) ndash path to the resulting archive

bull path (str) ndash path to the application

bull compiled (bool) ndash if True packs the compiled version

bull filenames (list) ndash adds filenames to the archive

gluonfileutilsw2p_unpack(filename path delete_tar=True)

gluonfileutilsw2p_pack_plugin(filename path plugin_name)Packs the given plugin into a w2p file Will match files at

ltpathgtplugin_[name]ltpathgtplugin_[name]

gluonfileutilsw2p_unpack_plugin(filename path delete_tar=True)

gluonfileutilsfix_newlines(path)

gluonfileutilsmake_fake_file_like_object()

26 Chapter 10 fileutils Module

CHAPTER 11

globals Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

Contains the classes for the global used variables

bull Request

bull Response

bull Session

class gluonglobalsRequest(env)Bases gluonstorageStorage

Defines the request object and the default values of its members

bull env environment variables by gluonmainwsgibase()

bull cookies

bull get_vars

bull post_vars

bull vars

bull folder

bull application

bull function

bull args

bull extension

bull now datetimedatetimenow()

27

web2py Documentation Release 2146-stable

bull utcnow datetimedatetimeutcnow()

bull is_local

bull is_https

bull restful()

body

compute_uuid()

get_varsLazily parses the query string into get_vars

parse_all_vars()Merges get_vars and post_vars to vars

parse_get_vars()Takes the QUERY_STRING and unpacks it to get_vars

parse_post_vars()Takes the body of the request and unpacks it into post_vars applicationjson is also automatically parsed

post_varsLazily parse the body into post_vars

requires_https()If request comes in over HTTP redirects it to HTTPS and secures the session

restful()

user_agent()

uuidLazily uuid

varsLazily parses all get_vars and post_vars to fill vars

class gluonglobalsResponseBases gluonstorageStorage

Defines the response object and the default values of its members responsewrite( ) can be used to write in theoutput html

download(request db chunk_size=65536 attachment=True download_filename=None)Example of usage in controller

def download()return responsedownload(request db)

Downloads from http downloadfilename

include_files(extensions=None)Includes files (usually in the head) Can minify and cache local files By default caches in ram for 5minutes To change responsecache_includes = (cache_method time_expire) Example (cachedisk 60) caches to disk for 1 minute

include_meta()

json(data default=None)

render(a b)

28 Chapter 11 globals Module

web2py Documentation Release 2146-stable

stream(stream chunk_size=65536 request=None attachment=False filename=None)If in a controller function

return responsestream(file 100)

the file content will be streamed at 100 bytes at the time

Parameters

bull stream ndash filename or read()able content

bull chunk_size (int) ndash Buffer size

bull request ndash the request object

bull attachment (bool) ndash prepares the correct headers to download the file as an attach-ment Usually creates a pop-up download window on browsers

bull filename (str) ndash the name for the attachment

Note for using the stream name (filename) with attachments the option must be explicitly set as functionparameter (will default to the last request argument otherwise)

toolbar()

write(data escape=True)

xmlrpc(request methods)assuming

def add(a b)return a+b

if a controller function ldquofuncrdquo

return responsexmlrpc(request [add])

the controller will be able to handle xmlrpc requests for the add function Example

import xmlrpclibconnection = xmlrpclibServerProxy(

httphostnameappcontrfunc)print connectionadd(3 4)

class gluonglobalsSessionBases gluonstorageStorage

Defines the session object and the default values of its members (None)

bull session_storage_type lsquofilersquo lsquodbrsquo or lsquocookiersquo

bull session_cookie_compression_level

bull session_cookie_expires cookie expiration

bull session_cookie_key for encrypted sessions in cookies

bull session_id a number or None if no session

bull session_id_name

bull session_locked

29

web2py Documentation Release 2146-stable

bull session_masterapp

bull session_new a new session obj is being created

bull session_hash hash of the pickled loaded session

bull session_pickled picked session

if session in cookie

bull session_data_name name of the cookie for session data

if session in db

bull session_db_record_id

bull session_db_table

bull session_db_unique_key

if session in file

bull session_file

bull session_filename

clear()rarr None Remove all items from D

clear_session_cookies()

connect(request=None response=None db=None tablename=rsquoweb2py_sessionrsquo master-app=None migrate=True separate=None check_client=False cookie_key=Nonecookie_expires=None compression_level=None)

Used in models allows to customize Session handling

Parameters

bull request ndash the request object

bull response ndash the response object

bull db ndash to storeretrieve sessions in db (a table is created)

bull tablename (str) ndash table name

bull masterapp (str) ndash points to anotherrsquos app sessions This enables a ldquoSSOrdquo environmentamong apps

bull migrate ndash passed to the underlying db

bull separate ndash with True creates a folder with the 2 initials of the session id Can also bea function eg

separate=lambda(session_name) session_name[-2]

bull check_client ndash if True sessions can only come from the same ip

bull cookie_key (str) ndash secret for cookie encryption

bull cookie_expires ndash sets the expiration of the cookie

bull compression_level (int) ndash 0-9 sets zlib compression on the data before the en-cryption

forget(response=None)

is_expired(seconds=3600)

is_new()

30 Chapter 11 globals Module

web2py Documentation Release 2146-stable

renew(clear_session=False)

save_session_id_cookie()

secure()

31

web2py Documentation Release 2146-stable

32 Chapter 11 globals Module

CHAPTER 12

highlight Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

gluonhighlighthighlight(code language link=rsquoexamplesglobalsvarsrsquo counter=1styles=None highlight_line=None context_lines=None at-tributes=None)

33

web2py Documentation Release 2146-stable

34 Chapter 12 highlight Module

CHAPTER 13

html Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

131 Template helpers

class gluonhtmlA(components attributes)Bases gluonhtmlDIV

Generates an A() link A() in web2py is really important and with the included web2pyjs allows lots of Ajaxinteractions in the page

On top of ldquousualrdquo _attributes it takes

Parameters

bull callback ndash an url to call but not redirect to

bull cid ndash if you want to load the _href into an element of the page (component) pass its id(without the ) here

bull delete ndash element to delete after calling callback

bull target ndash same thing as cid

bull confirm ndash text to display upon a callback with a delete

bull noconfirm ndash donrsquot display alert upon a callback with delete

tag = a

xml()generates the xml for this component

gluonhtmlASSIGNJS(kargs)

35

web2py Documentation Release 2146-stable

Example

ASSIGNJS(var1=lsquo1rsquo var2=lsquo2rsquo) will return the following javascript variables assignations

var var1 = ldquo1rdquo var var2 = ldquo2rdquo

Parameters kargs ndash Any keywords arguments and assigned values

Returns Javascript vars assignations for the keyvalue passed

class gluonhtmlB(components attributes)Bases gluonhtmlDIV

tag = b

class gluonhtmlBEAUTIFY(component attributes)Bases gluonhtmlDIV

Turns any list dictionary etc into decent looking html

Two special attributes are

bull sorted a function that takes the dict and returned sorted keys

bull keyfilter a function that takes a key and returns its representation or None if the key is to be skipped Bydefault key[1]==rsquo_rsquo is skipped

Examples

gtgtgt BEAUTIFY([a b hello world])xml()ltdivgtlttablegtlttrgtlttdgtltdivgtaltdivgtlttdgtlttrgtlttrgtlttdgtltdivgtbltdivgtlttdgtlttrgtlttrgtlttdgtrarr˓ltdivgtlttablegtlttrgtlttd style=font-weightboldvertical-aligntopgthellolttdgtlttdrarr˓style=vertical-aligntopgtlttdgtlttdgtltdivgtworldltdivgtlttdgtlttrgtlttablegtltdivgtltrarr˓tdgtlttrgtlttablegtltdivgt

static no_underscore(key)

tag = div

class gluonhtmlBODY(components attributes)Bases gluonhtmlDIV

tag = body

class gluonhtmlBR(components attributes)Bases gluonhtmlDIV

tag = br

class gluonhtmlBUTTON(components attributes)Bases gluonhtmlDIV

tag = button

class gluonhtmlCENTER(components attributes)Bases gluonhtmlDIV

tag = center

class gluonhtmlCAT(components attributes)Bases gluonhtmlDIV

tag =

36 Chapter 13 html Module

web2py Documentation Release 2146-stable

class gluonhtmlCODE(components attributes)Bases gluonhtmlDIV

Displays code in HTML with syntax highlighting

Parameters

bull language ndash indicates the language otherwise PYTHON is assumed

bull link ndash can provide a link

bull styles ndash for styles

Examples

=CODE(ldquoprint lsquohello worldrsquordquo language=rsquopythonrsquo link=None counter=1 styles= high-light_line=None)

supported languages are

ldquopythonrdquo ldquohtml_plainrdquo ldquocrdquo ldquocpprdquo ldquoweb2pyrdquo ldquohtmlrdquo

The ldquohtmlrdquo language interprets and tags as ldquoweb2pyrdquo code ldquohtml_plainrdquo doesnrsquot

if a link=rsquoexamplesglobalvarsrsquo is provided web2py keywords are linked to the online docs

the counter is used for line numbering counter can be None or a prompt string

xml()generates the xml for this component

class gluonhtmlCOL(components attributes)Bases gluonhtmlDIV

tag = col

class gluonhtmlCOLGROUP(components attributes)Bases gluonhtmlDIV

tag = colgroup

class gluonhtmlDIV(components attributes)Bases gluonhtmlXmlComponent

HTML helper for easy generating and manipulating a DOM structure Little or no validation is done

Behaves like a dictionary regarding updating of attributes Behaves like a list regarding insertingappendingcomponents

Examples

gtgtgt DIV(hello world _style=colorred)xml()ltdiv style=colorredgthelloworldltdivgt

All other HTML helpers are derived from DIV

_something=rdquovaluerdquo attributes are transparently translated into something=rdquovaluerdquo HTML attributes

append(value)list style appending of components

Examples

131 Template helpers 37

web2py Documentation Release 2146-stable

gtgtgt a=DIV()gtgtgt aappend(SPAN(x))gtgtgt print altdivgtltspangtxltspangtltdivgt

element(args kargs)Finds the first component that matches the supplied attribute dictionary or None if nothing could be found

Also the components of the components are searched

elements(args kargs)Find all components that match the supplied attribute dictionary or None if nothing could be found

All components of the components are searched

Examples

gtgtgt a = DIV(DIV(SPAN(x)3DIV(SPAN(y))))gtgtgt for c in aelements(span first_only=True) c[0]=zgtgtgt print altdivgtltdivgtltspangtzltspangt3ltdivgtltspangtyltspangtltdivgtltdivgtltdivgtgtgtgt for c in aelements(span) c[0]=zgtgtgt print altdivgtltdivgtltspangtzltspangt3ltdivgtltspangtzltspangtltdivgtltdivgtltdivgt

It also supports a syntax compatible with jQuery

Examples

gtgtgt a=TAG(ltdivgtltspangtlta id=1-1 uv=$gthelloltagtltspangtltp class=this is ararr˓testgtworldltpgtltdivgt)gtgtgt for e in aelements(div a1-1 pis) print eflatten()helloworldgtgtgt for e in aelements(1-1) print eflatten()hellogtgtgt aelements(a[uv=$])[0]xml()lta id=1-1 uv=$gthelloltagtgtgtgt a=FORM( INPUT(_type=text) SELECT(range(1)) TEXTAREA() )gtgtgt for c in aelements(input select textarea) c[_disabled] = disabledrarr˓gtgtgt axml()ltform action= enctype=multipartform-data method=postgtltinput disabled=rarr˓disabled type=text gtltselect disabled=disabledgtltoption value=0gt0ltrarr˓optiongtltselectgtlttextarea cols=40 disabled=disabled rows=10gtltrarr˓textareagtltformgt

Elements that are matched can also be replaced or removed by specifying a ldquoreplacerdquo argument (note alist of the original matching elements is still returned as usual)

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=abc) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(spanabc replace=P(x _class=xyz))gtgtgt print a We should xml() here instead of printltdivgtltdivgtltp class=xyzgtxltpgtltdivgtltp class=xyzgtxltpgtltp class=xyzgtxltpgtltrarr˓divgtltdivgtltdivgt

38 Chapter 13 html Module

web2py Documentation Release 2146-stable

ldquoreplacerdquo can be a callable which will be passed the original element and should return a new element toreplace it

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=abc) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(spanabc replace=lambda el P(el[0] _class=xyz))gtgtgt print altdivgtltdivgtltp class=xyzgtxltpgtltdivgtltp class=xyzgtyltpgtltp class=xyzgtzltpgtltrarr˓divgtltdivgtltdivgt

If replace=None matching elements will be removed completely

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=abc) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(span find=y replace=None)gtgtgt print altdivgtltdivgtltspan class=abcgtxltspangtltdivgtltspan class=abcgtzltspangtltdivgtltrarr˓divgtltdivgt

If a ldquofind_textrdquo argument is specified elements will be searched for text components that match find_textand any matching text components will be replaced (find_text is ignored if ldquoreplacerdquo is not also specified)Like the ldquofindrdquo argument ldquofind_textrdquo can be a string or a compiled regex

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=abc) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(find_text=recompile(x|y|z) replace=hello)gtgtgt print altdivgtltdivgtltspan class=abcgthelloltspangtltdivgtltspan class=abcgthelloltspangtrarr˓ltspan class=abcgthelloltspangtltdivgtltdivgtltdivgt

If other attributes are specified along with find_text then only components that match the specified at-tributes will be searched for find_text

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=efg) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(spanefg find_text=recompile(x|y|z) replace=hello)gtgtgt print altdivgtltdivgtltspan class=abcgtxltspangtltdivgtltspan class=efggthelloltspangtltspanrarr˓class=abcgtzltspangtltdivgtltdivgtltdivgt

flatten(render=None)Returns the text stored by the DIV object rendered by the render function the render function must taketext tagname and attributes render=None is equivalent to render=lambda text tag attr text

Examples

gtgtgt markdown = lambda text tag=None attributes=rarr˓None resub(s+ text) h1+text+nnrarr˓ ptext+nget(tagtext)gtgtgt a=TAG(lth1gtHeaderlth1gtltpgtthis is a testltpgt)gtgtgt aflatten(markdown)Headernnthis is a testn

131 Template helpers 39

web2py Documentation Release 2146-stable

get(i)

insert(i value)List-style inserting of components

Examples

gtgtgt a=DIV()gtgtgt ainsert(0 SPAN(x))gtgtgt print altdivgtltspangtxltspangtltdivgt

regex_attr = lt_sreSRE_Pattern objectgt

regex_class = lt_sreSRE_Pattern objectgt

regex_id = lt_sreSRE_Pattern objectgt

regex_tag = lt_sreSRE_Pattern objectgt

sibling(args kargs)Finds the first sibling component that match the supplied argument list and attribute dictionary or None ifnothing could be found

siblings(args kargs)Finds all sibling components that match the supplied argument list and attribute dictionary or None ifnothing could be found

tag = div

update(kargs)dictionary like updating of the tag attributes

xml()generates the xml for this component

class gluonhtmlEM(components attributes)Bases gluonhtmlDIV

tag = em

class gluonhtmlEMBED(components attributes)Bases gluonhtmlDIV

tag = embed

class gluonhtmlFIELDSET(components attributes)Bases gluonhtmlDIV

tag = fieldset

class gluonhtmlFORM(components attributes)Bases gluonhtmlDIV

Examples

gtgtgt from validators import IS_NOT_EMPTYgtgtgt form=FORM(INPUT(_name=test requires=IS_NOT_EMPTY()))gtgtgt formxml()ltform action= enctype=multipartform-data method=postgtltinput name=testrarr˓type=text gtltformgt

a FORM is container for INPUT TEXTAREA SELECT and other helpers

form has one important method

40 Chapter 13 html Module

web2py Documentation Release 2146-stable

formaccepts(requestvars session)

if form is accepted (and all validators pass) formvars contains the accepted vars otherwise formerrors containsthe errors in case of errors the form is modified to present the errors to the user

REDIRECT_JS = windowlocation=sreturn false

accepts(request_vars session=None formname=rsquodefaultrsquo keepvalues=False onvalidation=Nonehideerror=False kwargs)

kwargs is not used but allows to specify the same interface for FORM and SQLFORM

add_button(value url _class=None)

as_dict(flat=False sanitize=True)EXPERIMENTAL

Sanitize is naive It should catch any unsafe value for client retrieval

as_json(sanitize=True)

as_xml(sanitize=True)

as_yaml(sanitize=True)

assert_status(status request_vars)

static confirm(text=rsquoOKrsquo buttons=None hidden=None)

hidden_fields()

process(kwargs)Perform the validate() method but returns the form

Usage in controllers

directly on returndef action()

some code herereturn dict(form=FORM()process())

You can use it with FORM SQLFORM or FORM based plugins

responseflash messagesdef action()

form = SQLFORM(dbtable)process(message_onsuccess=Sucess)return dict(form=form)

callback function callback receives True or False as first arg and a list of argsdef my_callback(status msg)

responseflash = Success +msg if status else Errors occured

after argument can be flash to responseflash messages or a function name to use as callback or None to do nothingdef action()

return dict(form=SQLFORM(dbtable)process(onsuccess=my_callback)

tag = form

validate(kwargs)This function validates the form you can use it instead of directly formaccepts

Usage In controller

131 Template helpers 41

web2py Documentation Release 2146-stable

def action()form=FORM(INPUT(_name=test requires=IS_NOT_EMPTY()))formvalidate() you can pass some args here - see belowreturn dict(form=form)

This can receive a bunch of arguments

onsuccess = lsquoflashrsquo - will show message_onsuccess in responseflash None - will do nothing can be afunction (lambda form pass)

onfailure = lsquoflashrsquo - will show message_onfailure in responseflash None - will do nothing can be afunction (lambda form pass)

onchange = lsquoflashrsquo - will show message_onchange in responseflash None - will do nothing can be afunction (lambda form pass)

message_onsuccess message_onfailure message_onchange next = where to redirect in case of success anyother kwargs will be passed for formaccepts( )

xml()generates the xml for this component

class gluonhtmlH1(components attributes)Bases gluonhtmlDIV

tag = h1

class gluonhtmlH2(components attributes)Bases gluonhtmlDIV

tag = h2

class gluonhtmlH3(components attributes)Bases gluonhtmlDIV

tag = h3

class gluonhtmlH4(components attributes)Bases gluonhtmlDIV

tag = h4

class gluonhtmlH5(components attributes)Bases gluonhtmlDIV

tag = h5

class gluonhtmlH6(components attributes)Bases gluonhtmlDIV

tag = h6

class gluonhtmlHEAD(components attributes)Bases gluonhtmlDIV

tag = head

class gluonhtmlHR(components attributes)Bases gluonhtmlDIV

tag = hr

class gluonhtmlHTML(components attributes)Bases gluonhtmlDIV

42 Chapter 13 html Module

web2py Documentation Release 2146-stable

There are four predefined document type definitions They can be specified in the lsquodoctypersquo parameter

bull lsquostrictrsquo enables strict doctype

bull lsquotransitionalrsquo enables transitional doctype (default)

bull lsquoframesetrsquo enables frameset doctype

bull lsquohtml5rsquo enables HTML 5 doctype

bull any other string will be treated as userrsquos own doctype

lsquolangrsquo parameter specifies the language of the document Defaults to lsquoenrsquo

See also DIV

frameset = ltDOCTYPE HTML PUBLIC -W3CDTD HTML 401 FramesetEN httpwwww3orgTRhtml4framesetdtdgtn

html5 = ltDOCTYPE HTMLgtn

strict = ltDOCTYPE HTML PUBLIC -W3CDTD HTML 401EN httpwwww3orgTRhtml4strictdtdgtn

tag = html

transitional = ltDOCTYPE HTML PUBLIC -W3CDTD HTML 401 TransitionalEN httpwwww3orgTRhtml4loosedtdgtn

xml()generates the xml for this component

class gluonhtmlI(components attributes)Bases gluonhtmlDIV

tag = i

class gluonhtmlIFRAME(components attributes)Bases gluonhtmlDIV

tag = iframe

class gluonhtmlIMG(components attributes)Bases gluonhtmlDIV

tag = img

class gluonhtmlINPUT(components attributes)Bases gluonhtmlDIV

INPUT Component

Takes two special attributes value= and requires=

Parameters

bull value ndash used to pass the initial value for the input field value differs from _value becauseit works for checkboxes radio textarea and selectoption too For a checkbox value shouldbe lsquorsquo or lsquoonrsquo For a radio or selectoption value should be the _value of the checkedselecteditem

bull requires ndash should be None or a validator or a list of validators for the value of the field

Examples

gtgtgt INPUT(_type=text _name=name value=Max)xml()ltinput name=name type=text value=Max gt

gtgtgt INPUT(_type=checkbox _name=checkbox value=on)xml()ltinput checked=checked name=checkbox type=checkbox value=on gt

131 Template helpers 43

web2py Documentation Release 2146-stable

gtgtgt INPUT(_type=radio _name=radio _value=yes value=yes)xml()ltinput checked=checked name=radio type=radio value=yes gt

gtgtgt INPUT(_type=radio _name=radio _value=no value=yes)xml()ltinput name=radio type=radio value=no gt

tag = input

xml()generates the xml for this component

class gluonhtmlLABEL(components attributes)Bases gluonhtmlDIV

tag = label

class gluonhtmlLEGEND(components attributes)Bases gluonhtmlDIV

tag = legend

class gluonhtmlLI(components attributes)Bases gluonhtmlDIV

tag = li

class gluonhtmlLINK(components attributes)Bases gluonhtmlDIV

tag = link

class gluonhtmlOL(components attributes)Bases gluonhtmlUL

tag = ol

class gluonhtmlUL(components attributes)Bases gluonhtmlDIV

UL Component

If subcomponents are not LI-components they will be wrapped in a LI

tag = ul

class gluonhtmlMARKMIN(text extra=None allowed=None sep=rsquoprsquo url=None environ-ment=None latex=rsquogooglersquo autolinks=rsquodefaultrsquo protolinks=rsquodefaultrsquoclass_prefix=rdquo id_prefix=rsquomarkmin_rsquo kwargs)

Bases gluonhtmlXmlComponent

For documentation httpweb2pycomexamplesstaticmarkminhtml

flatten()

xml()

class gluonhtmlMENU(data args)Bases gluonhtmlDIV

Used to build menus

Parameters

bull _class ndash defaults to lsquoweb2py-menu web2py-menu-verticalrsquo

bull ul_class ndash defaults to lsquoweb2py-menu-verticalrsquo

44 Chapter 13 html Module

web2py Documentation Release 2146-stable

bull li_class ndash defaults to lsquoweb2py-menu-expandrsquo

bull li_first ndash defaults to lsquoweb2py-menu-firstrsquo

bull li_last ndash defaults to lsquoweb2py-menu-lastrsquo

Use like

menu = MENU([[name False URL() [submenu]] ])=menu

serialize(data level=0)

serialize_mobile(data select=None prefix=rdquo)

tag = ul

xml()generates the xml for this component

class gluonhtmlMETA(components attributes)Bases gluonhtmlDIV

tag = meta

class gluonhtmlOBJECT(components attributes)Bases gluonhtmlDIV

tag = object

class gluonhtmlOPTION(components attributes)Bases gluonhtmlDIV

tag = option

class gluonhtmlP(components attributes)Bases gluonhtmlDIV

Will replace n by ltbr gt if the cr2br attribute is provided

see also DIV

tag = p

xml()generates the xml for this component

class gluonhtmlPRE(components attributes)Bases gluonhtmlDIV

tag = pre

class gluonhtmlSCRIPT(components attributes)Bases gluonhtmlDIV

tag = script

xml()generates the xml for this component

class gluonhtmlOPTGROUP(components attributes)Bases gluonhtmlDIV

tag = optgroup

131 Template helpers 45

web2py Documentation Release 2146-stable

class gluonhtmlSELECT(components attributes)Bases gluonhtmlINPUT

Examples

gtgtgt from validators import IS_IN_SETgtgtgt SELECT(yes no _name=selector value=yes requires=IS_IN_SET([yes no]))xml()ltselect name=selectorgtltoption selected=selected value=yesgtyesltoptiongtrarr˓ltoption value=nogtnoltoptiongtltselectgt

tag = select

class gluonhtmlSPAN(components attributes)Bases gluonhtmlDIV

tag = span

class gluonhtmlSTRONG(components attributes)Bases gluonhtmlDIV

tag = strong

class gluonhtmlSTYLE(components attributes)Bases gluonhtmlDIV

tag = style

xml()generates the xml for this component

class gluonhtmlTABLE(components attributes)Bases gluonhtmlDIV

TABLE Component

If subcomponents are not TRTBODYTHEADTFOOT-components they will be wrapped in a TR

tag = table

gluonhtmlTAGTAG factory

Examples

gtgtgt print TAGfirst(TAGsecond(test) _key = 3)ltfirst key=3gtltsecondgttestltsecondgtltfirstgt

class gluonhtmlTD(components attributes)Bases gluonhtmlDIV

tag = td

class gluonhtmlTEXTAREA(components attributes)Bases gluonhtmlINPUT

Examples

TEXTAREA(_name=sometext value=blah 100 requires=IS_NOT_EMPTY())

lsquoblah blah blah rsquo will be the content of the textarea field

tag = textarea

46 Chapter 13 html Module

web2py Documentation Release 2146-stable

class gluonhtmlTH(components attributes)Bases gluonhtmlDIV

tag = th

class gluonhtmlTHEAD(components attributes)Bases gluonhtmlDIV

tag = thead

class gluonhtmlTBODY(components attributes)Bases gluonhtmlDIV

tag = tbody

class gluonhtmlTFOOT(components attributes)Bases gluonhtmlDIV

tag = tfoot

class gluonhtmlTITLE(components attributes)Bases gluonhtmlDIV

tag = title

class gluonhtmlTR(components attributes)Bases gluonhtmlDIV

TR Component

If subcomponents are not TDTH-components they will be wrapped in a TD

tag = tr

class gluonhtmlTT(components attributes)Bases gluonhtmlDIV

tag = tt

gluonhtmlURL(a=None c=None f=None r=None args=None vars=None an-chor=rdquo extension=None env=None hmac_key=None hash_vars=Truesalt=None user_signature=None scheme=None host=None port=None en-code_embedded_slash=False url_encode=True language=None)

generates a url lsquoacfrsquo corresponding to application a controller c and function f If r=request is passed a c fare set respectively to rapplication rcontroller rfunction

The more typical usage is

URL(lsquoindexrsquo)

that generates a url for the index function within the present application and controller

Parameters

bull a ndash application (default to current if r is given)

bull c ndash controller (default to current if r is given)

bull f ndash function (default to current if r is given)

bull r ndash request (optional)

bull args ndash any arguments (optional) Additional ldquopathrdquo elements

bull vars ndash any variables (optional) Querystring elements

bull anchor ndash anchorname without (optional)

131 Template helpers 47

web2py Documentation Release 2146-stable

bull extension ndash force an extension

bull hmac_key ndash key to use when generating hmac signature (optional)

bull hash_vars ndash which of the vars to include in our hmac signature True (default) - hash allvars False - hash none of the vars iterable - hash only the included vars [lsquokey1rsquorsquokey2rsquo]

bull salt ndash salt hashing with this string

bull user_signature ndash signs automatically the URL in such way that only the user canaccess the URL (use with URLverify or authrequires_signature())

bull scheme ndash URI scheme (True lsquohttprsquo or lsquohttpsrsquo etc) forces absolute URL (optional)

bull host ndash string to force absolute URL with host (True means http_host)

bull port ndash optional port number (forces absolute URL)

bull encode_embedded_slash ndash encode slash characters included in args

bull url_encode ndash encode characters included in vars

Raises SyntaxError ndash when no application controller or function is available or when a CRLFis found in the generated url

Examples

gtgtgt str(URL(a=a c=c f=f args=[x y z] vars=p1 q2 anchor=1))acfxyzp=1ampq=21

gtgtgt str(URL(a=a c=c f=f args=[x y z] vars=p(13) q2 anchor=1))acfxyzp=1ampp=3ampq=21

gtgtgt str(URL(a=a c=c f=f args=[x y z] vars=p(31) q2 anchor=1))acfxyzp=3ampp=1ampq=21

gtgtgt str(URL(a=a c=c f=f anchor=1+2))acf12B2

gtgtgt str(URL(a=a c=c f=f args=[x y z] vars=p(13) q2 anchor=1 hmac_key=key))acfxyzp=1ampp=3ampq=2amp_signature=a32530f0d0caa80964bb92aad2bedf8a4486a31f1

gtgtgt str(URL(a=a c=c f=f args=[wx yz]))acfwxyz

gtgtgt str(URL(a=a c=c f=f args=[wx yz] encode_embedded_slash=True))acfw2Fxy2Fz

gtgtgt str(URL(a=a c=c f=f args=[(id)d] url_encode=False))acf(id)d

gtgtgt str(URL(a=a c=c f=f args=[(id)d] url_encode=True))acf2528id29d

48 Chapter 13 html Module

web2py Documentation Release 2146-stable

gtgtgt str(URL(a=a c=c f=f vars=id (id)d url_encode=False))acfid=(id)d

gtgtgt str(URL(a=a c=c f=f vars=id (id)d url_encode=True))acfid=2528id29d

gtgtgt str(URL(a=a c=c f=f anchor=(id)d url_encode=False))acf(id)d

gtgtgt str(URL(a=a c=c f=f anchor=(id)d url_encode=True))acf2528id29d

class gluonhtmlXHTML(components attributes)Bases gluonhtmlDIV

This is XHTML version of the HTML helper

There are three predefined document type definitions They can be specified in the lsquodoctypersquo parameter

bull lsquostrictrsquo enables strict doctype

bull lsquotransitionalrsquo enables transitional doctype (default)

bull lsquoframesetrsquo enables frameset doctype

bull any other string will be treated as userrsquos own doctype

lsquolangrsquo parameter specifies the language of the document and the xml document Defaults to lsquoenrsquo

lsquoxmlnsrsquo parameter specifies the xml namespace Defaults to lsquohttpwwww3org1999xhtmlrsquo

See also DIV

frameset = ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 FramesetEN httpwwww3orgTRxhtml1DTDxhtml1-framesetdtdgtn

strict = ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgtn

tag = html

transitional = ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 TransitionalEN httpwwww3orgTRxhtml1DTDxhtml1-transitionaldtdgtn

xml()generates the xml for this component

xmlns = httpwwww3org1999xhtml

class gluonhtmlXML(text sanitize=False permitted_tags=[rsquoarsquo rsquobrsquo rsquoblockquotersquo rsquobrrsquo rsquoirsquo rsquolirsquo rsquoolrsquorsquoulrsquo rsquoprsquo rsquocitersquo rsquocodersquo rsquoprersquo rsquoimgrsquo rsquoh1rsquo rsquoh2rsquo rsquoh3rsquo rsquoh4rsquo rsquoh5rsquo rsquoh6rsquo rsquotablersquo rsquotrrsquorsquotdrsquo rsquodivrsquo rsquostrongrsquo rsquospanrsquo] allowed_attributes=rsquoarsquo [rsquohrefrsquo rsquotitlersquo rsquotargetrsquo]rsquoblockquotersquo [rsquotypersquo] rsquoimgrsquo [rsquosrcrsquo rsquoaltrsquo] rsquotdrsquo [rsquocolspanrsquo])

Bases gluonhtmlXmlComponent

use it to wrap a string that contains XMLHTML so that it will not be escaped by the template

Examples

gtgtgt XML(lth1gtHellolth1gt)xml()lth1gtHellolth1gt

elements(args kargs)to be considered experimental since the behavior of this method is questionable another option could beTAG(selftext)elements(args kwargs)

131 Template helpers 49

web2py Documentation Release 2146-stable

flatten(render=None)returns the text stored by the XML object rendered by the render function

xml()

gluonhtmlxmlescape(data quote=True)Returns an escaped string of the provided data

Parameters

bull data ndash the data to be escaped

bull quote ndash optional (default False)

gluonhtmlembed64(filename=None file=None data=None extension=rsquoimagegifrsquo)helper to encode the provided (binary) data into base64

Parameters

bull filename ndash if provided opens and reads this file in lsquorbrsquo mode

bull file ndash if provided reads this file

bull data ndash if provided uses the provided data

50 Chapter 13 html Module

CHAPTER 14

http Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

141 HTTP statuses helpers

exception gluonhttpHTTP(status body=rdquo cookies=None headers)Bases exceptionsException

Raises an HTTP response

Parameters

bull status ndash usually an integer If itrsquos a well known status code the ERROR message will beautomatically added A string can also be passed as 510 Foo Bar and in that case the statuscode and the error message will be parsed accordingly

bull body ndash what to return as body If left as is will return the error code and the status messagein the body itself

bull cookies ndash pass cookies along (usually not needed)

bull headers ndash pass headers as usual dict mapping

cookies2headers(cookies)

messagecompose a message describing this exception

ldquostatus defined_status [web2py_error]rdquo

message elements that are not defined are omitted

to(responder env=None)

51

web2py Documentation Release 2146-stable

gluonhttpredirect(location=rdquo how=303 client_side=False headers=None)Raises a redirect (303)

Parameters

bull location ndash the url where to redirect

bull how ndash what HTTP status code to use when redirecting

bull client_side ndash if set to True it triggers a reload of the entire page when the fragmenthas been loaded as a component

52 Chapter 14 http Module

CHAPTER 15

languages Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)Plural subsystem is created by Vladyslav Kozlovskyy (Ukraine) ltdbdevelopgmailcomgt

151 Translation system

class gluonlanguagestranslator(langpath http_accept_language)Bases object

This class is instantiated by gluoncompileappbuild_environment as the T object

Example

Tforce(None) turns off translation Tforce(lsquofr itrsquo) forces web2py to translate using frpy or itpy

T(ldquoHello Worldrdquo) translates ldquoHello Worldrdquo using the selected file

Note

bull there is no need to force since by default T uses http_accept_language to determine a translation file

bull en and en-en are considered different languages

bull if language xx-yy is not found force() probes other similar languages using such algorithm xx-yypy -gtxxpy -gt xx-yypy -gt xxpy

M(message symbols= language=None lazy=None filter=None ftag=None ns=None)Gets cached translated markmin-message with inserted parametes if lazy==True lazyT object is returned

apply_filter(message symbols= filter=None ftag=None)

53

web2py Documentation Release 2146-stable

force(languages)Selects language(s) for translation

if a list of languages is passed as a parameter the first language from this list that matches the ones fromthe possible_languages dictionary will be selected

default language will be selected if none of them matches possible_languages

get_possible_languages()Gets list of all possible languages for current application

get_possible_languages_info(lang=None)Returns info for selected language or dictionary with all possible languages info from APPlanguagespyIt Returns

bull a tuple containing

langcode langname langfile_mtimepluraldict_fname pluraldict_mtimeprules_langcode npluralsget_plural_id construct_plural_form

or None

bull if lang is NOT defined a dictionary with all possible languages

langcode(from filename)( langcode language code from langcodelangname

language name in national spelling from langnamelangfile_mtime m_time of language filepluraldict_fname name of plural dictionary file or None (when

rarr˓defaultpy is not exist)pluraldict_mtime m_time of plural dictionary file or 0 if file is

rarr˓not existprules_langcode code of plural rules language or defaultnplurals nplurals for current languageget_plural_id get_plural_id() for current languageconstruct_plural_form) construct_plural_form() for current

rarr˓language

Parameters lang (str) ndash language

get_t(message prefix=rdquo)Use to add a comment into a translation string the comment can be useful do discriminate differentpossible translations for the same string (for example different locations)

T( hello world ) -gt hello world T( hello world token) -gt hello world T(hello world token) -gt hello world

the notation is ignored in multiline strings and strings that start with This is needed to allow markminsyntax to be translated

params_substitution(message symbols)Substitutes parameters from symbols into message using also parse placeholders for plural-formsprocessing

Returns string with parameters

54 Chapter 15 languages Module

web2py Documentation Release 2146-stable

Note symbols MUST BE OR tuple OR dict of parameters

plural(word n)Gets plural form of word for number n invoked from T()TM() in tag

Note ldquowordrdquo MUST be defined in current language (Taccepted_language)

Parameters

bull word (str) ndash word in singular

bull n (numeric) ndash number plural form created for

Returns word in appropriate singularplural form

Return type word (str)

set_current_languages(languages)Sets current AKA ldquodefaultrdquo languages Setting one of this languages makes the force() function to turntranslation off

translate(message symbols)Gets cached translated message with inserted parameters(symbols)

gluonlanguagesfindT(path language=rsquoenrsquo)

Note Must be run by the admin app

gluonlanguagesupdate_all_languages(application_path)

Note Must be run by the admin app

151 Translation system 55

web2py Documentation Release 2146-stable

56 Chapter 15 languages Module

CHAPTER 16

main Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

161 The gluon wsgi application

gluonmainwsgibase(environ responder)The gluon wsgi application The first function called when a page is requested (static or dynamic) It can becalled by pastehttpserver or by apache mod_wsgi (or any WSGI-compatible server)

bull fills request with info

bull the environment variables replacing lsquorsquo with lsquo_rsquo

bull adds web2py path and version info

bull compensates for fcgi missing path_info and query_string

bull validates the path in url

The url path must be either

1 for static pages

bull ltapplicationgtstaticltfilegt

2 for dynamic pages

bull ltapplicationgt[ltcontrollergt[ltfunctiongt[ltsubgt]]][ltextensiongt]

The naming conventions are

bull application controller function and extension may only contain [a-zA-Z0-9_]

57

web2py Documentation Release 2146-stable

bull file and sub may also contain lsquo-lsquo lsquo=rsquo lsquorsquo and lsquorsquo

gluonmainsave_password(password port)Used by main() to save the password in the parameters_portpy file

gluonmainappfactory(wsgiapp=ltfunction wsgibasegt logfilename=rsquohttpserverlogrsquo pro-filer_dir=None profilerfilename=None)

generates a wsgi application that does logging and profiling and calls wsgibase

Parameters

bull wsgiapp ndash the base application

bull logfilename ndash where to store apache-compatible requests log

bull profiler_dir ndash where to store profile files

class gluonmainHttpServer(ip=rsquo127001rsquo port=8000 password=rdquopid_filename=rsquohttpserverpidrsquo log_filename=rsquohttpserverlogrsquoprofiler_dir=None ssl_certificate=None ssl_private_key=Nonessl_ca_certificate=None min_threads=None max_threads=Noneserver_name=None request_queue_size=5 timeout=10socket_timeout=1 shutdown_timeout=None path=None inter-faces=None)

Bases object

the web2py web server (Rocket)

start()start the web server

stop(stoplogging=False)stop cron and the web server

58 Chapter 16 main Module

CHAPTER 17

messageboxhandler Module

class gluonmessageboxhandlerMessageBoxHandlerBases loggingHandler

emit(record)Do whatever it takes to actually log the specified logging record

This version is intended to be implemented by subclasses and so raises a NotImplementedError

class gluonmessageboxhandlerNotifySendHandlerBases loggingHandler

emit(record)Do whatever it takes to actually log the specified logging record

This version is intended to be implemented by subclasses and so raises a NotImplementedError

59

web2py Documentation Release 2146-stable

60 Chapter 17 messageboxhandler Module

CHAPTER 18

myregex Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

181 Useful regexes

61

web2py Documentation Release 2146-stable

62 Chapter 18 myregex Module

CHAPTER 19

newcron Module

This file is part of the web2py Web FrameworkCreated by Attila Csipa ltweb2pycsipainrsgtModified by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

Cron-style interface

class gluonnewcronToken(path)Bases object

acquire(startup=False)Returns the time when the lock is acquired or None if cron already running

lock is implemented by writing a pickle (start stop) in cronmaster start is time when cron job starts andstop is time when cron completed stop == 0 if job started but did not yet complete if a cron job startedwithin less than 60 seconds acquire returns None if a cron job started before 60 seconds and did not stopa warning is issue ldquoStale cronmaster detectedrdquo

release()Writes into cronmaster the time when cron job was completed

gluonnewcronabsolute_path_link(path)Returns an absolute path for the destination of a symlink

gluonnewcroncrondance(applications_parent ctype=rsquosoftrsquo startup=False apps=None)

class gluonnewcroncronlauncher(cmd shell=True)Bases threadingThread

run()Method representing the threadrsquos activity

You may override this method in a subclass The standard run() method invokes the callable object passedto the objectrsquos constructor as the target argument if any with sequential and keyword arguments takenfrom the args and kwargs arguments respectively

63

web2py Documentation Release 2146-stable

class gluonnewcronextcron(applications_parent apps=None)Bases threadingThread

run()Method representing the threadrsquos activity

You may override this method in a subclass The standard run() method invokes the callable object passedto the objectrsquos constructor as the target argument if any with sequential and keyword arguments takenfrom the args and kwargs arguments respectively

class gluonnewcronhardcron(applications_parent)Bases threadingThread

launch()

run()Method representing the threadrsquos activity

You may override this method in a subclass The standard run() method invokes the callable object passedto the objectrsquos constructor as the target argument if any with sequential and keyword arguments takenfrom the args and kwargs arguments respectively

gluonnewcronparsecronline(line)

gluonnewcronrangetolist(s period=rsquominrsquo)

class gluonnewcronsoftcron(applications_parent)Bases threadingThread

run()Method representing the threadrsquos activity

You may override this method in a subclass The standard run() method invokes the callable object passedto the objectrsquos constructor as the target argument if any with sequential and keyword arguments takenfrom the args and kwargs arguments respectively

gluonnewcronstopcron()Graceful shutdown of cron

64 Chapter 19 newcron Module

CHAPTER 20

portalocker Module

Cross-platform (posixnt) API for flock-style file locking

Synopsis

import portalockerfile = open(somefile r+)portalockerlock(file portalockerLOCK_EX)fileseek(12)filewrite(foo)fileclose()

If you know what yoursquore doing you may choose to

portalockerunlock(file)

before closing the file but why

Methods

lock( file flags )unlock( file )

Constants

LOCK_EXLOCK_SHLOCK_NB

I learned the win32 technique for locking files from sample code provided by John Nielsen ltnielsenjfmy-dejacomgtin the documentation that accompanies the win32 modules

Author Jonathan Feinberg ltjdfpoboxcomgt Version $Id portalockerpyv 13 20010529 184755 AdministratorExp $

class gluonportalockerLockedFile(filename mode=rsquorbrsquo)Bases object

65

web2py Documentation Release 2146-stable

close()

read(size=None)

readline()

readlines()

write(data)

gluonportalockerlock(file flags)

gluonportalockerread_locked(filename)

gluonportalockerunlock(file)

gluonportalockerwrite_locked(filename data)

66 Chapter 20 portalocker Module

CHAPTER 21

recfile Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

211 Generates names for cache and session files

gluonrecfileexists(filename path=None)

gluonrecfilegenerate(filename depth=2 base=512)

gluonrecfileopen(filename mode=rsquorrsquo path=None)

gluonrecfileremove(filename path=None)

67

web2py Documentation Release 2146-stable

68 Chapter 21 recfile Module

CHAPTER 22

restricted Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

221 Restricted environment to execute applicationrsquos code

exception gluonrestrictedRestrictedError(layer=rdquo code=rdquo output=rdquo environ-ment=None)

Bases exceptionsException

Class used to wrap an exception that occurs in the restricted environment below The traceback is used to logthe exception and generate a ticket

load(request app ticket_id)Loads a logged exception

log(request)Logs the exception

gluonrestrictedrestricted(code environment=None layer=rsquoUnknownrsquo)Runs code in environment and returns the output If an exception occurs in code it raises a RestrictedErrorcontaining the traceback Layer is passed to RestrictedError to identify where the error occurred

class gluonrestrictedTicketStorage(db=None tablename=rsquoweb2py_ticketrsquo)Bases gluonstorageStorage

Defines the ticket object and the default values of its members (None)

load(request app ticket_id)

store(request ticket_id ticket_data)Stores the ticket It will figure out if this must be on disk or in db

gluonrestrictedcompile2(code layer)The +n is necessary else compile fails when code ends in a comment

69

web2py Documentation Release 2146-stable

70 Chapter 22 restricted Module

CHAPTER 23

rewrite Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

gluonrewrite parses incoming URLs and formats outgoing URLs for gluonhtmlURL

In addition it rewrites both incoming and outgoing URLs based on the (optional) user-supplied routespy which alsoallows for rewriting of certain error messages

routespy supports two styles of URL rewriting depending on whether lsquoroutersrsquo is defined Refer to routerexamplepyand routesexamplepy for additional documentation

class gluonrewriteMapUrlIn(request=None env=None)Bases object

Logic for mapping incoming URLs

arg0Returns first arg

harg0Returns first arg with optional hyphen mapping

map_app()Determines application name

map_controller()Identifies controller

map_function()Handles functionextension

map_language()Handles language (no hyphen mapping)

71

web2py Documentation Release 2146-stable

map_prefix()Strips path prefix if present in its entirety

map_root_static()Handles root-static files (no hyphen mapping)

a root-static file is one whose incoming URL expects it to be at the root typically robotstxt amp faviconico

map_static()Handles static files file_match but no hyphen mapping

pop_arg_if(dopop)Conditionally removes first arg and returns new first arg

sluggify()

update_request()Updates request from self Builds envrequest_uri Makes lower-case versions of http headers in env

validate_args()Checks args against validation pattern

class gluonrewriteMapUrlOut(request env application controller function args other schemehost port language)

Bases object

Logic for mapping outgoing URLs

acf()Converts components to applangcontrollerfunction

build_acf()Builds acf from components

omit_acf()Omits what we can of acf

omit_lang()Omits language if possible

gluonrewritecompile_regex(k v env=None)Preprocess and compile the regular expressions in routes_appinout The resulting regex will match a pattern ofthe form

[remote address][protocol][host][method] [path]

We allow abbreviated regexes on input here we try to complete them

gluonrewritefilter_err(status application=rsquoapprsquo ticket=rsquotktrsquo)doctestunittest interface to routes_onerror

gluonrewritefilter_url(url method=rsquogetrsquo remote=rsquo0000rsquo out=False app=False lang=Nonedomain=(None None) env=False scheme=None host=Noneport=None language=None)

doctestunittest interface to regex_filter_in() and regex_filter_out()

gluonrewritefixup_missing_path_info(environ)

gluonrewriteget_effective_router(appname)Returns a private copy of the effective router for the specified application

gluonrewriteinvalid_url(routes)

72 Chapter 23 rewrite Module

web2py Documentation Release 2146-stable

gluonrewriteload(routes=rsquoroutespyrsquo app=None data=None rdict=None)load read (if file) and parse routes store results in params (called from mainpy at web2py initialization time)If data is present itrsquos used instead of the routespy contents If rdict is present it must be a dict to be used forrouters (unit test)

gluonrewriteload_routers(all_apps)Load-time post-processing of routers

gluonrewritelog_rewrite(string)Log rewrite activity under control of routespy

gluonrewritemap_url_in(request env app=False)Routes incoming URL

gluonrewritemap_url_out(request env application controller function args other scheme hostport language=None)

Supply acf (or alangcf) portion of outgoing url

The basic rule is that we can only make transformations that map_url_in can reverse

Suppose that the incoming arguments are acfargslang and that the router defaults are da dc df dl

We can perform these transformations trivially if args=[] and lang=None or dl

dadcdf =gt adcdf =gt aacdf =gt ac

We would also like to be able to strip the default application or applicationcontroller from URLs with func-tionargs present thus

dacfargs =gt cfargsdadcfargs =gt fargs

We use [applications] and [controllers] and functions to suppress ambiguous omissions

We assume that language names do not collide with acf names

gluonrewriteregex_filter_in(e)Regex rewrite incoming URL

gluonrewriteregex_filter_out(url e=None)Regex rewrite outgoing URL

gluonrewriteregex_select(env=None app=None request=None)Selects a set of regex rewrite params for the current request

gluonrewriteregex_uri(e regexes tag default=None)Filters incoming URI against a list of regexes

gluonrewriteregex_url_in(request environ)Rewrites and parses incoming URL

gluonrewritesluggify(key)

gluonrewritetry_redirect_on_error(http_object request ticket=None)Called from mainwsgibase to rewrite the http response

gluonrewritetry_rewrite_on_error(http_response request environ ticket=None)Called from mainwsgibase to rewrite the http response

gluonrewriteurl_in(request environ)Parses and rewrites incoming URL

73

web2py Documentation Release 2146-stable

gluonrewriteurl_out(request environ application controller function args other scheme hostport language=None)

Assembles and rewrites outgoing URL

74 Chapter 23 rewrite Module

CHAPTER 24

sanitizer Module

From httpaspnactivestatecomASPNCookbookPythonRecipe496942Submitter Josh Goldfoot (other recipes)Last Updated 20060805Version 10

241 Cross-site scripting (XSS) defense

gluonsanitizersanitize(text permitted_tags=[rsquoarsquo rsquobrsquo rsquoblockquotersquo rsquobrrsquo rsquoirsquo rsquolirsquo rsquoolrsquo rsquoulrsquorsquoprsquo rsquocitersquo rsquocodersquo rsquoprersquo rsquoimgrsquo rsquoh1rsquo rsquoh2rsquo rsquoh3rsquo rsquoh4rsquo rsquoh5rsquo rsquoh6rsquo rsquota-blersquo rsquotbodyrsquo rsquotheadrsquo rsquotfootrsquo rsquotrrsquo rsquotdrsquo rsquodivrsquo rsquostrongrsquo rsquospanrsquo] al-lowed_attributes=rsquoarsquo [rsquohrefrsquo rsquotitlersquo] rsquoblockquotersquo [rsquotypersquo] rsquoimgrsquo[rsquosrcrsquo rsquoaltrsquo] rsquotdrsquo [rsquocolspanrsquo] escape=True)

75

web2py Documentation Release 2146-stable

76 Chapter 24 sanitizer Module

CHAPTER 25

scheduler Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

251 Background processes made simple

class gluonschedulerJobGraph(db job_name)Bases object

Experimental dependencies amongs tasks

add_deps(task_parent task_child)Create a dependency between task_parent and task_child

validate(job_name=None)Validate if all tasks job_name can be completed

Checks if there are no mutual dependencies among tasks Commits at the end if successfull or it rollbacksthe entire transaction Handle with care

class gluonschedulerMetaSchedulerBases threadingThread

Base class documenting schedulerrsquos base methods

async(task)Start the background process

Parameters task ndash a Task object

Returns

containing

77

web2py Documentation Release 2146-stable

(okresultoutput)(errorexceptionNone)(timeoutNoneNone)(terminatedNoneNone)

Return type tuple

die()Forces termination of the worker process along with any running task

give_up()Waits for any running task to be executed then exits the worker process

loop()Main loop fetching tasks and starting executorrsquos background processes

pop_task()Fetches a task ready to be executed

report_task(task task_report)Creates a task report

run()This is executed by the main thread to send heartbeats

send_heartbeat(counter)

sleep()

start_heartbeats()

terminate_process()Terminates any running tasks (internal use only)

class gluonschedulerScheduler(db tasks=None migrate=True worker_name=Nonegroup_names=None heartbeat=3 max_empty_runs=0discard_results=False utc_time=False)

Bases gluonschedulerMetaScheduler

Scheduler object

Parameters

bull db ndash DAL connection where Scheduler will create its tables

bull tasks (dict) ndash either a dict containing namendashgtfunc or None If None functions will besearched in the environment

bull migrate (bool) ndash turn migration onoff for the Schedulerrsquos tables

bull worker_name (str) ndash force worker_name to identify each process Leave it to None toautoassign a name (hostnamepid)

bull group_names (list) ndash process tasks belonging to this group defaults to [lsquomainrsquo] if noth-ing gets passed

bull heartbeat (int) ndash how many seconds the worker sleeps between one execution and thefollowing one Indirectly sets how many seconds will pass between checks for new tasks

bull max_empty_runs (int) ndash how many loops are allowed to pass without processing anytasks before exiting the process 0 to keep always the process alive

78 Chapter 25 scheduler Module

web2py Documentation Release 2146-stable

bull discard_results (bool) ndash Scheduler stores executionsrsquos details into the sched-uler_run table By default only if there is a result the details are kept Turning this toTrue means discarding results even for tasks that return something

bull utc_time (bool) ndash do all datetime calculations assuming UTC as the timezone Remem-ber to pass start_time and stop_time to tasks accordingly

adj_hibernation()Used to increase the ldquosleeprdquo interval for DISABLED workers

assign_tasks(db)Assign task to workers that can then pop them from the queue

Deals with group_name(s) logic in order to assign linearly tasks to available workers for those groups

being_a_ticker()Elect a TICKER process that assigns tasks to available workers

Does its best to elect a worker that is not busy processing other tasks to allow a proper distribution of tasksamong all active workers ASAP

define_tables(db migrate)Define Scheduler tables structure

disable(group_names=None limit=None worker_name=None)Set DISABLED on the workers processing group_names tasks

A DISABLED worker will be kept alive but it wonrsquot be able to process any waiting tasks essentiallyputting it to sleep By default all group_names of Schedulerrsquos instantation are selected

get_workers(only_ticker=False)Returns a dict holding worker_name columns representing all ldquoregisteredrdquo workers only_ticker re-turns only the workers running as a TICKER if there are any

kill(group_names=None limit=None worker_name=None)Sets KILL as worker status The worker will be killed even if itrsquos processing a task

loop(worker_name=None)Main loop

This works basically as a neverending loop that

bull checks if the worker is ready to process tasks (is not DISABLED)

bull pops a task from the queue

bull if there is a task

ndash spawns the executor background process

ndash waits for the process to be finished

ndash sleeps heartbeat seconds

bull if there is not a task

ndash checks for max_empty_runs

ndash sleeps heartbeat seconds

now()Shortcut that fetches current time based on UTC preferences

pop_task(db)Grab a task ready to be executed from the queue

251 Background processes made simple 79

web2py Documentation Release 2146-stable

queue_task(function pargs=[] pvars= kwargs)Queue tasks This takes care of handling the validation of all parameters

Parameters

bull function ndash the function (anything callable with a __name__)

bull pargs ndash ldquorawrdquo args to be passed to the function Automatically jsonified

bull pvars ndash ldquorawrdquo kwargs to be passed to the function Automatically jsonified

bull kwargs ndash all the parameters available (basically every scheduler_task column) If argsand vars are here they should be jsonified already and they will override pargs and pvars

Returns a dict just as a normal validate_and_insert() plus a uuid key holding the uuid of thequeued task If validation is not passed ( ie some parameters are invalid) both id and uuidwill be None and yoursquoll get an ldquoerrorrdquo dict holding the errors found

report_task(task task_report)Take care of storing the result according to preferences

Deals with logic for repeating tasks

resume(group_names=None limit=None worker_name=None)Wakes a worker up (it will be able to process queued tasks)

send_heartbeat(counter)Coordination among available workers

It - sends the heartbeat - elects a ticker among available workers (the only process that

effectively dispatch tasks to workers)

bull deals with workerrsquos statuses

bull does ldquohousecleaningrdquo for dead workers

bull triggers tasks assignment to workers

set_requirements(scheduler_task)Called to set defaults for lazy_tables connections

set_worker_status(group_names=None action=rsquoACTIVErsquo exclude=None limit=Noneworker_name=None)

Internal function to set workerrsquos status

sleep()Calculate the number of seconds to sleep

stop_task(ref)Shortcut for task termination

If the task is RUNNING it will terminate it meaning that status will be set as FAILED

If the task is QUEUED its stop_time will be set as to ldquonowrdquo the enabled flag will be set to False andthe status to STOPPED

Parameters ref ndash can be

bull an integer lookup will be done by scheduler_taskid

bull a string lookup will be done by scheduler_taskuuid

Returns

bull 1 if task was stopped (meaning an update has been done)

80 Chapter 25 scheduler Module

web2py Documentation Release 2146-stable

bull None if task was not found or if task was not RUNNING or QUEUED

Note Experimental

task_status(ref output=False)Retrieves task status and optionally the result of the task

Parameters

bull ref ndash can be

ndash an integer lookup will be done by scheduler_taskid

ndash a string lookup will be done by scheduler_taskuuid

ndash a Query lookup as you wish eg

dbscheduler_tasktask_name == test1

bull output (bool) ndash if True fetch also the scheduler_run record

Returns a single Row object for the last queued task If output == True returns also the lastscheduler_run record The scheduler_run record is fetched by a left join so it can have allfields == None

terminate(group_names=None limit=None worker_name=None)Sets TERMINATE as worker status The worker will wait for any currently running tasks to be executedand then it will exit gracefully

static total_seconds(td)Backport for py26

update_dependencies(db task_id)Unblock execution paths for Jobs

wrapped_assign_tasks(db)Commodity function to call assign_tasks and trap exceptions

If an exception is raised assume it happened because of database contention and retries assign_task after05 seconds

wrapped_pop_task()Commodity function to call pop_task and trap exceptions

If an exception is raised assume it happened because of database contention and retries pop_task after 05seconds

wrapped_report_task(task task_report)Commodity function to call report_task and trap exceptions

If an exception is raised assume it happened because of database contention and retries pop_task after 05seconds

class gluonschedulerTYPE(myclass=lttype rsquolistrsquogt parse=False)Bases object

Validator that checks whether field is valid json and validates its type Used for args and vars of the sched-uler_task table

class gluonschedulerTask(app function timeout args=rsquo[]rsquo vars=rsquorsquo kwargs)Bases object

251 Background processes made simple 81

web2py Documentation Release 2146-stable

Defines a ldquotaskrdquo object that gets passed from the main thread to the executorrsquos one

class gluonschedulerTaskReport(status result=None output=None tb=None)Bases object

Defines a ldquotask reportrdquo object that gets passed from the executorrsquos thread to the main one

gluonschedulerexecutor(queue task out)The function used to execute tasks in the background process

gluonschedulermain()allows to run worker without python web2pypy by simply

python gluonschedulerpy

82 Chapter 25 scheduler Module

CHAPTER 26

serializers Module

This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

gluonserializerscast_keys(o cast=lttype rsquostrrsquogt encoding=rsquoutf-8rsquo)Builds a new object with ltcastgt type keys Use this function if you are in Python lt 265 This avoids syntaxerrors when unpacking dictionary arguments

Parameters

bull o ndash is the object input

bull cast ndash (defaults to str) is an object type or function which supports conversion such as

converted = cast(o)

bull encoding ndash (defaults to utf-8) is the encoding for unicode keys This is not used forcustom cast functions

gluonserializerscsv(value)

gluonserializerscustom_json(o)

gluonserializersics(events title=None link=None timeshift=0 calname=True ignored)

gluonserializersjson(value default=ltfunction custom_jsongt)

gluonserializersloads_json(o unicode_keys=True kwargs)

gluonserializersloads_yaml(data)

gluonserializersrss(feed)

gluonserializerssafe_encode(text)

gluonserializersxml(value encoding=rsquoUTF-8rsquo key=rsquodocumentrsquo quote=True)

gluonserializersxml_rec(value key quote=True)

gluonserializersyaml(data)

83

web2py Documentation Release 2146-stable

84 Chapter 26 serializers Module

CHAPTER 27

settings Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

85

web2py Documentation Release 2146-stable

86 Chapter 27 settings Module

CHAPTER 28

shell Module

This file is part of the web2py Web FrameworkDeveloped by Massimo Di Pierro ltmdipierrocsdepauledugtlimodou ltlimodougmailcomgt and srackham ltsrackhamgmailcomgtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

281 Web2py environment in the shell

gluonshelldie(msg)

gluonshellenable_autocomplete_and_history(adir env)

gluonshellenv(a import_models=False c=None f=None dir=rdquo extra_request=)Returns web2py execution environment for application (a) controller (c) function (f) If import_models is Truethe exec all application models into the environment

extra_request allows you to pass along any extra variables to the request object before your models get executedThis was mainly done to support web2py_utilstest_runner however you can use it with any wrapper scripts thatneed access to the web2py environment

gluonshellexec_environment(pyfile=rdquo request=None response=None session=None)Environment builder and module loader

Builds a web2py environment and optionally executes a Python file into the environment

A Storage dictionary containing the resulting environment is returned The working directory must be web2pyroot ndash this is the web2py default

gluonshellexec_pythonrc()

gluonshellexecute_from_command_line(argv=None)

gluonshellget_usage()

87

web2py Documentation Release 2146-stable

gluonshellparse_path_info(path_info av=False)Parses path info formatted like acf where c and f are optional and a leading is accepted Return tuple (a c f)If invalid path_info a is set to None If c or f are omitted they are set to None If av=True parse args and vars

gluonshellrun(appname plain=False import_models=False startfile=None bpython=Falsepython_code=False cronjob=False)

Start interactive shell or run Python script (startfile) in web2py controller environment appname is formattedlike

bull a web2py application name

bull ac exec the controller c into the application environment

gluonshelltest(testpath import_models=True verbose=False)Run doctests in web2py environment testpath is formatted like

bull a tests all controllers in application a

bull ac tests controller c in application a

bull acf test function f in controller c application a

Where a c and f are application controller and function names respectively If the testpath is a file name the fileis tested If a controller is specified models are executed by default

88 Chapter 28 shell Module

CHAPTER 29

sql Module

This file is part of the web2py Web FrameworkDeveloped by Massimo Di Pierro ltmdipierrocsdepauledugtlimodou ltlimodougmailcomgt and srackham ltsrackhamgmailcomgtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

291 Just for backward compatibility

class gluonsqlDAL(uri=rsquosqlitedummydbrsquo pool_size=0 folder=None db_codec=rsquoUTF-8rsquo check_reserved=None migrate=True fake_migrate=False mi-grate_enabled=True fake_migrate_all=False decode_credentials=Falsedriver_args=None adapter_args=None attempts=5 auto_import=False big-int_id=False debug=False lazy_tables=False db_uid=None do_connect=Trueafter_connection=None tables=None ignore_field_case=True en-tity_quoting=False table_hash=None)

Bases pydalhelpersclassesSerializable pydalhelpersclassesBasicStorage

An instance of this class represents a database connection

Parameters

bull uri (str) ndash contains information for connecting to a database Defaults tolsquosqlitedummydbrsquo

Note experimental you can specify a dictionary as uri parameter ie with

db = DAL(uri sqlitestoragesqlitetables )

for an example of dict input you can check the output of the scaffolding db model with

dbas_dict()

89

web2py Documentation Release 2146-stable

Note that for compatibility with Python older than version 265 you should cast your dictinput keys to str due to a syntax limitation on kwarg names for proper DAL dictionary inputyou can use one of

obj = serializerscast_keys(dict [encoding=utf-8])or else (for parsing json input)obj = serializersloads_json(data unicode_keys=False)

bull pool_size ndash How many open connections to make to the database object

bull folder ndash where table files will be created Automatically set within web2py Use anexplicit path when using DAL outside web2py

bull db_codec ndash string encoding of the database (default lsquoUTF-8rsquo)

bull table_hash ndash database identifier with tables If your connection hash change you canstill using old tables if they have db_hash as prefix

bull check_reserved ndash list of adapters to check tablenames and column names againstsqlnosql reserved keywords Defaults to None

ndash rsquocommonrsquo List of sql keywords that are common to all database types such as ldquoSELECTINSERTrdquo (recommended)

ndash rsquoallrsquo Checks against all known SQL keywords

ndash rsquoltadapternamegtrdquo Checks against the specific adapters list of keywords

ndash rsquoltadapternamegt_nonreservedrsquo Checks against the specific adapters list of nonreservedkeywords (if available)

bull migrate ndash sets default migrate behavior for all tables

bull fake_migrate ndash sets default fake_migrate behavior for all tables

bull migrate_enabled ndash If set to False disables ALL migrations

bull fake_migrate_all ndash If set to True fake migrates ALL tables

bull attempts ndash Number of times to attempt connecting

bull auto_import ndash If set to True tries import automatically table definitions from thedatabases folder (works only for simple models)

bull bigint_id ndash If set turn on bigint instead of int for id and reference fields

bull lazy_tables ndash delays table definition until table access

bull after_connection ndash can a callable that will be executed after the connection

Example

Use as

db = DAL(sqlitetestdb)

or

90 Chapter 29 sql Module

web2py Documentation Release 2146-stable

db = DAL(uri tables []) experimental

dbdefine_table(tablename Field(fieldname1)Field(fieldname2))

class Field(fieldname type=rsquostringrsquo length=None default=ltfunction ltlambdagtgt re-quired=False requires=ltfunction ltlambdagtgt ondelete=rsquoCASCADErsquo not-null=False unique=False uploadfield=True widget=None label=None com-ment=None writable=True readable=True update=None authorize=Noneautodelete=False represent=None uploadfolder=None uploadseparate=Falseuploadfs=None compute=None custom_store=None custom_retrieve=Nonecustom_retrieve_file_properties=None custom_delete=None filter_in=None fil-ter_out=None custom_qualifier=None map_none=None rname=None)

Bases pydalobjectsExpression pydalhelpersclassesSerializable

Lazyalias of FieldMethod

Methodalias of FieldMethod

Virtualalias of FieldVirtual

as_dict(flat=False sanitize=True)

clone(point_self_references_to=False args)

count(distinct=None)

formatter(value)

retrieve(name path=None nameonly=False)If nameonly==True return (filename fullfilename) instead of (filename stream)

retrieve_file_properties(name path=None)

set_attributes(args attributes)

sqlsafe

sqlsafe_name

store(file filename=None path=None)

validate(value)

class Row(args kwargs)Bases pydalhelpersclassesBasicStorage

A dictionary that lets you do d[lsquoarsquo] as well as da this is only used to store a Row

as_dict(datetime_to_str=False custom_types=None)

as_json(mode=rsquoobjectrsquo default=None colnames=None serialize=True kwargs)serializes the row to a JSON object kwargs are passed to as_dict method only ldquoobjectrdquo mode sup-ported

serialize = False used by Rowsas_json

TODO return array mode with query column order

mode and colnames are not implemented

as_xml(row_name=rsquorowrsquo colnames=None indent=rsquo rsquo)

291 Just for backward compatibility 91

web2py Documentation Release 2146-stable

get(key default=None)

class Table(db tablename fields args)Bases pydalhelpersclassesSerializable pydalhelpersclassesBasicStorage

Represents a database table

Example

You can create a table as db = DAL( ) dbdefine_table(lsquousersrsquo Field(lsquonamersquo))

And then

dbusersinsert(name=me) print dbusers_insert() to see SQLdbusersdrop()

as_dict(flat=False sanitize=True)

bulk_insert(items)here items is a list of dictionaries

drop(mode=rdquo)

fields

import_from_csv_file(csvfile id_map=None null=rsquoltNULLgtrsquo unique=rsquouuidrsquoid_offset=None args kwargs)

Import records from csv file Column headers must have same names as table fields Field lsquoidrsquo isignored If column names read lsquotablefilersquo the lsquotablersquo prefix is ignored

bull lsquouniquersquo argument is a field which must be unique (typically a uuid field)bull lsquorestorersquo argument is default False if set True will remove old values in table firstbull lsquoid_maprsquo if set to None will not map ids

The import will keep the id numbers in the restored table This assumes that there is an field of typeid that is integer and in incrementing order Will keep the id numbers in restored table

insert(fields)

on(query)

sqlsafe

sqlsafe_alias

truncate(mode=None)

update(args kwargs)

update_or_insert(_key=ltfunction ltlambdagtgt values)

validate_and_insert(fields)

validate_and_update(_key=ltfunction ltlambdagtgt fields)

validate_and_update_or_insert(_key=ltfunction ltlambdagtgt fields)

with_alias(alias)

as_dict(flat=False sanitize=True)

can_join()

check_reserved_keyword(name)Validates name against SQL keywords Uses selfcheck_reserve which is a list of operators to use

close()

92 Chapter 29 sql Module

web2py Documentation Release 2146-stable

commit()

define_table(tablename fields args)

static distributed_transaction_begin(instances)

static distributed_transaction_commit(instances)

executesql(query placeholders=None as_dict=False fields=None colnames=Noneas_ordered_dict=False)

Executes an arbitrary query

Parameters

bull query (str) ndash the query to submit to the backend

bull placeholders ndash is optional and will always be None If using raw SQL with place-holders placeholders may be a sequence of values to be substituted in or (if supported bythe DB driver) a dictionary with keys matching named placeholders in your SQL

bull as_dict ndash will always be None when using DAL If using raw SQL can be set to Trueand the results cursor returned by the DB driver will be converted to a sequence of dic-tionaries keyed with the db field names Results returned with as_dict=True are the sameas those returned when applying to_list() to a DAL query If ldquoas_ordered_dictrdquo=True thebehaviour is the same as when ldquoas_dictrdquo=True with the keys (field names) guaranteed tobe in the same order as returned by the select name executed on the database

bull fields ndash list of DAL Fields that match the fields returned from the DB The Field objectsshould be part of one or more Table objects defined on the DAL object The ldquofieldsrdquo listcan include one or more DAL Table objects in addition to or instead of including Fieldobjects or it can be just a single table (not in a list) In that case the Field objects will beextracted from the table(s)

Note if either fields or colnames is provided the results will be converted to a DAL Rowsobject using the db_adapterparse() method

bull colnames ndash list of field names in tablenamefieldname format

Note It is also possible to specify both ldquofieldsrdquo and the associated ldquocolnamesrdquo In that case ldquofieldsrdquocan also include DAL Expression objects in addition to Field objects For Field objects in ldquofieldsrdquo theassociated ldquocolnamesrdquo must still be in tablenamefieldname format For Expression objects in ldquofieldsrdquo theassociated ldquocolnamesrdquo can be any arbitrary labels

DAL Table objects referred to by ldquofieldsrdquo or ldquocolnamesrdquo can be dummy tables and do not have to representany real tables in the database Also note that the ldquofieldsrdquo and ldquocolnamesrdquo must be in the same order asthe fields in the results cursor returned from the DB

export_to_csv_file(ofile args kwargs)

static get_instances()Returns a dictionary with uri as key with timings and defined tables

sqlitestoragesqlite dbstats [(select auth_useremail from auth_user 002009)]dbtables

defined [auth_cas auth_event auth_groupauth_membership auth_permission auth_user]

(continues on next page)

291 Just for backward compatibility 93

web2py Documentation Release 2146-stable

(continued from previous page)

lazy []

has_representer(name)

import_from_csv_file(ifile id_map=None null=rsquoltNULLgtrsquo unique=rsquouuidrsquomap_tablenames=None ignore_missing_tables=False args kwargs)

import_table_definitions(path migrate=False fake_migrate=False tables=None)

lazy_define_table(tablename fields args)

logger = ltloggingLogger objectgt

parse_as_rest(patterns args vars queries=None nested_select=True)

Example

Use as

dbdefine_table(personField(name)Field(info))dbdefine_table(pet

Field(ownedbydbperson)Field(name)Field(info)

)

requestrestful()def index()

def GET(argsvars)patterns = [

friends[person]personnamefieldpersonnamepets[petownedby]personnamepets[petownedby]petnamepersonnamepets[petownedby]petnamefield(dogs[pet] dbpetinfo==dog)(dogs[pet]petnamestartswith dbpetinfo==dog)]

parser = dbparse_as_rest(patternsargsvars)if parserstatus == 200

return dict(content=parserresponse)else

raise HTTP(parserstatusparsererror)

def POST(table_namevars)if table_name == person

return dbpersonvalidate_and_insert(vars)elif table_name == pet

return dbpetvalidate_and_insert(vars)else

raise HTTP(400)return locals()

represent(name args kwargs)

representers = rows_render ltfunction represent at 0x7fcf10dcdb18gt rows_xml ltclass gluonsqlhtmlSQLTABLEgt

94 Chapter 29 sql Module

web2py Documentation Release 2146-stable

rollback()

serializers = json ltfunction custom_json at 0x7fcf11069488gt xml ltfunction xml at 0x7fcf11069578gt

static set_folder(folder)

smart_query(fields text)

tables

uuid()

validators = None

validators_method(field)Field type validation using web2pyrsquos validators mechanism

makes sure the content of a field is in line with the declared fieldtype

where(query=None ignore_common_filters=None)

class gluonsqlField(fieldname type=rsquostringrsquo length=None default=ltfunction ltlambdagtgtrequired=False requires=ltfunction ltlambdagtgt ondelete=rsquoCASCADErsquonotnull=False unique=False uploadfield=True widget=None label=Nonecomment=None writable=True readable=True update=None autho-rize=None autodelete=False represent=None uploadfolder=None upload-separate=False uploadfs=None compute=None custom_store=Nonecustom_retrieve=None custom_retrieve_file_properties=None cus-tom_delete=None filter_in=None filter_out=None custom_qualifier=Nonemap_none=None rname=None)

Bases pydalobjectsExpression pydalhelpersclassesSerializable

LazyRepresents a database field

Example

Usage

a = Field(name string length=32 default=None required=Falserequires=IS_NOT_EMPTY() ondelete=CASCADEnotnull=False unique=Falseuploadfield=True widget=None label=None comment=Noneuploadfield=True True means store on disk

a_field_name means store in this field in db False means file content will be discarded

writable=True readable=True update=None authorize=Noneautodelete=False represent=None uploadfolder=Noneuploadseparate=False upload to separate directories by uuid_keys

first 2 character and tablenamefieldname False - old behavior True - put uploaded file in ltuploaddirgtlttablenamegtltfieldnamegtuuid_key[2] directory)

uploadfs=None a pyfilesystem where to store upload)

to be used as argument of DALdefine_table

alias of FieldMethod

291 Just for backward compatibility 95

web2py Documentation Release 2146-stable

Methodalias of FieldMethod

Virtualalias of FieldVirtual

as_dict(flat=False sanitize=True)

clone(point_self_references_to=False args)

count(distinct=None)

formatter(value)

retrieve(name path=None nameonly=False)If nameonly==True return (filename fullfilename) instead of (filename stream)

retrieve_file_properties(name path=None)

set_attributes(args attributes)

sqlsafe

sqlsafe_name

store(file filename=None path=None)

validate(value)

96 Chapter 29 sql Module

CHAPTER 30

sqlhtml Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

Holds

bull SQLFORM provide a form for a table (withwithout record)

bull SQLTABLE provides a table for a set of records

bull form_factory provides a SQLFORM for an non-db backed table

class gluonsqlhtmlAutocompleteWidget(request field id_field=None db=None or-derby=None limitby=(0 10) distinct=False key-word=rsquo_autocomplete_(tablename)s_(fieldname)srsquomin_length=2 help_fields=Nonehelp_string=None at_beginning=True)

Bases object

callback()

class gluonsqlhtmlBooleanWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates an INPUT checkbox tag

see also FormWidgetwidget

class gluonsqlhtmlCacheRepresenterBases object

class gluonsqlhtmlCheckboxesWidgetBases gluonsqlhtmlOptionsWidget

classmethod widget(field value attributes)Generates a TABLE tag including INPUT checkboxes (multiple allowed)

97

web2py Documentation Release 2146-stable

see also FormWidgetwidget

class gluonsqlhtmlDateWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlDatetimeWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlDecimalWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlDoubleWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlExportClass(rows)Bases object

content_type = None

export()

file_ext = None

label = None

represented()

class gluonsqlhtmlExporterCSV(rows)Bases gluonsqlhtmlExportClass

content_type = textcsv

export()

file_ext = csv

label = CSV

class gluonsqlhtmlExporterCSV_hidden(rows)Bases gluonsqlhtmlExportClass

content_type = textcsv

export()

file_ext = csv

label = CSV

class gluonsqlhtmlExporterHTML(rows)Bases gluonsqlhtmlExportClass

content_type = texthtml

export()

file_ext = html

label = HTML

class gluonsqlhtmlExporterJSON(rows)Bases gluonsqlhtmlExportClass

content_type = applicationjson

export()

file_ext = json

98 Chapter 30 sqlhtml Module

web2py Documentation Release 2146-stable

label = JSON

class gluonsqlhtmlExporterTSV(rows)Bases gluonsqlhtmlExportClass

content_type = texttab-separated-values

export()

file_ext = csv

label = TSV

class gluonsqlhtmlExporterXML(rows)Bases gluonsqlhtmlExportClass

content_type = textxml

export()

file_ext = xml

label = XML

class gluonsqlhtmlFormWidgetBases object

Helper for SQLFORM to generate form input fields (widget) related to the fieldtype

classmethod widget(field value attributes)Generates the widget for the field

When serialized will provide an INPUT tag

bull id = tablename_fieldname

bull class = fieldtype

bull name = fieldname

Parameters

bull field ndash the field needing the widget

bull value ndash value

bull attributes ndash any other attributes to be applied

class gluonsqlhtmlIntegerWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlJSONWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates a TEXTAREA for JSON notation

see also FormWidgetwidget

class gluonsqlhtmlListWidgetBases gluonsqlhtmlStringWidget

classmethod widget(field value attributes)Generates an INPUT text tag

see also FormWidgetwidget

99

web2py Documentation Release 2146-stable

class gluonsqlhtmlMultipleOptionsWidgetBases gluonsqlhtmlOptionsWidget

classmethod widget(field value size=5 attributes)Generates a SELECT tag including OPTIONs (multiple options allowed)

see also FormWidgetwidget

Parameters size ndash optional param (default=5) to indicate how many rows must be shown

class gluonsqlhtmlOptionsWidgetBases gluonsqlhtmlFormWidget

static has_options(field)Checks if the field has selectable options

Parameters field ndash the field needing checking

Returns True if the field has options

classmethod widget(field value attributes)Generates a SELECT tag including OPTIONs (only 1 option allowed)

see also FormWidgetwidget

class gluonsqlhtmlPasswordWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates a INPUT password tag If a value is present it will be shown as a number of lsquorsquo not related tothe length of the actual value

see also FormWidgetwidget

class gluonsqlhtmlRadioWidgetBases gluonsqlhtmlOptionsWidget

classmethod widget(field value attributes)Generates a TABLE tag including INPUT radios (only 1 option allowed)

see also FormWidgetwidget

class gluonsqlhtmlSQLFORM(table record=None deletable=False linkto=None upload=Nonefields=None labels=None col3= submit_button=rsquoSubmitrsquodelete_label=rsquoCheck to deletersquo showid=True readonly=False com-ments=True keepopts=[] ignore_rw=False record_id=Noneformstyle=None buttons=[rsquosubmitrsquo] separator=None ex-tra_fields=None attributes)

Bases gluonhtmlFORM

SQLFORM is used to map a table (and a current record) into an HTML form

Given a Table like dbtable

Generates an insert form

SQLFORM(dbtable)

Generates an update form

record=dbtable[some_id]SQLFORM(dbtable record)

Generates an update with a delete button

100 Chapter 30 sqlhtml Module

web2py Documentation Release 2146-stable

SQLFORM(dbtable record deletable=True)

Parameters

bull table ndash Table object

bull record ndash either an int if the id is an int or the record fetched from the table

bull deletable ndash adds the delete checkbox

bull linkto ndash the URL of a controllerfunction to access referencedby records

bull upload ndash the URL of a controllerfunction to download an uploaded file

bull fields ndash a list of fields that should be placed in the form default is all

bull labels ndash a dictionary with labels for each field keys are the field names

bull col3 ndash a dictionary with content for an optional third column (right of each field) keys arefield names

bull submit_button ndash text to show in the submit button

bull delete_label ndash text to show next to the delete checkbox

bull showid ndash shows the id of the record

bull readonly ndash doesnrsquot allow for any modification

bull comments ndash show comments (stored in col3 or in Field definition)

bull ignore_rw ndash overrides readablewritable attributes

bull record_id ndash used to create session key against CSRF

bull formstyle ndash what to use to generate the form layout

bull buttons ndash override buttons as you please (will be also stored in formcustomsubmit)

bull separator ndash character as separator between labels and inputs

any named optional attribute is passed to the ltformgt tag for example _class _id _style _action _method etc

AUTOTYPES = lttype intgt (integer ltgluonvalidatorsIS_INT_IN_RANGE object at 0x7fcf10deb210gt) lttype floatgt (double ltgluonvalidatorsIS_FLOAT_IN_RANGE object at 0x7fcf10deb250gt) lttype unicodegt (string None) lttype boolgt (boolean None) lttype strgt (string None) lttype listgt (liststring None) lttype datetimedatetimegt (datetime ltgluonvalidatorsIS_DATETIME object at 0x7fcf10deb310gt) lttype datetimedategt (date ltgluonvalidatorsIS_DATE object at 0x7fcf10deb2d0gt)

FIELDKEY_DELETE_RECORD = delete_record

FIELDNAME_REQUEST_DELETE = delete_this_record

ID_LABEL_SUFFIX = __label

ID_ROW_SUFFIX = __row

accepts(request_vars session=None formname=rsquo(tablename)s(record_id)srsquo keepvalues=Noneonvalidation=None dbio=True hideerror=False detect_record_change=False kwargs)

Similar to FORMaccepts but also does insert update or delete in DAL If detect_record_change is Truethan

bull formrecord_changed = False (record is properly validatedsubmitted)

bull formrecord_changed = True (record cannot be submitted because changed)

If detect_record_change == False than

bull formrecord_changed = None

assert_status(status request_vars)

101

web2py Documentation Release 2146-stable

static build_query(fields keywords)

createform(xfields)

static dictform(dictionary kwargs)

static factory(fields attributes)Generates a SQLFORM for the given fields

Internally will build a non-database based data model to hold the fields

formstyles = bootstrap ltfunction formstyle_bootstrap at 0x7fcf10de99b0gt bootstrap3_inline ltfunction _inner at 0x7fcf10de9b90gt bootstrap3_stacked ltfunction formstyle_bootstrap3_stacked at 0x7fcf10de9a28gt divs ltfunction formstyle_divs at 0x7fcf10de9848gt inline ltfunction formstyle_inline at 0x7fcf10de98c0gt table2cols ltfunction formstyle_table2cols at 0x7fcf10de97d0gt table3cols ltfunction formstyle_table3cols at 0x7fcf10dcdde8gt ul ltfunction formstyle_ul at 0x7fcf10de9938gt

static grid(query fields=None field_id=None left=None headers= or-derby=None groupby=None searchable=True sortable=True pagi-nate=20 deletable=True editable=True details=True selectable=None cre-ate=True csv=True links=None links_in_grid=True upload=rsquoltdefaultgtrsquoargs=[] user_signature=True maxtextlengths= maxtextlength=20 on-validation=None onfailure=None oncreate=None onupdate=None on-delete=None sorter_icons=(ltgluonhtmlXML objectgt ltgluonhtmlXMLobjectgt) ui=rsquoweb2pyrsquo showbuttontext=True _class=rsquoweb2py_gridrsquo form-name=rsquoweb2py_gridrsquo search_widget=rsquodefaultrsquo advanced_search=True ig-nore_rw=False formstyle=None exportclasses=None formargs= cre-ateargs= editargs= viewargs= selectable_submit_button=rsquoSubmitrsquobuttons_placement=rsquorightrsquo links_placement=rsquorightrsquo noconfirm=Falsecache_count=None client_side_delete=False ignore_common_filters=Noneauto_pagination=True use_cursor=False)

static search_menu(fields search_options=None prefix=rsquow2prsquo)

static smartdictform(session name filename=None query=None kwargs)

static smartgrid(table constraints=None linked_tables=None links=None links_in_grid=Trueargs=None user_signature=True divider=rsquogtrsquo breadcrumbs_class=rdquokwargs)

Builds a system of SQLFORMgrid(s) between any referenced tables

Parameters

bull table ndash main table

bull constraints (dict) ndash lsquotablersquoquery that limits which records can be accessible

bull links (dict) ndash like lsquotablenamersquo[lambda row A( ) ] that will add buttons whentable tablename is displayed

bull linked_tables (list) ndash list of tables to be linked

Example

given you defined a model as

dbdefine_table(person Field(name) format=(name)s)dbdefine_table(dog

Field(name) Field(owner dbperson) format=(name)s)dbdefine_table(comment Field(body) Field(dog dbdog))if db(dbperson)isempty()

from gluoncontribpopulate import populatepopulate(dbperson 300)populate(dbdog 300)populate(dbcomment 1000)

102 Chapter 30 sqlhtml Module

web2py Documentation Release 2146-stable

in a controller you can do

authrequires_login()def index()

form=SQLFORMsmartgrid(db[requestargs(0) or person])return dict(form=form)

widgets = autocomplete ltclass gluonsqlhtmlAutocompleteWidgetgt blob None boolean ltclass gluonsqlhtmlBooleanWidgetgt checkboxes ltclass gluonsqlhtmlCheckboxesWidgetgt date ltclass gluonsqlhtmlDateWidgetgt datetime ltclass gluonsqlhtmlDatetimeWidgetgt decimal ltclass gluonsqlhtmlDecimalWidgetgt double ltclass gluonsqlhtmlDoubleWidgetgt integer ltclass gluonsqlhtmlIntegerWidgetgt json ltclass gluonsqlhtmlJSONWidgetgt list ltclass gluonsqlhtmlListWidgetgt multiple ltclass gluonsqlhtmlMultipleOptionsWidgetgt options ltclass gluonsqlhtmlOptionsWidgetgt password ltclass gluonsqlhtmlPasswordWidgetgt radio ltclass gluonsqlhtmlRadioWidgetgt string ltclass gluonsqlhtmlStringWidgetgt text ltclass gluonsqlhtmlTextWidgetgt time ltclass gluonsqlhtmlTimeWidgetgt upload ltclass gluonsqlhtmlUploadWidgetgt

class gluonsqlhtmlSQLTABLE(sqlrows linkto=None upload=None orderby=None headers=truncate=16 columns=None th_link=rdquo extracolumns=None se-lectid=None renderstyle=False cid=None colgroup=False at-tributes)

Bases gluonhtmlTABLE

Given with a Rows object as returned by a db()select() generates an html table with the rows

Parameters

bull sqlrows ndash the Rows object

bull linkto ndash URL (or lambda to generate a URL) to edit individual records

bull upload ndash URL to download uploaded files

bull orderby ndash Add an orderby link to column headers

bull headers ndash dictionary of headers to headers redefinions headers can also be a string to gen-erate the headers from data for now only headers=rdquofieldnamecapitalizerdquo headers=rdquolabelsrdquoand headers=None are supported

bull truncate ndash length at which to truncate text in table cells Defaults to 16 characters

bull columns ndash a list or dict contaning the names of the columns to be shown Defaults to all

bull th_link ndash base link to support orderby headers

bull extracolumns ndash a list of dicts

bull selectid ndash The id you want to select

bull renderstyle ndash Boolean render the style with the table

bull cid ndash use this cid for all links

bull colgroup ndash FIXME

Extracolumns example

[labelA(Extra _href=)class class name of the headerwidth width in pixels or contentlambda row rc A(Edit _href=editsrowid)selected False agregate class selected to this column]

style()

class gluonsqlhtmlStringWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates an INPUT text tag

see also FormWidgetwidget

103

web2py Documentation Release 2146-stable

class gluonsqlhtmlTextWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates a TEXTAREA tag

see also FormWidgetwidget

class gluonsqlhtmlTimeWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlUploadWidgetBases gluonsqlhtmlFormWidget

DEFAULT_WIDTH = 150px

DELETE_FILE = delete

GENERIC_DESCRIPTION = file download

ID_DELETE_SUFFIX = __delete

static is_image(value)Tries to check if the filename provided references to an image

Checking is based on filename extension Currently recognized gif png jp(e)g bmp

Parameters value ndash filename

classmethod represent(field value download_url=None)How to represent the file

bull with download url and if it is an image ltA href= gtltIMG gtltAgt

bull otherwise with download url ltA href= gtfileltAgt

bull otherwise file

Parameters

bull field ndash the field

bull value ndash the field value

bull download_url ndash url for the file download (default = None)

classmethod widget(field value download_url=None attributes)generates a INPUT file tag

Optionally provides an A link to the file including a checkbox so the file can be deleted

All is wrapped in a DIV

see also FormWidgetwidget

Parameters

bull field ndash the field

bull value ndash the field value

bull download_url ndash url for the file download (default = None)

gluonsqlhtmladd_class(a b)

104 Chapter 30 sqlhtml Module

web2py Documentation Release 2146-stable

gluonsqlhtmlform_factory(fields attributes)Generates a SQLFORM for the given fields

Internally will build a non-database based data model to hold the fields

gluonsqlhtmlformstyle_bootstrap(form fields)bootstrap 23x format form layout

gluonsqlhtmlformstyle_bootstrap3_inline_factory(col_label_size=3)bootstrap 3 horizontal form layout

Note Experimental

gluonsqlhtmlformstyle_bootstrap3_stacked(form fields)bootstrap 3 format form layout

Note Experimental

gluonsqlhtmlformstyle_divs(form fields)divs only

gluonsqlhtmlformstyle_inline(form fields)divs only but inline

gluonsqlhtmlformstyle_table2cols(form fields)2 column table

gluonsqlhtmlformstyle_table3cols(form fields)3 column table - default

gluonsqlhtmlformstyle_ul(form fields)unordered list

gluonsqlhtmlrepresent(field value record)

gluonsqlhtmlsafe_float(x)

gluonsqlhtmlsafe_int(x)

gluonsqlhtmlshow_if(cond)

105

web2py Documentation Release 2146-stable

106 Chapter 30 sqlhtml Module

CHAPTER 31

storage Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

Provides

bull List like list but returns None instead of IndexOutOfBounds

bull Storage like dictionary allowing also for objfoo for obj[lsquofoorsquo]

class gluonstorageListBases list

Like a regular python list but callable When a(i) is called if i is out of bounds returns None instead of IndexError

class gluonstorageStorageBases dict

A Storage object is like a dictionary except objfoo can be used in addition to obj[lsquofoorsquo] and setting objfoo =None deletes item foo

Example

gtgtgt o = Storage(a=1)gtgtgt print oa1

gtgtgt o[a]1

gtgtgt oa = 2gtgtgt print o[a]2

gtgtgt del oa

(continues on next page)

107

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt print oaNone

getfirst(key default=None)Returns the first value of a list or the value itself when given a requestvars style key

If the value is a list its first item will be returned otherwise the value will be returned as-is

Example output for a query string of x=abcampy=abcampy=def

gtgtgt request = Storage()gtgtgt requestvars = Storage()gtgtgt requestvarsx = abcgtgtgt requestvarsy = [abc def]gtgtgt requestvarsgetfirst(x)abcgtgtgt requestvarsgetfirst(y)abcgtgtgt requestvarsgetfirst(z)

getlast(key default=None)Returns the last value of a list or value itself when given a requestvars style key

If the value is a list the last item will be returned otherwise the value will be returned as-is

Simulated output with a query string of x=abcampy=abcampy=def

gtgtgt request = Storage()gtgtgt requestvars = Storage()gtgtgt requestvarsx = abcgtgtgt requestvarsy = [abc def]gtgtgt requestvarsgetlast(x)abcgtgtgt requestvarsgetlast(y)defgtgtgt requestvarsgetlast(z)

getlist(key)Returns a Storage value as a list

If the value is a list it will be returned as-is If object is None an empty list will be returned Otherwise[value] will be returned

Example output for a query string of x=abcampy=abcampy=def

gtgtgt request = Storage()gtgtgt requestvars = Storage()gtgtgt requestvarsx = abcgtgtgt requestvarsy = [abc def]gtgtgt requestvarsgetlist(x)[abc]gtgtgt requestvarsgetlist(y)[abc def]gtgtgt requestvarsgetlist(z)[]

class gluonstorageSettingsBases gluonstorageStorage

108 Chapter 31 storage Module

web2py Documentation Release 2146-stable

class gluonstorageMessages(T)Bases gluonstorageSettings

class gluonstorageStorageListBases gluonstorageStorage

Behaves like Storage but missing elements defaults to [] instead of None

gluonstorageload_storage(filename)

gluonstoragesave_storage(storage filename)

109

web2py Documentation Release 2146-stable

110 Chapter 31 storage Module

CHAPTER 32

streamer Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

321 Facilities to handle file streaming

gluonstreamerstream_file_or_304_or_206(static_file chunk_size=65536 request=Noneheaders= status=200 error_message=None)

gluonstreamerstreamer(stream chunk_size=65536 bytes=None)

111

web2py Documentation Release 2146-stable

112 Chapter 32 streamer Module

CHAPTER 33

template Module

This file is part of the web2py Web FrameworkLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)Author Thadeus BurgessContributors- Massimo Di Pierro for creating the original gluontemplatepy- Jonathan Lundell for extensively testing the regex on Jython- Limodou (creater of uliweb) who inspired the block-element support for web2py

331 Templating syntax

class gluontemplateBlockNode(name=rdquo pre_extend=False delimiters=(rsquorsquo rsquorsquo))Bases gluontemplateNode

Block Container

This Node can contain other Nodes and will render in a hierarchical order of when nodes were added

ie

block test This is default block test

end

append(node)Adds an element to the nodes

Parameters node ndash Node object or string to append

extend(other)Extends the list of nodes with another BlockNode class

Parameters other ndash BlockNode or Content object to extend from

113

web2py Documentation Release 2146-stable

output(blocks)Merges all nodes into a single string

Parameters blocks ndash Dictionary of blocks that are extending from this template

class gluontemplateContent(name=rsquoContentBlockrsquo pre_extend=False)Bases gluontemplateBlockNode

Parent Container ndash Used as the root level BlockNode

Contains functions that operate as such

Parameters name ndash Unique name for this BlockNode

append(node)Adds a node to list If it is a BlockNode then we assign a block for it

clear_content()

extend(other)Extends the objects list of nodes with another objects nodes

insert(other index=0)Inserts object at index

You may pass a list of objects and have them inserted

class gluontemplateDummyResponse

write(data escape=True)

class gluontemplateNOESCAPE(text)A little helper to avoid escaping

xml()

class gluontemplateNode(value=None pre_extend=False)Bases object

Basic Container Object

class gluontemplateSuperNode(name=rdquo pre_extend=False)Bases gluontemplateNode

class gluontemplateTemplateParser(text name=rsquoParserContainerrsquo context=path=rsquoviewsrsquo writer=rsquoresponsewritersquo lexers=delimiters=(rsquorsquo rsquorsquo) _super_nodes=[])

Bases object

Parse all blocks

Parameters

bull text ndash text to parse

bull context ndash context to parse in

bull path ndash folder path to templates

bull writer ndash string of writer class to use

bull lexers ndash dict of custom lexers to use

bull delimiters ndash for example (lsquolsquorsquorsquo)

114 Chapter 33 template Module

web2py Documentation Release 2146-stable

bull _super_nodes ndash a list of nodes to check for inclusion this should only be set byldquoselfextendrdquo It contains a list of SuperNodes from a child template that need to be han-dled

default_delimiters = ( )

extend(filename)Extends filename Anything not declared in a block defined by the parent will be placed in the parenttemplates include block

include(content filename)Includes filename here

parse(text)

r_multiline = lt_sreSRE_Pattern objectgt

r_tag = lt_sreSRE_Pattern objectgt

re_block = lt_sreSRE_Pattern objectgt

re_pass = lt_sreSRE_Pattern objectgt

re_unblock = lt_sreSRE_Pattern objectgt

reindent(text)Reindents a string of unindented python code

to_string()Returns the parsed template with correct indentation

Used to make it easier to port to python3

gluontemplateget_parsed(text)Returns the indented python code of text Useful for unit testing

gluontemplateoutput_aux(node blocks)

gluontemplateparse_template(filename path=rsquoviewsrsquo context= lexers= delimiters=(rsquorsquorsquorsquo))

Parameters

bull filename ndash can be a view filename in the views folder or an input stream

bull path ndash is the path of a views folder

bull context ndash is a dictionary of symbols used to render the template

bull lexers ndash dict of custom lexers to use

bull delimiters ndash opening and closing tags

gluontemplaterender(content=rsquohello worldrsquo stream=None filename=None path=None con-text= lexers= delimiters=(rsquorsquo rsquorsquo) writer=rsquoresponsewritersquo)

Generic render function

Parameters

bull content ndash default content

bull stream ndash file-like obj to read template from

bull filename ndash where to find template

bull path ndash base path for templates

bull context ndash env

331 Templating syntax 115

web2py Documentation Release 2146-stable

bull lexers ndash custom lexers to use

bull delimiters ndash opening and closing tags

bull writer ndash where to inject the resulting stream

Example

gtgtgt render()hello worldgtgtgt render(content=abc)abcgtgtgt render(content=abc)abcgtgtgt render(content=abc)abcgtgtgt render(content=anbc)anbcgtgtgt render(content=abcde)abcdegtgtgt render(content=anc)ancgtgtgt render(content=ac)acgtgtgt render(content=for i in range(a)=iltbr gtpassrarr˓context=dict(a=5))0ltbr gt1ltbr gt2ltbr gt3ltbr gt4ltbr gtgtgtgt render(content=for i in range(a)=iltbr gtpassrarr˓context=dict(a=5)delimiters=())0ltbr gt1ltbr gt2ltbr gt3ltbr gt4ltbr gtgtgtgt render(content==hellonworld)hellonworldgtgtgt render(content=for i in range(3)n=inpass)012

116 Chapter 33 template Module

CHAPTER 34

tools Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

341 Auth Mail PluginManager and various utilities

class gluontoolsMail(server=None sender=None login=None tls=True)Bases object

Class for configuring and sending emails with alternative text html body multiple attachments and encryptionsupport

Works with SMTP and Google App Engine

Parameters

bull server ndash SMTP server address in addressport notation

bull sender ndash sender email address

bull login ndash sender login name and password in loginpassword notation or None if no authen-tication is required

bull tls ndash enablesdisables encryption (True by default)

In Google App Engine use

server=gae

For sake of backward compatibility all fields are optional and default to None however to be able to send emailsat least server and sender must be specified They are available under following fields

117

web2py Documentation Release 2146-stable

mailsettingsservermailsettingssendermailsettingsloginmailsettingstimeout = 60 seconds (default)

When server is lsquologgingrsquo email is logged but not sent (debug mode)

Optionally you can use PGP encryption or X509

mailsettingscipher_type = Nonemailsettingsgpg_home = Nonemailsettingssign = Truemailsettingssign_passphrase = Nonemailsettingsencrypt = Truemailsettingsx509_sign_keyfile = Nonemailsettingsx509_sign_certfile = Nonemailsettingsx509_sign_chainfile = Nonemailsettingsx509_nocerts = Falsemailsettingsx509_crypt_certfiles = None

cipher_type Nonegpg - need a python-pyme package and gpgme libx509 - smime

gpg_home you can set a GNUPGHOME environment variableto specify home of gnupg

sign sign the message (True or False)sign_passphrase passphrase for key signingencrypt encrypt the message (True or False) It defaults

to True x509 only

x509_sign_keyfile the signers private key filename orstring containing the key (PEM format)

x509_sign_certfile the signers certificate filename orstring containing the cert (PEM format)

x509_sign_chainfile sets the optional all-in-one file where youcan assemble the certificates of CertificationAuthorities (CA) which form the certificatechain of email certificate It can be astring containing the certs to (PEM format)

x509_nocerts if True then no attached certificate in mailx509_crypt_certfiles the certificates file or strings to encrypt

the messages with can be a file name string or a list of file names strings (PEM format)

Examples

Create Mail object with authentication data for remote server

mail = Mail(examplecom25 meexamplecom mepassword)

Notice for GAE users attachments have an automatic content_id=rsquoattachment-irsquo where i is progressive num-ber in this way the can be referenced from the HTML as ltimg src=rdquocidattachment-0rdquo gt etc

118 Chapter 34 tools Module

web2py Documentation Release 2146-stable

class Attachment(payload filename=None content_id=None content_type=Noneencoding=rsquoutf-8rsquo)

Bases emailmimebaseMIMEBase

Email attachment

Parameters

bull payload ndash path to file or file-like object with read() method

bull filename ndash name of the attachment stored in message if set to None it will be fetchedfrom payload path file-like object payload must have explicit filename specified

bull content_id ndash id of the attachment automatically contained within lt and gt

bull content_type ndash content type of the attachment if set to None it will be fetched fromfilename using gluoncontenttype module

bull encoding ndash encoding of all strings passed to this function (except attachment body)

Content ID is used to identify attachments within the html body in example attached image with contentID lsquophotorsquo may be used in html message as a source of img tag ltimg src=rdquocidphotordquo gt

Example Create attachment from text file

attachment = MailAttachment(pathtofiletxt)

Content-Type textplainMIME-Version 10Content-Disposition attachment filename=filetxtContent-Transfer-Encoding base64

SOMEBASE64CONTENT=

Create attachment from image file with custom filename and cid

attachment = MailAttachment(pathtofilepngfilename=photopngcontent_id=photo)

Content-Type imagepngMIME-Version 10Content-Disposition attachment filename=photopngContent-Id ltphotogtContent-Transfer-Encoding base64

SOMEOTHERBASE64CONTENT=

send(to subject=rsquo[no subject]rsquo message=rsquo[no message]rsquo attachments=None cc=None bcc=Nonereply_to=None sender=None encoding=rsquoutf-8rsquo raw=False headers= from_address=Nonecipher_type=None sign=None sign_passphrase=None encrypt=None x509_sign_keyfile=Nonex509_sign_chainfile=None x509_sign_certfile=None x509_crypt_certfiles=Nonex509_nocerts=None)

Sends an email using data specified in constructor

Parameters

bull to ndash list or tuple of receiver addresses will also accept single object

bull subject ndash subject of the email

bull message ndash email body text depends on type of passed object

341 Auth Mail PluginManager and various utilities 119

web2py Documentation Release 2146-stable

ndash if 2-list or 2-tuple is passed first element will be source of plain text while second ofhtml text

ndash otherwise object will be the only source of plain text and html source will be set toNone

If text or html source is

ndash None content part will be ignored

ndash string content part will be set to it

ndash file-like object content part will be fetched from it using itrsquos read() method

bull attachments ndash list or tuple of MailAttachment objects will also accept single object

bull cc ndash list or tuple of carbon copy receiver addresses will also accept single object

bull bcc ndash list or tuple of blind carbon copy receiver addresses will also accept single object

bull reply_to ndash address to which reply should be composed

bull encoding ndash encoding of all strings passed to this method (including message bodies)

bull headers ndash dictionary of headers to refine the headers just before sending mail eg lsquoX-Mailerrsquo lsquoweb2py mailerrsquo

bull from_address ndash address to appear in the lsquoFromrsquo header this is not the envelopesender If not specified the sender will be used

bull cipher_type ndash gpg - need a python-pyme package and gpgme lib x509 - smime

bull gpg_home ndash you can set a GNUPGHOME environment variable to specify home ofgnupg

bull sign ndash sign the message (True or False)

bull sign_passphrase ndash passphrase for key signing

bull encrypt ndash encrypt the message (True or False) It defaults to True x509 only

bull x509_sign_keyfile ndash the signers private key filename or string containing the key(PEM format)

bull x509_sign_certfile ndash the signers certificate filename or string containing the cert(PEM format)

bull x509_sign_chainfile ndash sets the optional all-in-one file where you can assemblethe certificates of Certification Authorities (CA) which form the certificate chain of emailcertificate It can be a string containing the certs to (PEM format)

bull x509_nocerts ndash if True then no attached certificate in mail

bull x509_crypt_certfiles ndash the certificates file or strings to encrypt the messages withcan be a file name string or a list of file names strings (PEM format)

Examples

Send plain text message to single address

mailsend(youexamplecomMessage subjectPlain text body of the message)

120 Chapter 34 tools Module

web2py Documentation Release 2146-stable

Send html message to single address

mailsend(youexamplecomMessage subjectlthtmlgtPlain text body of the messagelthtmlgt)

Send text and html message to three addresses (two in cc)

mailsend(youexamplecomMessage subject(Plain text body lthtmlgthtml bodylthtmlgt)cc=[other1examplecom other2examplecom])

Send html only message with image attachment available from the message by lsquophotorsquo content id

mailsend(youexamplecomMessage subject(None lthtmlgtltimg src=cidphoto gtlthtmlgt)MailAttachment(pathtophotojpg

content_id=photo))

Send email with two attachments and no body text

mailsend(youexamplecomMessage subjectNone[MailAttachment(pathtofistfile)MailAttachment(pathtosecondfile)])

Returns True on success False on failure

Before return method updates two objectrsquos fields

bull selfresult return value of smtplibSMTPsendmail() or GAErsquos mailsend_mail() method

bull selferror Exception message or None if above was successful

class gluontoolsAuth(environment=None db=None mailer=True hmac_key=None con-troller=rsquodefaultrsquo function=rsquouserrsquo cas_provider=None signature=Truesecure=False csrf_prevention=True propagate_extension=Noneurl_index=None jwt=None host_names=None)

Bases object

accessible_query(name table user_id=None)Returns a query with all accessible records for user_id or the current logged in user this method does notwork on GAE because uses JOIN and IN

Example

Use as

db(authaccessible_query(read dbmytable))select(dbmytableALL)

add_group(role description=rdquo)Creates a group associated to a role

add_membership(group_id=None user_id=None role=None)Gives user_id membership of group_id or role if user is None than user_id is that of current logged in user

341 Auth Mail PluginManager and various utilities 121

web2py Documentation Release 2146-stable

add_permission(group_id name=rsquoanyrsquo table_name=rdquo record_id=0)Gives group_id lsquonamersquo access to lsquotable_namersquo and lsquorecord_idrsquo

allows_jwt(otherwise=None)

static archive(form archive_table=None current_record=rsquocurrent_recordrsquoarchive_current=False fields=None)

If you have a table (dbmytable) that needs full revision history you can just do

form = crudupdate(dbmytable myrecord onaccept=autharchive)

or

form = SQLFORM(dbmytable myrecord)process(onaccept=autharchive)

crudarchive will define a new table ldquomytable_archiverdquo and store a copy of the current record (ifarchive_current=True) or a copy of the previous record (if archive_current=False) in the newly createdtable including a reference to the current record

fields allows to specify extra fields that need to be archived

If you want to access such table you need to define it yourself in a model

dbdefine_table(mytable_archiveField(current_record dbmytable)dbmytable)

Notice such table includes all fields of dbmytable plus one current_record crudarchive does not times-tamp the stored record unless your original table has a fields like

dbdefine_table(Field(saved_on datetime

default=requestnow update=requestnow writable=False)Field(saved_by authuser

default=authuser_id update=authuser_id writable=False)

there is nothing special about these fields since they are filled before the record is archived

If you want to change the archive table name and the name of the reference field you can do for example

dbdefine_table(myhistoryField(parent_record dbmytable) dbmytable)

and use it as

form = crudupdate(dbmytable myrecordonaccept=lambda formcrudarchive(form

archive_table=dbrarr˓myhistory

current_record=parent_rarr˓record))

basic(basic_auth_realm=False)Performs basic login

Parameters basic_auth_realm ndash optional basic http authentication realm Can take str orunicode or function or callable or boolean

reads currentrequestenvhttp_authorization and returns basic_allowedbasic_accepteduser

122 Chapter 34 tools Module

web2py Documentation Release 2146-stable

if basic_auth_realm is defined is a callable itrsquos return value is used to set the basic authentication realm ifitrsquos a string its content is used instead Otherwise basic authentication realm is set to the application nameIf basic_auth_realm is None or False (the default) the behavior is to skip sending any challenge

bulk_register(max_emails=100)Creates a form for ther user to send invites to other users to join

cas_login(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt version=2)

cas_validate(version=2 proxy=False)

change_password(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form that lets the user change password

confirm_registration(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form to confirm user registration

default_messages = access_denied Insufficient privileges add_group_log Group (group_id)s created add_membership_log None add_permission_log None bulk_invite_body You have been invited to join (site)s click (link)s to complete the process bulk_invite_subject Invitation to join (site)s change_password_log User (id)s Password changed del_group_log Group (group_id)s deleted del_membership_log None del_permission_log None delete_label Check to delete email_sent Email sent email_taken This email already has an account email_verified Email verified function_disabled Function disabled group_description Group uniquely assigned to user (id)s has_membership_log None has_permission_log None impersonate_log User (id)s is impersonating (other_id)s invalid_email Invalid email invalid_login Invalid login invalid_password Invalid password invalid_reset_password Invalid reset password invalid_two_factor_code Incorrect code 0 more attempt(s) remaining invalid_user Invalid user invalid_username Invalid username is_empty Cannot be empty label_client_ip Client IP label_description Description label_email E-mail label_first_name First name label_group_id Group ID label_last_name Last name label_name Name label_origin Origin label_password Password label_record_id Record ID label_registration_id Registration identifier label_registration_key Registration key label_remember_me Remember me (for 30 days) label_reset_password_key Reset Password key label_role Role label_table_name Object or table name label_time_stamp Timestamp label_two_factor Authentication code label_user_id User ID label_username Username logged_in Logged in logged_out Logged out login_button Log In login_disabled Login disabled by administrator login_failed_log None login_log User (id)s Logged-in logout_log User (id)s Logged-out mismatched_password Password fields dont match new_password New password new_password_sent A new password was emailed to you old_password Old password password_change_button Change password password_changed Password changed password_reset_button Request reset password profile_log User (id)s Profile updated profile_save_button Apply changes profile_updated Profile updated register_button Sign Up register_log User (id)s Registered registration_pending Registration is pending approval registration_successful Registration successful registration_verifying Registration needs verification reset_password Click on the link (link)s to reset your password reset_password_log User (id)s Password reset reset_password_subject Password reset retrieve_password Your password is (password)s retrieve_password_log User (id)s Password retrieved retrieve_password_subject Password retrieve retrieve_two_factor_code Your temporary login code is 0 retrieve_two_factor_code_subject Two-step Login Authentication Code retrieve_username Your username is (username)s retrieve_username_log User (id)s Username retrieved retrieve_username_subject Username retrieve submit_button Submit two_factor_comment This code was emailed to you and is required for login unable_send_email Unable to send email unable_to_send_email Unable to send email username_sent Your username was emailed to you username_taken Username already taken verify_email Welcome (username)s Click on the link (link)s to verify your email verify_email_log User (id)s Verification email sent verify_email_subject Email verification verify_password Verify Password verify_password_comment please input your password againClass for authentication authorization role based access control

Includes

bull registration and profile

bull login and logout

bull username and password retrieval

bull event logging

bull role creation and assignment

bull user defined grouprole based permission

Parameters

bull environment ndash is there for legacy but unused (awful)

bull db ndash has to be the database where to create tables for authentication

bull mailer ndash Mail( ) or None (no mailer) or True (make a mailer)

bull hmac_key ndash can be a hmac_key or hmac_key=Authget_or_create_key()

bull controller ndash (where is the user action)

bull cas_provider ndash (delegate authentication to the URL CAS2)

Authentication Example

from gluoncontributils import mail=Mail()mailsettingsserver=smtpgmailcom587mailsettingssender=yousomewherecommailsettingslogin=usernamepasswordauth=Auth(db)authsettingsmailer=mail authsettings=authdefine_tables()def authentication()

return dict(form=auth())

341 Auth Mail PluginManager and various utilities 123

web2py Documentation Release 2146-stable

Exposes

bull http applicationcontrollerauthenticationlogin

bull http applicationcontrollerauthenticationlogout

bull http applicationcontrollerauthenticationregister

bull http applicationcontrollerauthenticationverify_email

bull http applicationcontrollerauthenticationretrieve_username

bull http applicationcontrollerauthenticationretrieve_password

bull http applicationcontrollerauthenticationreset_password

bull http applicationcontrollerauthenticationprofile

bull http applicationcontrollerauthenticationchange_password

On registration a group with role=new_userid is created and user is given membership of this group

You can create a group with

group_id=authadd_group(Manager can access the manage action)authadd_permission(group_id access to manage)

Here ldquoaccess to managerdquo is just a user defined string You can give access to a user

authadd_membership(group_id user_id)

If user id is omitted the logged in user is assumed

Then you can decorate any action

authrequires_permission(access to manage)def manage()

return dict()

You can restrict a permission to a specific table

authadd_permission(group_id edit dbsometable)authrequires_permission(edit dbsometable)

Or to a specific record

authadd_permission(group_id edit dbsometable 45)authrequires_permission(edit dbsometable 45)

If authorization is not granted calls

authsettingson_failed_authorization

Other options

authsettingsmailer=Noneauthsettingsexpiration=3600 seconds

these are messages that can be customized

124 Chapter 34 tools Module

web2py Documentation Release 2146-stable

default_settings = allow_basic_login False allow_basic_login_only False allow_delete_accounts False alternate_requires_registration False auth_manager_role None auth_two_factor_enabled False auth_two_factor_tries_left 3 bulk_register_enabled False captcha None cas_maps None client_side True create_user_groups user_(id)s email_case_sensitive True everybody_group_id None expiration 3600 formstyle None hideerror False keep_session_onlogin True keep_session_onlogout False label_separator None logging_enabled True login_after_password_change True login_after_registration False login_captcha None login_email_validate True login_userfield None logout_onlogout None long_expiration 2592000 manager_actions multi_login False on_failed_authentication ltfunction ltlambdagt at 0x7fcf0cf9f578gt ondelete CASCADE password_field password password_min_length 4 pre_registration_div None prevent_open_redirect_attacks True prevent_password_reset_attacks True profile_fields None register_captcha None register_fields None register_verify_password True registration_requires_approval False registration_requires_verification False remember_me_form True renew_session_onlogin True renew_session_onlogout True reset_password_requires_verification False retrieve_password_captcha None retrieve_username_captcha None showid False table_cas None table_cas_name auth_cas table_event None table_event_name auth_event table_group None table_group_name auth_group table_membership None table_membership_name auth_membership table_permission None table_permission_name auth_permission table_token_name auth_token table_user None table_user_name auth_user two_factor_authentication_group None update_fields [email] use_username False username_case_sensitive True wiki ltStorage gt

define_signature()

define_tables(username=None signature=None enable_tokens=False migrate=Nonefake_migrate=None)

To be called unless tables are defined manually

Examples

Use as

defines all needed tables and table files myprefix_auth_usertable authdefine_tables(migrate=myprefix_)

defines all needed tables without migrationtable filesauthdefine_tables(migrate=False)

del_group(group_id)Deletes a group

del_membership(group_id=None user_id=None role=None)Revokes membership from group_id to user_id if user_id is None than user_id is that of current logged inuser

del_permission(group_id name=rsquoanyrsquo table_name=rdquo record_id=0)Revokes group_id lsquonamersquo access to lsquotable_namersquo and lsquorecord_idrsquo

email_registration(subject body user)Sends and email invitation to a user informing they have been registered with the application

email_reset_password(user)

enable_record_versioning(tables archive_db=None archive_names=rsquo(tablename)s_archiversquocurrent_record=rsquocurrent_recordrsquo current_record_label=None)

Used to enable full record versioning (including auth tables)

auth = Auth(db)authdefine_tables(signature=True) define our own tablesdbdefine_table(mythingField(name)authsignature)authenable_record_versioning(tables=db)

tables can be the db (all table) or a list of tables only tables with modified_by and modified_on fiels (ascreated by authsignature) will have versioning Old record versions will be in table lsquomything_archiversquoautomatically defined

when you enable enable_record_versioning records are never deleted but marked with is_active=False

enable_record_versioning enables a common_filter for every table that filters out records with is_active =False

Note If you use authenable_record_versioning do not use autharchive or you will end up with dupli-cates autharchive does explicitly what enable_record_versioning does automatically

static get_or_create_key(filename=None alg=rsquosha512rsquo)

341 Auth Mail PluginManager and various utilities 125

web2py Documentation Release 2146-stable

get_or_create_user(keys update_fields=[rsquoemailrsquo] login=True get=True)Used for alternate login methods If the user exists already then password is updated If the user doesnrsquotyet exist then they are created

get_vars_next()

groups()Displays the groups and their roles for the logged in user

has_membership(group_id=None user_id=None role=None)Checks if user is member of group_id or role

has_permission(name=rsquoanyrsquo table_name=rdquo record_id=0 user_id=None group_id=None)Checks if user_id or current logged in user is member of a group that has lsquonamersquo permission on lsquota-ble_namersquo and lsquorecord_idrsquo if group_id is passed it checks whether the group has the permission

here()

id_group(role)Returns the group_id of the group specified by the role

impersonate(user_id=ltfunction ltlambdagtgt)To use this make a POST to http impersonate requestpost_varsuser_id=ltidgt

Set requestpost_varsuser_id to 0 to restore original user

requires impersonator is logged in and

has_permission(impersonate auth_user user_id)

is_impersonating()

is_logged_in()Checks if the user is logged in and returns TrueFalse If so user is in authuser as well as in ses-sionauthuser

jwt()To use JWT authentication 1) instantiate auth with

auth = Auth(db jwt = secret_keysecret)

where lsquosecretrsquo is your own secret string

2 Decorate functions that require login but should accept the JWT token credentials

authallows_jwt()authrequires_login()def myapi() return hello s authuseremail

Notice jwt is allowed but not required if user is logged in myapi is accessible

3 Use it

Now API users can obtain a token with

http appdefaultuserjwtusername= amppassword=

(returns json object with a token attribute) API users can refresh an existing token with

http appdefaultuserjwttoken=

they can authenticate themselves when calling http myapi by injecting a header

Authorization Bearer ltthe jwt tokengt

126 Chapter 34 tools Module

web2py Documentation Release 2146-stable

Any additional attributes in the jwt argument of Auth() below

auth = Auth(db jwt = )

are passed to the constructor of class AuthJWT Look there for documentation

log_event(description vars=None origin=rsquoauthrsquo)

Examples

Use as

authlog_event(description=this happened origin=auth)

login(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a login form

login_bare(username password)Logins user as specified by username (or email) and password

login_user(user)Logins the user = dbauth_user(id)

logout(next=ltfunction ltlambdagtgt onlogout=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)Logouts and redirects to login

logout_bare()

manage_tokens()

navbar(prefix=rsquoWelcomersquo action=None separators=(rsquo [ rsquo rsquo | rsquo rsquo ] rsquo) user_identifier=ltfunctionltlambdagtgt referrer_actions=ltfunction ltlambdagtgt mode=rsquodefaultrsquo)

Navbar with support for more templates This uses some code from the old navbar

Parameters mode ndash see options for list of

not_authorized()You can change the view for this page to make it look as you like

profile(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form that lets the user change hisher profile

random_password()

register(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a registration form

register_bare(fields)Registers a user as specified by username (or email) and a raw password

request_reset_password(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgtonaccept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form to reset the user password

requires(condition requires_login=True otherwise=None)Decorator that prevents access to action if not logged in

requires_login(otherwise=None)Decorator that prevents access to action if not logged in

341 Auth Mail PluginManager and various utilities 127

web2py Documentation Release 2146-stable

requires_login_or_token(otherwise=None)

requires_membership(role=None group_id=None otherwise=None)Decorator that prevents access to action if not logged in or if user logged in is not a member of group_idIf role is provided instead of group_id then the group_id is calculated

requires_permission(name table_name=rdquo record_id=0 otherwise=None)Decorator that prevents access to action if not logged in or if user logged in is not a member of any group(role) that has lsquonamersquo access to lsquotable_namersquo lsquorecord_idrsquo

requires_signature(otherwise=None hash_vars=True)Decorator that prevents access to action if not logged in or if user logged in is not a member of group_idIf role is provided instead of group_id then the group_id is calculated

reset_password(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form to reset the user password

reset_password_deprecated(next=ltfunction ltlambdagtgt onvalidation=ltfunctionltlambdagtgt onaccept=ltfunction ltlambdagtgt log=ltfunctionltlambdagtgt)

Returns a form to reset the user password (deprecated)

retrieve_password(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

retrieve_username(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form to retrieve the user username (only if there is a username field)

run_login_onaccept()

select_host(host host_names=None)checks that host is valid ie in the list of glob host_names if the host is missing then is it selects the firstentry from host_names read more here httpsgithubcomweb2pyweb2pyissues1196

table_cas()

table_event()

table_group()

table_membership()

table_permission()

table_token()

table_user()

update_groups()

url(f=None args=None vars=None scheme=False)

user_group(user_id=None)Returns the group_id of the group uniquely associated to this user ie role=user[user_id]

user_group_role(user_id=None)

user_iduserid or None

verify_email(next=ltfunction ltlambdagtgt onaccept=ltfunction ltlambdagtgt log=ltfunctionltlambdagtgt)

Action used to verify the registration email

128 Chapter 34 tools Module

web2py Documentation Release 2146-stable

when_is_logged_in_bypass_next_in_url(next session)This function should be use when someone want to avoid asking for user credentials when loaded pagecontains ldquouserlogin_next=NEXT_COMPONENTrdquo in the URL is refresh but user is already authenti-cated

wiki(slug=None env=None render=rsquomarkminrsquo manage_permissions=False force_prefix=rdquo re-strict_search=False resolve=True extra=None menu_groups=None templates=None mi-grate=True controller=None function=None force_render=False groups=None)

wikimenu()To be used in menupy for app wide wiki menus

class gluontoolsRecaptcha(request=None public_key=rdquo private_key=rdquo use_ssl=False er-ror=None error_message=rsquoinvalidrsquo label=rsquoVerifyrsquo options=rdquocomment=rdquo ajax=False)

Bases gluonhtmlDIV

Examples

Use as

form = FORM(Recaptcha(public_key= private_key=))

or

form = SQLFORM()formappend(Recaptcha(public_key= private_key=))

API_SERVER = httpwwwgooglecomrecaptchaapi

API_SSL_SERVER = httpswwwgooglecomrecaptchaapi

VERIFY_SERVER = httpwwwgooglecomrecaptchaapiverify

xml()generates the xml for this component

class gluontoolsRecaptcha2(request=None public_key=rdquo private_key=rdquo er-ror_message=rsquoinvalidrsquo label=rsquoVerifyrsquo options=None com-ment=rdquo)

Bases gluonhtmlDIV

Experimental Creates a DIV holding the newer Recaptcha from Google (v2)

Parameters

bull request ndash the request If not passed uses current request

bull public_key ndash the public key Google gave you

bull private_key ndash the private key Google gave you

bull error_message ndash the error message to show if verification fails

bull label ndash the label to use

bull options (dict) ndash takes these parameters

ndash hl

ndash theme

ndash type

341 Auth Mail PluginManager and various utilities 129

web2py Documentation Release 2146-stable

ndash tabindex

ndash callback

ndash expired-callback

see httpsdevelopersgooglecomrecaptchadocsdisplay for docs about those

bull comment ndash the comment

Examples

Use as

form = FORM(Recaptcha2(public_key= private_key=))

or

form = SQLFORM()formappend(Recaptcha2(public_key= private_key=))

to protect the login page instead use

from gluontools import Recaptcha2authsettingscaptcha = Recaptcha2(request public_key= private_key=)

API_URI = httpswwwgooglecomrecaptchaapijs

VERIFY_SERVER = httpswwwgooglecomrecaptchaapisiteverify

xml()generates the xml for this component

class gluontoolsCrud(environment db=None controller=rsquodefaultrsquo)Bases object

static archive(form archive_table=None current_record=rsquocurrent_recordrsquo)

create(table next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt message=ltfunction ltlambdagtgt form-name=ltfunction ltlambdagtgt attributes)

delete(table record_id next=ltfunction ltlambdagtgt message=ltfunction ltlambdagtgt)

get_format(field)

get_query(field op value refsearch=False)

has_permission(name table record=0)

log_event(message vars)

read(table record)

rows(table query=None fields=None orderby=None limitby=None)

search(tables args)Creates a search form and its results for a table rubric Examples

Use as

130 Chapter 34 tools Module

web2py Documentation Release 2146-stable

form results = crudsearch(dbtestqueries = [equals not equal contains]query_labels=equalsEquals

not equalNot equalfields = [idchildren]field_labels =

idIDchildrenChildrenzero=Please choosequery = (dbtestid gt 0)amp(dbtestid = 3) )

select(table query=None fields=None orderby=None limitby=None headers=None attr)

tables()

update(table record next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt ondelete=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgtmessage=ltfunction ltlambdagtgt deletable=ltfunction ltlambdagtgt formname=ltfunctionltlambdagtgt attributes)

url(f=None args=None vars=None)This should point to the controller that exposes download and crud

class gluontoolsService(environment=None)Bases object

exception JsonRpcException(code info)Bases exceptionsException

amfrpc(f)

Example

Use as

service = Service()serviceamfrpcdef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget httpappdefaultcallamfrpcmyfunctiona=helloampb=world

amfrpc3(domain=rsquodefaultrsquo)

Example

Use as

service = Service()serviceamfrpc3(domain)def myfunction(a b)

return a + bdef call()

return service()

341 Auth Mail PluginManager and various utilities 131

web2py Documentation Release 2146-stable

Then call it with

wget http appdefaultcallamfrpc3myfunctiona=helloampb=world

csv(f)

Example

Use as

service = Service()servicecsvdef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget httpappdefaultcallcsvmyfunctiona=3ampb=4

error()

json(f)

Example

Use as

service = Service()servicejsondef myfunction(a b)

return [a b]def call()

return service()

Then call it with

wget http appdefaultcalljsonmyfunctiona=helloampb=world

jsonrpc(f)

Example

Use as

service = Service()servicejsonrpcdef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget http appdefaultcalljsonrpcmyfunctiona=helloampb=world

132 Chapter 34 tools Module

web2py Documentation Release 2146-stable

jsonrpc2(f)

Example

Use as

service = Service()servicejsonrpc2def myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget ndashpost-data lsquoldquojsonrpcrdquo ldquo20rdquo ldquoidrdquo 1 ldquomethodrdquo ldquomyfunctionrdquo ldquoparamsrdquo ldquoardquo 1 ldquobrdquo2rsquo http appdefaultcalljsonrpc2

jsonrpc_errors = -32700 (Parse error Invalid JSON was received by the server An error occurred on the server while parsing the JSON text) -32603 (Internal error Internal JSON-RPC error) -32602 (Invalid params Invalid method parameter(s)) -32601 (Method not found The method does not exist is not available) -32600 (Invalid Request The JSON sent is not a valid Request object) -32099 (Server error Reserved for implementation-defined server-errors)

rss(f)

Example

Use as

service = Service()servicerssdef myfunction()

return dict(title= link= description=created_on= entries=[dict(title= link=

description= created_on=])def call()

return service()

Then call it with

wget http appdefaultcallrssmyfunction

run(f)

Example

Use as

service = Service()servicerundef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget httpappdefaultcallrunmyfunctiona=3ampb=4

341 Auth Mail PluginManager and various utilities 133

web2py Documentation Release 2146-stable

serve_amfrpc(version=0)

serve_csv(args=None)

serve_json(args=None)

serve_jsonrpc()

serve_jsonrpc2(data=None batch_element=False)

serve_rss(args=None)

serve_run(args=None)

serve_soap(version=rsquo11rsquo)

serve_xml(args=None)

serve_xmlrpc()

soap(name=None returns=None args=None doc=None)

Example

Use as

service = Service()servicesoap(MyFunctionreturns=resultintargs=aintbint)def myfunction(a b)

return a + bdef call()

return service()

Then call it with

from gluoncontribpysimplesoapclient import SoapClientclient = SoapClient(wsdl=httpappdefaultcallsoapWSDL)response = clientMyFunction(a=1b=2)return response[result]

It also exposes online generated documentation and xml example messages athttp appdefaultcallsoap

xml(f)

Example

Use as

service = Service()servicexmldef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget httpappdefaultcallxmlmyfunctiona=3ampb=4

134 Chapter 34 tools Module

web2py Documentation Release 2146-stable

xmlrpc(f)

Example

Use as

service = Service()servicexmlrpcdef myfunction(a b)

return a + bdef call()

return service()

The call it with

wget http appdefaultcallxmlrpcmyfunctiona=helloampb=world

class gluontoolsWiki(auth env=None render=rsquomarkminrsquo manage_permissions=Falseforce_prefix=rdquo restrict_search=False extra=None menu_groups=Nonetemplates=None migrate=True controller=None function=Nonegroups=None)

Bases object

automenu()adds the menu if not present

can_edit(page=None)

can_manage()

can_read(page)

can_search()

can_see_menu()

cloud()

static component(text)In wiki docs allows componentcontrollerfunctionargs which renders as a LOAD( ajax=True)

create()

edit(slug from_template=0)

editmedia(slug)

everybody = everybody

first_paragraph(page)

fix_hostname(body)

get_renderer()

html_render(page)

markmin_base(body)

markmin_render(page)

media(id)

menu(controller=rsquodefaultrsquo function=rsquoindexrsquo)

341 Auth Mail PluginManager and various utilities 135

web2py Documentation Release 2146-stable

not_authorized(page=None)

pages()

preview(render)

read(slug force_render=False)

render_tags(tags)

rows_page = 25

search(tags=None query=None cloud=True preview=True limitby=(0 100) orderby=None)

class gluontoolsPluginManager(plugin=None defaults)Bases object

Plugin Manager is similar to a storage object but it is a single level singleton This means that multiple instanceswithin the same thread share the same attributes Its constructor is also special The first argument is the nameof the plugin you are defining The named arguments are parameters needed by the plugin with default valuesIf the parameters were previous defined the old values are used

Example

in some general configuration file

plugins = PluginManager()pluginsmeparam1=3

within the plugin model

_ = PluginManager(meparam1=5param2=6param3=7)

where the plugin is used

gtgtgt print pluginsmeparam13gtgtgt print pluginsmeparam26gtgtgt pluginsmeparam3 = 8gtgtgt print pluginsmeparam38

Here are some tests

gtgtgt a=PluginManager()gtgtgt ax=6gtgtgt b=PluginManager(check)gtgtgt print bx6gtgtgt b=PluginManager() reset settingsgtgtgt print bxltStorage gtgtgtgt bx=7gtgtgt print ax7gtgtgt ayz=8gtgtgt print byz8

(continues on next page)

136 Chapter 34 tools Module

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt test_thread_separation()5gtgtgt plugins=PluginManager(medb=mydb)gtgtgt print pluginsmedbmydbgtgtgt print me in pluginsTruegtgtgt print pluginsmeinstalledTrue

instances =

keys()

gluontoolsfetch(url data=None headers=None cookie= user_agent=rsquoMozilla50rsquo)

gluontoolsgeocode(address)

gluontoolsreverse_geocode(lat lng lang=None)Try to get an approximate address for a given latitude longitude

gluontoolsprettydate(d T=ltfunction ltlambdagtgt utc=False)

341 Auth Mail PluginManager and various utilities 137

web2py Documentation Release 2146-stable

138 Chapter 34 tools Module

CHAPTER 35

utf8 Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)Created by Vladyslav Kozlovskyy (Ukraine) ltdbdevelopcopygmailcomgtfor Web2py project

351 Utilities and class for UTF8 strings managing

class gluonutf8Utf8Bases str

Class for utf8 string storing and manipulations

The base presupposition of this class usage is ldquoALL strings in the application are either of utf-8 or unicodetype even when simple str type is used UTF-8 is only a ldquopackedrdquo version of unicode so Utf-8 and unicodestrings are interchangeablerdquo

CAUTION This class is slower than strunicode Do NOT use it inside intensive loops Simply decode string(s)to unicode before loop and encode it back to utf-8 string(s) after intensive calculation

You can see the benefit of this class in doctests() below

capitalize()rarr stringReturn a copy of the string S with only its first character capitalized

center(width[ fillchar ])rarr stringReturn S centered in a string of length width Padding is done using the specified fill character (default isa space)

count(sub[ start[ end ]])rarr intReturn the number of non-overlapping occurrences of substring sub in string S[startend] Optional argu-ments start and end are interpreted as in slice notation

139

web2py Documentation Release 2146-stable

decode([encoding[ errors]])rarr objectDecodes S using the codec registered for encoding encoding defaults to the default encoding errors maybe given to set a different error handling scheme Default is lsquostrictrsquo meaning that encoding errors raise aUnicodeDecodeError Other possible values are lsquoignorersquo and lsquoreplacersquo as well as any other name registeredwith codecsregister_error that is able to handle UnicodeDecodeErrors

encode([encoding[ errors]])rarr objectEncodes S using the codec registered for encoding encoding defaults to the default encoding errors maybe given to set a different error handling scheme Default is lsquostrictrsquo meaning that encoding errors raise aUnicodeEncodeError Other possible values are lsquoignorersquo lsquoreplacersquo and lsquoxmlcharrefreplacersquo as well as anyother name registered with codecsregister_error that is able to handle UnicodeEncodeErrors

endswith(suffix[ start[ end ]])rarr boolReturn True if S ends with the specified suffix False otherwise With optional start test S beginning atthat position With optional end stop comparing S at that position suffix can also be a tuple of strings totry

expandtabs([tabsize])rarr stringReturn a copy of S where all tab characters are expanded using spaces If tabsize is not given a tab size of8 characters is assumed

find(sub[ start[ end ]])rarr intReturn the lowest index in S where substring sub is found such that sub is contained within S[startend]Optional arguments start and end are interpreted as in slice notation

Return -1 on failure

format(args kwargs)rarr stringReturn a formatted version of S using substitutions from args and kwargs The substitutions are identifiedby braces (lsquolsquo and lsquorsquo)

index(sub[ start[ end ]])rarr intLike Sfind() but raise ValueError when the substring is not found

isalnum()rarr boolReturn True if all characters in S are alphanumeric and there is at least one character in S False otherwise

isalpha()rarr boolReturn True if all characters in S are alphabetic and there is at least one character in S False otherwise

isdigit()rarr boolReturn True if all characters in S are digits and there is at least one character in S False otherwise

islower()rarr boolReturn True if all cased characters in S are lowercase and there is at least one cased character in S Falseotherwise

isspace()rarr boolReturn True if all characters in S are whitespace and there is at least one character in S False otherwise

istitle()rarr boolReturn True if S is a titlecased string and there is at least one character in S ie uppercase characters mayonly follow uncased characters and lowercase characters only cased ones Return False otherwise

isupper()rarr boolReturn True if all cased characters in S are uppercase and there is at least one cased character in S Falseotherwise

join(iterable)rarr stringReturn a string which is the concatenation of the strings in the iterable The separator between elements isS

140 Chapter 35 utf8 Module

web2py Documentation Release 2146-stable

ljust(width[ fillchar ])rarr stringReturn S left-justified in a string of length width Padding is done using the specified fill character (defaultis a space)

lower()rarr stringReturn a copy of the string S converted to lowercase

lstrip([chars])rarr string or unicodeReturn a copy of the string S with leading whitespace removed If chars is given and not None removecharacters in chars instead If chars is unicode S will be converted to unicode before stripping

partition(sep) -gt (head sep tail)Search for the separator sep in S and return the part before it the separator itself and the part after it Ifthe separator is not found return S and two empty strings

replace(old new[ count ])rarr stringReturn a copy of string S with all occurrences of substring old replaced by new If the optional argumentcount is given only the first count occurrences are replaced

rfind(sub[ start[ end ]])rarr intReturn the highest index in S where substring sub is found such that sub is contained within S[startend]Optional arguments start and end are interpreted as in slice notation

Return -1 on failure

rindex(sub[ start[ end ]])rarr intLike Srfind() but raise ValueError when the substring is not found

rjust(width[ fillchar ])rarr stringReturn S right-justified in a string of length width Padding is done using the specified fill character (defaultis a space)

rpartition(sep) -gt (head sep tail)Search for the separator sep in S starting at the end of S and return the part before it the separator itselfand the part after it If the separator is not found return two empty strings and S

rsplit([sep[ maxsplit ]])rarr list of stringsReturn a list of the words in the string S using sep as the delimiter string starting at the end of the stringand working to the front If maxsplit is given at most maxsplit splits are done If sep is not specified or isNone any whitespace string is a separator

rstrip([chars])rarr string or unicodeReturn a copy of the string S with trailing whitespace removed If chars is given and not None removecharacters in chars instead If chars is unicode S will be converted to unicode before stripping

split([sep[ maxsplit ]])rarr list of stringsReturn a list of the words in the string S using sep as the delimiter string If maxsplit is given at mostmaxsplit splits are done If sep is not specified or is None any whitespace string is a separator and emptystrings are removed from the result

splitlines(keepends=False)rarr list of stringsReturn a list of the lines in S breaking at line boundaries Line breaks are not included in the resulting listunless keepends is given and true

startswith(prefix[ start[ end ]])rarr boolReturn True if S starts with the specified prefix False otherwise With optional start test S beginning atthat position With optional end stop comparing S at that position prefix can also be a tuple of strings totry

strip([chars])rarr string or unicodeReturn a copy of the string S with leading and trailing whitespace removed If chars is given and not None

351 Utilities and class for UTF8 strings managing 141

web2py Documentation Release 2146-stable

remove characters in chars instead If chars is unicode S will be converted to unicode before stripping

swapcase()rarr stringReturn a copy of the string S with uppercase characters converted to lowercase and vice versa

title()rarr stringReturn a titlecased version of S ie words start with uppercase characters all remaining cased charactershave lowercase

translate(table[ deletechars])rarr stringReturn a copy of the string S where all characters occurring in the optional argument deletechars areremoved and the remaining characters have been mapped through the given translation table which mustbe a string of length 256 or None If the table argument is None no translation is applied and the operationsimply removes the characters in deletechars

upper()rarr stringReturn a copy of the string S converted to uppercase

zfill(width)rarr stringPad a numeric string S with zeros on the left to fill a field of the specified width The string S is nevertruncated

142 Chapter 35 utf8 Module

CHAPTER 36

utils Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

361 This file specifically includes utilities for security

gluonutilsAES_new(key IV=None)Returns an AES cipher object and random IV if None specified

gluonutilscompare(a b)Compares two strings and not vulnerable to timing attacks

gluonutilsfast_urandom16(urandom=[] locker=lt_RLock owner=None count=0gt)This is 4x faster than calling osurandom(16) and prevents the ldquotoo many files openrdquo issue with concurrent accessto osurandom()

gluonutilsget_callable_argspec(fn)

gluonutilsget_digest(value)Returns a hashlib digest algorithm from a string

gluonutilsgetipaddrinfo(host)Filter out non-IP and bad IP addresses from getaddrinfo

gluonutilsinitialize_urandom()This function and the web2py_uuid follow from the following discussionhttpgroupsgooglecomgroupweb2py-developersbrowse_threadthread7fd5789a7da3f09

At startup web2py compute a unique ID that identifies the machine by adding uuidgetnode() + int(timetime() 1e3)

This is a 48-bit number It converts the number into 16 8-bit tokens It uses this value to initialize the entropysource (lsquodevurandomrsquo) and to seed random

143

web2py Documentation Release 2146-stable

If osrandom() is not supported it falls back to using random and issues a warning

gluonutilsis_loopback_ip_address(ip=None addrinfo=None)Determines whether the address appears to be a loopback address This assumes that the IP is valid

gluonutilsis_valid_ip_address(address)

Examples

Better than a thousand words

gtgtgt is_valid_ip_address(1270)Falsegtgtgt is_valid_ip_address(127001)Truegtgtgt is_valid_ip_address(20016601)True

gluonutilsmd5_hash(text)Generates a md5 hash with the given text

gluonutilspad(s n=32 padchar=rsquo rsquo)

gluonutilspbkdf2_hex(data salt iterations=1000 keylen=24 hashfunc=None)

gluonutilssecure_dumps(data encryption_key hash_key=None compression_level=None)

gluonutilssecure_loads(data encryption_key hash_key=None compression_level=None)

gluonutilssimple_hash(text key=rdquo salt=rdquo digest_alg=rsquomd5rsquo)Generates hash with the given text using the specified digest hashing algorithm

gluonutilsweb2py_uuid(ctokens=(12807810588179607998L 787762416516532974))This function follows from the following discussion httpgroupsgooglecomgroupweb2py-developersbrowse_threadthread7fd5789a7da3f09

It works like uuiduuid4 except that tries to use osurandom() if possible and it XORs the output with the tokensuniquely associated with this machine

144 Chapter 36 utils Module

CHAPTER 37

validators Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)Thanks to ga2arch for help with IS_IN_DB and IS_NOT_IN_DB on GAE

371 Validators

class gluonvalidatorsANY_OF(subs)Bases gluonvalidatorsValidator

Tests if any of the validators in a list returns successfully

gtgtgt ANY_OF([IS_EMAIL()IS_ALPHANUMERIC()])(abco)(abco None)gtgtgt ANY_OF([IS_EMAIL()IS_ALPHANUMERIC()])(abco)(abco None)gtgtgt ANY_OF([IS_EMAIL()IS_ALPHANUMERIC()])(abco)(abco enter only letters numbers and underscore)gtgtgt ANY_OF([IS_ALPHANUMERIC()IS_EMAIL()])(abco)(abco enter a valid email address)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

class gluonvalidatorsCLEANUP(regex=None)Bases gluonvalidatorsValidator

Examples

Use as

145

web2py Documentation Release 2146-stable

INPUT(_type=text _name=name requires=CLEANUP())

removes special characters on validation

REGEX_CLEANUP = lt_sreSRE_Pattern objectgt

class gluonvalidatorsCRYPT(key=None digest_alg=rsquopbkdf2(1000 20 sha512)rsquo min_length=0error_message=rsquoToo shortrsquo salt=True max_length=1024)

Bases object

Examples

Use as

INPUT(_type=text _name=name requires=CRYPT())

encodes the value on validation with a digest

If no arguments are provided CRYPT uses the MD5 algorithm If the key argument is provided the HMAC+MD5algorithm is used If the digest_alg is specified this is used to replace the MD5 with for example SHA512 Thedigest_alg can be the name of a hashlib algorithm as a string or the algorithm itself

min_length is the minimal password length (default 4) - IS_STRONG for serious security error_message is themessage if password is too short

Notice that an empty password is accepted but invalid It will not allow login back Stores junk as hashedpassword

Specify an algorithm or by default we will use sha512

Typical available algorithms md5 sha1 sha224 sha256 sha384 sha512

If salt it hashes a password with a salt If salt is True this method will automatically generate one Either caseit returns an encrypted password string in the following format

ltalgorithmgt$ltsaltgt$lthashgt

Important hashed password is returned as a LazyCrypt object and computed only if needed The LasyCryptobject also knows how to compare itself with an existing salted password

Supports standard algorithms

gtgtgt for alg in (md5sha1sha256sha384sha512) print str(CRYPT(digest_alg=algsalt=True)(test)[0])md5$$sha1$$sha256$$sha384$$sha512$$

The syntax is always alg$salt$hash

Supports for pbkdf2

gtgtgt alg = pbkdf2(100020sha512)gtgtgt print str(CRYPT(digest_alg=algsalt=True)(test)[0])pbkdf2(100020sha512)$$

An optional hmac_key can be specified and it is used as salt prefix

146 Chapter 37 validators Module

web2py Documentation Release 2146-stable

gtgtgt a = str(CRYPT(digest_alg=md5key=mykeysalt=True)(test)[0])gtgtgt print amd5$$

Even if the algorithm changes the hash can still be validated

gtgtgt CRYPT(digest_alg=sha1key=mykeysalt=True)(test)[0] == aTrue

If no salt is specified CRYPT can guess the algorithms from length

gtgtgt a = str(CRYPT(digest_alg=sha1salt=False)(test)[0])gtgtgt asha1$$a94a8fe5ccb19ba61c4c0873d391e987982fbbd3gtgtgt CRYPT(digest_alg=sha1salt=False)(test)[0] == aTruegtgtgt CRYPT(digest_alg=sha1salt=False)(test)[0] == a[6]Truegtgtgt CRYPT(digest_alg=md5salt=False)(test)[0] == aTruegtgtgt CRYPT(digest_alg=md5salt=False)(test)[0] == a[6]True

class gluonvalidatorsIS_ALPHANUMERIC(error_message=rsquoEnter only letters numbers andunderscorersquo)

Bases gluonvalidatorsIS_MATCH

Example

Used as

INPUT(_type=text _name=name requires=IS_ALPHANUMERIC())

gtgtgt IS_ALPHANUMERIC()(1)(1 None)gtgtgt IS_ALPHANUMERIC()()( None)gtgtgt IS_ALPHANUMERIC()(A_a)(A_a None)gtgtgt IS_ALPHANUMERIC()()( enter only letters numbers and underscore)

class gluonvalidatorsIS_DATE_IN_RANGE(minimum=None maximum=None format=rsquoY-m-drsquo error_message=None)

Bases gluonvalidatorsIS_DATE

Examples

Use as

gtgtgt v = IS_DATE_IN_RANGE(minimum=datetimedate(200811)rarr˓ maximum=datetimedate(20091231)rarr˓ format=mdYerror_message=Oops)

(continues on next page)

371 Validators 147

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt v(03032008)(datetimedate(2008 3 3) None)

gtgtgt v(03032010)(03032010 oops)

gtgtgt v(datetimedate(200833))(datetimedate(2008 3 3) None)

gtgtgt v(datetimedate(201033))(datetimedate(2010 3 3) oops)

class gluonvalidatorsIS_DATE(format=rsquoY-m-drsquo error_message=rsquoEnter date as (for-mat)srsquo)

Bases gluonvalidatorsValidator

Examples

Use as

INPUT(_type=text _name=name requires=IS_DATE())

date has to be in the ISO8960 format YYYY-MM-DD

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

class gluonvalidatorsIS_DATETIME_IN_RANGE(minimum=None maximum=Noneformat=rsquoY-m-d HMSrsquo er-ror_message=None timezone=None)

Bases gluonvalidatorsIS_DATETIME

Examples

Use as

gtgtgt v = IS_DATETIME_IN_RANGE( minimum=datetimerarr˓datetime(2008111220) maximum=datetimerarr˓datetime(200912311220) format=mdY HMrarr˓error_message=Oops)gtgtgt v(03032008 1240)(datetimedatetime(2008 3 3 12 40) None)

gtgtgt v(03032010 1034)(03032010 1034 oops)

gtgtgt v(datetimedatetime(20083300))(datetimedatetime(2008 3 3 0 0) None)

gtgtgt v(datetimedatetime(20103300))(datetimedatetime(2010 3 3 0 0) oops)

148 Chapter 37 validators Module

web2py Documentation Release 2146-stable

class gluonvalidatorsIS_DATETIME(format=rsquoY-m-d HMSrsquo er-ror_message=rsquoEnter date and time as (format)srsquotimezone=None)

Bases gluonvalidatorsValidator

Examples

Use as

INPUT(_type=text _name=name requires=IS_DATETIME())

datetime has to be in the ISO8960 format YYYY-MM-DD hhmmss timezome must be None or apytztimezone(ldquoAmericaChicagordquo) object

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

isodatetime = Y-m-d HMS

static nice(format)

class gluonvalidatorsIS_DECIMAL_IN_RANGE(minimum=None maximum=None er-ror_message=None dot=rsquorsquo)

Bases gluonvalidatorsValidator

Determines that the argument is (or can be represented as) a Python Decimal and that it falls within the specifiedinclusive range The comparison is made with Python Decimal arithmetic

The minimum and maximum limits can be None meaning no lower or upper limit respectively

Example

Used as

INPUT(_type=text _name=name requires=IS_DECIMAL_IN_RANGE(0 10))

gtgtgt IS_DECIMAL_IN_RANGE(15)(4)(Decimal(4) None)gtgtgt IS_DECIMAL_IN_RANGE(15)(4)(Decimal(4) None)gtgtgt IS_DECIMAL_IN_RANGE(15)(1)(Decimal(1) None)gtgtgt IS_DECIMAL_IN_RANGE(15)(525)(525 enter a number between 1 and 5)gtgtgt IS_DECIMAL_IN_RANGE(5256)(525)(Decimal(525) None)gtgtgt IS_DECIMAL_IN_RANGE(5256)(525)(Decimal(525) None)gtgtgt IS_DECIMAL_IN_RANGE(15)(60)(60 enter a number between 1 and 5)gtgtgt IS_DECIMAL_IN_RANGE(15)(35)(Decimal(35) None)gtgtgt IS_DECIMAL_IN_RANGE(1555)(35)(Decimal(35) None)gtgtgt IS_DECIMAL_IN_RANGE(1555)(65)(65 enter a number between 15 and 55)

(continues on next page)

371 Validators 149

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_DECIMAL_IN_RANGE(15None)(65)(Decimal(65) None)gtgtgt IS_DECIMAL_IN_RANGE(15None)(05)(05 enter a number greater than or equal to 15)gtgtgt IS_DECIMAL_IN_RANGE(None55)(45)(Decimal(45) None)gtgtgt IS_DECIMAL_IN_RANGE(None55)(65)(65 enter a number less than or equal to 55)gtgtgt IS_DECIMAL_IN_RANGE()(65)(Decimal(65) None)gtgtgt IS_DECIMAL_IN_RANGE(099)(123123)(123123 enter a number between 0 and 99)gtgtgt IS_DECIMAL_IN_RANGE(099)(123123)(123123 enter a number between 0 and 99)gtgtgt IS_DECIMAL_IN_RANGE(099)(1234)(Decimal(1234) None)gtgtgt IS_DECIMAL_IN_RANGE()(abc)(abc enter a number)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

class gluonvalidatorsIS_EMAIL(banned=None forced=None error_message=rsquoEnter a validemail addressrsquo)

Bases gluonvalidatorsValidator

Checks if fieldrsquos value is a valid email address Can be set to disallow or force addresses from certain domain(s)

Email regex adapted from httphaackedcomarchive20070821i-knew-how-to-validate-an-email-address-until-iaspx generally following the RFCs except that we disallow quoted strings and permit underscores and leadingnumerics in subdomain labels

Parameters

bull banned ndash regex text for disallowed address domains

bull forced ndash regex text for required address domains

Both arguments can also be custom objects with a match(value) method

Example

Check for valid email address

INPUT(_type=text _name=namerequires=IS_EMAIL())

Check for valid email address that canrsquot be from a com domain

INPUT(_type=text _name=namerequires=IS_EMAIL(banned=^com(|)$))

Check for valid email address that must be from a edu domain

INPUT(_type=text _name=namerequires=IS_EMAIL(forced=^edu(|)$))

(continues on next page)

150 Chapter 37 validators Module

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_EMAIL()(abcom)(abcom None)gtgtgt IS_EMAIL()(abcdefcom)(abcdefcom None)gtgtgt IS_EMAIL()(abc3defcom)(abc3defcom None)gtgtgt IS_EMAIL()(abcdefus)(abcdefus None)gtgtgt IS_EMAIL()(abcd_-fus)(abcd_-fus None)gtgtgt IS_EMAIL()(defcom) missing name(defcom enter a valid email address)gtgtgt IS_EMAIL()(abcdefcom) quoted name(abcdefcom enter a valid email address)gtgtgt IS_EMAIL()(abc+defcom) no (abc+defcom enter a valid email address)gtgtgt IS_EMAIL()(abcdefx) one-char TLD(abcdefx enter a valid email address)gtgtgt IS_EMAIL()(abcdef12) numeric TLD(abcdef12 enter a valid email address)gtgtgt IS_EMAIL()(abcdefcom) double-dot in domain(abcdefcom enter a valid email address)gtgtgt IS_EMAIL()(abcdefcom) dot starts domain(abcdefcom enter a valid email address)gtgtgt IS_EMAIL()(abcdefc_m) underscore in TLD(abcdefc_m enter a valid email address)gtgtgt IS_EMAIL()(NotAnEmail) missing (NotAnEmail enter a valid email address)gtgtgt IS_EMAIL()(abcNotAnEmail) missing TLD(abcNotAnEmail enter a valid email address)gtgtgt IS_EMAIL()(customerdepartmentexamplecom)(customerdepartmentexamplecom None)gtgtgt IS_EMAIL()($A12345examplecom)($A12345examplecom None)gtgtgt IS_EMAIL()(defxyzabcexamplecom)(defxyzabcexamplecom None)gtgtgt IS_EMAIL()(_YosemiteSamexamplecom)(_YosemiteSamexamplecom None)gtgtgt IS_EMAIL()(~examplecom)(~examplecom None)gtgtgt IS_EMAIL()(woolyexamplecom) dot starts name(woolyexamplecom enter a valid email address)gtgtgt IS_EMAIL()(woolyexamplecom) adjacent dots in name(woolyexamplecom enter a valid email address)gtgtgt IS_EMAIL()(pootietangexamplecom) dot ends name(pootietangexamplecom enter a valid email address)gtgtgt IS_EMAIL()(examplecom) name is bare dot(examplecom enter a valid email address)gtgtgt IS_EMAIL()(ImaFoolexamplecom)(ImaFoolexamplecom None)gtgtgt IS_EMAIL()(Ima Foolexamplecom) space in name(Ima Foolexamplecom enter a valid email address)gtgtgt IS_EMAIL()(localguylocalhost) localhost as domain(localguylocalhost None)

regex = lt_sreSRE_Pattern object at 0x2e0e160gt

371 Validators 151

web2py Documentation Release 2146-stable

regex_proposed_but_failed = lt_sreSRE_Pattern object at 0x2e100d0gt

class gluonvalidatorsIS_LIST_OF_EMAILS(error_message=rsquoInvalid emails srsquo)Bases object

Example

Used as

Field(emailsliststringwidget=SQLFORMwidgetstextwidgetrequires=IS_LIST_OF_EMAILS()represent=lambda vr SPAN([A(x_href=mailto+x)

rarr˓for x in (v or [])]))

formatter(value row=None)

split_emails = lt_sreSRE_Pattern objectgt

class gluonvalidatorsIS_EMPTY_OR(other null=None empty_regex=None)Bases gluonvalidatorsValidator

Dummy class for testing IS_EMPTY_OR

gtgtgt IS_EMPTY_OR(IS_EMAIL())(abcdefcom)(abcdefcom None)gtgtgt IS_EMPTY_OR(IS_EMAIL())( )(None None)gtgtgt IS_EMPTY_OR(IS_EMAIL() null=abc)( )(abc None)gtgtgt IS_EMPTY_OR(IS_EMAIL() null=abc empty_regex=def)(def)(abc None)gtgtgt IS_EMPTY_OR(IS_EMAIL())(abc)(abc enter a valid email address)gtgtgt IS_EMPTY_OR(IS_EMAIL())( abc )(abc enter a valid email address)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

set_self_id(id)

class gluonvalidatorsIS_EXPR(expression error_message=rsquoInvalid expressionrsquo environ-ment=None)

Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=namerequires=IS_EXPR(5 lt int(value) lt 10))

The argument of IS_EXPR must be python condition

152 Chapter 37 validators Module

web2py Documentation Release 2146-stable

gtgtgt IS_EXPR(int(value) lt 2)(1)(1 None)

gtgtgt IS_EXPR(int(value) lt 2)(2)(2 invalid expression)

class gluonvalidatorsIS_FLOAT_IN_RANGE(minimum=None maximum=None er-ror_message=None dot=rsquorsquo)

Bases gluonvalidatorsValidator

Determines that the argument is (or can be represented as) a float and that it falls within the specified inclusiverange The comparison is made with native arithmetic

The minimum and maximum limits can be None meaning no lower or upper limit respectively

Example

Used as

INPUT(_type=text _name=name requires=IS_FLOAT_IN_RANGE(0 10))

gtgtgt IS_FLOAT_IN_RANGE(15)(4)(40 None)gtgtgt IS_FLOAT_IN_RANGE(15)(4)(40 None)gtgtgt IS_FLOAT_IN_RANGE(15)(1)(10 None)gtgtgt IS_FLOAT_IN_RANGE(15)(525)(525 enter a number between 1 and 5)gtgtgt IS_FLOAT_IN_RANGE(15)(60)(60 enter a number between 1 and 5)gtgtgt IS_FLOAT_IN_RANGE(15)(35)(35 None)gtgtgt IS_FLOAT_IN_RANGE(1None)(35)(35 None)gtgtgt IS_FLOAT_IN_RANGE(None5)(35)(35 None)gtgtgt IS_FLOAT_IN_RANGE(1None)(05)(05 enter a number greater than or equal to 1)gtgtgt IS_FLOAT_IN_RANGE(None5)(65)(65 enter a number less than or equal to 5)gtgtgt IS_FLOAT_IN_RANGE()(65)(65 None)gtgtgt IS_FLOAT_IN_RANGE()(abc)(abc enter a number)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

class gluonvalidatorsIS_IMAGE(extensions=(rsquobmprsquo rsquogifrsquo rsquojpegrsquo rsquopngrsquo) maxsize=(1000010000) minsize=(0 0) error_message=rsquoInvalid imagersquo)

Bases gluonvalidatorsValidator

Checks if file uploaded through file input was saved in one of selected image formats and has dimensions (widthand height) within given boundaries

371 Validators 153

web2py Documentation Release 2146-stable

Does not check for maximum file size (use IS_LENGTH for that) Returns validation failure if no data wasuploaded

Supported file formats BMP GIF JPEG PNG

Code parts taken from httpmailpythonorgpipermailpython-list2007-June617126html

Parameters

bull extensions ndash iterable containing allowed lowercase image file extensions

bull extension of uploaded file counts as jpeg) ((jpg) ndash

bull maxsize ndash iterable containing maximum width and height of the image

bull minsize ndash iterable containing minimum width and height of the image

Use (-1 -1) as minsize to pass image size check

Examples

Check if uploaded file is in any of supported image formats

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_IMAGE())

Check if uploaded file is either JPEG or PNG

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_IMAGE(extensions=(lsquojpegrsquo lsquopngrsquo)))

Check if uploaded file is PNG with maximum size of 200x200 pixels

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_IMAGE(extensions=(lsquopngrsquo) maxsize=(200200)))

class gluonvalidatorsIS_IN_DB(dbset field label=None error_message=rsquoValue not indatabasersquo orderby=None groupby=None distinct=Nonecache=None multiple=False zero=rdquo sort=False_and=None left=None delimiter=None auto_add=False)

Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=namerequires=IS_IN_DB(db dbmytablemyfield zero=))

used for reference fields rendered as a dropbox

build_set()

maybe_add(table fieldname value)

options(zero=True)

set_self_id(id)

class gluonvalidatorsIS_IN_SET(theset labels=None error_message=rsquoValue not allowedrsquomultiple=False zero=rdquo sort=False)

Bases gluonvalidatorsValidator

154 Chapter 37 validators Module

web2py Documentation Release 2146-stable

Example

Used as

INPUT(_type=text _name=namerequires=IS_IN_SET([max john]zero=))

The argument of IS_IN_SET must be a list or set

gtgtgt IS_IN_SET([max john])(max)(max None)gtgtgt IS_IN_SET([max john])(massimo)(massimo value not allowed)gtgtgt IS_IN_SET([max john] multiple=True)((max john))((max john) None)gtgtgt IS_IN_SET([max john] multiple=True)((bill john))((bill john) value not allowed)gtgtgt IS_IN_SET((id1id2) [first labelsecond label])(id1) Traditionalrarr˓way(id1 None)gtgtgt IS_IN_SET(id1first label id2second label)(id1)(id1 None)gtgtgt import itertoolsgtgtgt IS_IN_SET(itertoolschain([135][246]))(1)(1 None)gtgtgt IS_IN_SET([(id1first label) (id2second label)])(id1) Redundantrarr˓way(id1 None)

options(zero=True)

class gluonvalidatorsIS_INT_IN_RANGE(minimum=None maximum=None er-ror_message=None)

Bases gluonvalidatorsValidator

Determines that the argument is (or can be represented as) an int and that it falls within the specified range Therange is interpreted in the Pythonic way so the test is min lt= value lt max

The minimum and maximum limits can be None meaning no lower or upper limit respectively

Example

Used as

INPUT(_type=text _name=name requires=IS_INT_IN_RANGE(0 10))

gtgtgt IS_INT_IN_RANGE(15)(4)(4 None)gtgtgt IS_INT_IN_RANGE(15)(4)(4 None)gtgtgt IS_INT_IN_RANGE(15)(1)(1 None)gtgtgt IS_INT_IN_RANGE(15)(5)(5 enter an integer between 1 and 4)gtgtgt IS_INT_IN_RANGE(15)(5)(5 enter an integer between 1 and 4)gtgtgt IS_INT_IN_RANGE(15)(35)

(continues on next page)

371 Validators 155

web2py Documentation Release 2146-stable

(continued from previous page)

(35 enter an integer between 1 and 4)gtgtgt IS_INT_IN_RANGE(None5)(4)(4 None)gtgtgt IS_INT_IN_RANGE(None5)(6)(6 enter an integer less than or equal to 4)gtgtgt IS_INT_IN_RANGE(1None)(4)(4 None)gtgtgt IS_INT_IN_RANGE(1None)(0)(0 enter an integer greater than or equal to 1)gtgtgt IS_INT_IN_RANGE()(6)(6 None)gtgtgt IS_INT_IN_RANGE()(abc)(abc enter an integer)

class gluonvalidatorsIS_IPV4(minip=rsquo0000rsquo maxip=rsquo255255255255rsquo invert=Falseis_localhost=None is_private=None is_automatic=Noneerror_message=rsquoEnter valid IPv4 addressrsquo)

Bases gluonvalidatorsValidator

Checks if fieldrsquos value is an IP version 4 address in decimal form Can be set to force addresses from certainrange

IPv4 regex taken from httpregexlibcomREDetailsaspxregexp_id=1411

Parameters

bull minip ndash lowest allowed address accepts

ndash str eg 19216801

ndash list or tuple of octets eg [192 168 0 1]

bull maxip ndash highest allowed address same as above

bull invert ndash True to allow addresses only from outside of given range note that range bound-aries are not matched this way

bull is_localhost ndash localhost address treatment

ndash None (default) indifferent

ndash True (enforce) query address must match localhost address (127001)

ndash False (forbid) query address must not match localhost address

bull is_private ndash same as above except that query address is checked against two addressranges 1721600 - 17231255255 and 19216800 - 192168255255

bull is_automatic ndash same as above except that query address is checked against one addressrange 16925400 - 169254255255

Minip and maxip may also be lists or tuples of addresses in all above forms (str int list tuple) allowing setupof multiple address ranges

minip = (minip1 minip2 minipN)| | || | |

maxip = (maxip1 maxip2 maxipN)

Longer iterable will be truncated to match length of shorter one

156 Chapter 37 validators Module

web2py Documentation Release 2146-stable

Examples

Check for valid IPv4 address

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV4())

Check for valid IPv4 address belonging to specific range

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV4(minip=lsquo10020000rsquomaxip=lsquo100200255255rsquo))

Check for valid IPv4 address belonging to either 10011000 - 100110255255 or 2005000 - 200500255address range

INPUT(_type=rsquotextrsquo _name=rsquonamersquo

requires=IS_IPV4(minip=(lsquo10011000rsquo lsquo2005000rsquo) maxip=(lsquo100110255255rsquolsquo200500255rsquo)))

Check for valid IPv4 address belonging to private address space

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV4(is_private=True))

Check for valid IPv4 address that is not a localhost address

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV4(is_localhost=False))

gtgtgt IS_IPV4()(1234)(1234 None)gtgtgt IS_IPV4()(255255255255)(255255255255 None)gtgtgt IS_IPV4()(1234 )(1234 enter valid IPv4 address)gtgtgt IS_IPV4()(12345)(12345 enter valid IPv4 address)gtgtgt IS_IPV4()(123123)(123123 enter valid IPv4 address)gtgtgt IS_IPV4()(1111234)(1111234 enter valid IPv4 address)gtgtgt IS_IPV4()(0111234)(0111234 enter valid IPv4 address)gtgtgt IS_IPV4()(256234)(256234 enter valid IPv4 address)gtgtgt IS_IPV4()(300234)(300234 enter valid IPv4 address)gtgtgt IS_IPV4(minip=1234 maxip=1234)(1234)(1234 None)gtgtgt IS_IPV4(minip=1235 maxip=1239 error_message=Bad ip)(1rarr˓234)(1234 bad ip)gtgtgt IS_IPV4(maxip=1234 invert=True)(127001)(127001 None)gtgtgt IS_IPV4(maxip=1234 invert=True)(1234)(1234 enter valid IPv4 address)gtgtgt IS_IPV4(is_localhost=True)(127001)(127001 None)gtgtgt IS_IPV4(is_localhost=True)(1234)(1234 enter valid IPv4 address)gtgtgt IS_IPV4(is_localhost=False)(127001)(127001 enter valid IPv4 address)

(continues on next page)

371 Validators 157

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_IPV4(maxip=100000 is_localhost=True)(127001)(127001 enter valid IPv4 address)

automatic = (2851995648L 2852061183L)

localhost = 2130706433

numbers = (16777216 65536 256 1)

private = ((2886729728L 2886795263L) (3232235520L 3232301055L))

regex = lt_sreSRE_Pattern object at 0x2e26320gt

class gluonvalidatorsIS_IPV6(is_private=None is_link_local=None is_reserved=Noneis_multicast=None is_routeable=None is_6to4=Noneis_teredo=None subnets=None error_message=rsquoEnter validIPv6 addressrsquo)

Bases gluonvalidatorsValidator

Checks if fieldrsquos value is an IP version 6 address First attempts to use the ipaddress library and falls back tocontribipaddrpy from Google (httpscodegooglecompipaddr-py)

Parameters

bull is_private ndash None (default) indifferent True (enforce) address must be in fc007range False (forbid) address must NOT be in fc007 range

bull is_link_local ndash Same as above but uses fe8010 range

bull is_reserved ndash Same as above but uses IETF reserved range

bull is_mulicast ndash Same as above but uses ff008 range

bull is_routeable ndash Similar to above but enforces not private link_local reserved or multi-cast

bull is_6to4 ndash Same as above but uses 200216 range

bull is_teredo ndash Same as above but uses 200132 range

bull subnets ndash value must be a member of at least one from list of subnets

Examples

Check for valid IPv6 address

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV6())

Check for valid IPv6 address is a link_local address

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV6(is_link_local=True))

Check for valid IPv6 address that is Internet routeable

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV6(is_routeable=True))

Check for valid IPv6 address in specified subnet

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV6(subnets=[lsquo200132rsquo])

158 Chapter 37 validators Module

web2py Documentation Release 2146-stable

gtgtgt IS_IPV6()(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPV6()(19216811)(19216811 enter valid IPv6 address)gtgtgt IS_IPV6(error_message=Bad ip)(19216811)(19216811 bad ip)gtgtgt IS_IPV6(is_link_local=True)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPV6(is_link_local=False)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(is_link_local=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(is_multicast=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(is_multicast=True)(ff00126c8ffafe22b3af)(ff00126c8ffafe22b3af None)gtgtgt IS_IPV6(is_routeable=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af None)gtgtgt IS_IPV6(is_routeable=True)(ff00126c8ffafe22b3af)(ff00126c8ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(subnets=200132)(20018ffafe22b3af)(20018ffafe22b3af None)gtgtgt IS_IPV6(subnets=fb008)(20018ffafe22b3af)(20018ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(subnets=[fc008200132])(20018ffafe22b3af)(20018ffafe22b3af None)gtgtgt IS_IPV6(subnets=invalidsubnet)(20018ffafe22b3af)(20018ffafe22b3af invalid subnet provided)

class gluonvalidatorsIS_IPADDRESS(minip=rsquo0000rsquo maxip=rsquo255255255255rsquo in-vert=False is_localhost=None is_private=Noneis_automatic=None is_ipv4=None is_link_local=Noneis_reserved=None is_multicast=Noneis_routeable=None is_6to4=None is_teredo=Nonesubnets=None is_ipv6=None error_message=rsquoEntervalid IP addressrsquo)

Bases gluonvalidatorsValidator

Checks if fieldrsquos value is an IP Address (v4 or v6) Can be set to force addresses from within a specific rangeChecks are done with the correct IS_IPV4 and IS_IPV6 validators

Uses ipaddress library if found falls back to PEP-3144 ipaddrpy from Google (in contrib)

Parameters

bull minip ndash lowest allowed address accepts str eg 19216801 list or tuple of octets eg[192 168 0 1]

bull maxip ndash highest allowed address same as above

bull invert ndash True to allow addresses only from outside of given range note that range bound-aries are not matched this way

IPv4 specific arguments

bull is_localhost localhost address treatment

ndash None (default) indifferent

ndash True (enforce) query address must match localhost address (127001)

371 Validators 159

web2py Documentation Release 2146-stable

ndash False (forbid) query address must not match localhost address

bull is_private same as above except that query address is checked against two address ranges 1721600 -17231255255 and 19216800 - 192168255255

bull is_automatic same as above except that query address is checked against one address range 16925400- 169254255255

bull is_ipv4 either

ndash None (default) indifferent

ndash True (enforce) must be an IPv4 address

ndash False (forbid) must NOT be an IPv4 address

IPv6 specific arguments

bull is_link_local Same as above but uses fe8010 range

bull is_reserved Same as above but uses IETF reserved range

bull is_mulicast Same as above but uses ff008 range

bull is_routeable Similar to above but enforces not private link_local reserved or multicast

bull is_6to4 Same as above but uses 200216 range

bull is_teredo Same as above but uses 200132 range

bull subnets value must be a member of at least one from list of subnets

bull is_ipv6 either

ndash None (default) indifferent

ndash True (enforce) must be an IPv6 address

ndash False (forbid) must NOT be an IPv6 address

Minip and maxip may also be lists or tuples of addresses in all above forms (str int list tuple) allowing setupof multiple address ranges

minip = (minip1 minip2 minipN)| | || | |

maxip = (maxip1 maxip2 maxipN)

Longer iterable will be truncated to match length of shorter one

gtgtgt IS_IPADDRESS()(19216815)(19216815 None)gtgtgt IS_IPADDRESS(is_ipv6=False)(19216815)(19216815 None)gtgtgt IS_IPADDRESS()(255255255255)(255255255255 None)gtgtgt IS_IPADDRESS()(19216815 )(19216815 enter valid IP address)gtgtgt IS_IPADDRESS()(192168115)(192168115 enter valid IP address)gtgtgt IS_IPADDRESS()(123123)(123123 enter valid IP address)gtgtgt IS_IPADDRESS()(1111234)(1111234 enter valid IP address)gtgtgt IS_IPADDRESS()(0111234)

(continues on next page)

160 Chapter 37 validators Module

web2py Documentation Release 2146-stable

(continued from previous page)

(0111234 enter valid IP address)gtgtgt IS_IPADDRESS()(256234)(256234 enter valid IP address)gtgtgt IS_IPADDRESS()(300234)(300234 enter valid IP address)gtgtgt IS_IPADDRESS(minip=19216810 maxip=1921681255)(1921681100)(1921681100 None)gtgtgt IS_IPADDRESS(minip=1235 maxip=1239 error_message=Bad ip)(123rarr˓4)(1234 bad ip)gtgtgt IS_IPADDRESS(maxip=1234 invert=True)(127001)(127001 None)gtgtgt IS_IPADDRESS(maxip=19216814 invert=True)(19216814)(19216814 enter valid IP address)gtgtgt IS_IPADDRESS(is_localhost=True)(127001)(127001 None)gtgtgt IS_IPADDRESS(is_localhost=True)(192168110)(192168110 enter valid IP address)gtgtgt IS_IPADDRESS(is_localhost=False)(127001)(127001 enter valid IP address)gtgtgt IS_IPADDRESS(maxip=100000 is_localhost=True)(127001)(127001 enter valid IP address)

gtgtgt IS_IPADDRESS()(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPADDRESS(is_ipv4=False)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPADDRESS()(fe80126c8ffafe22b3af )(fe80126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_ipv4=True)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_ipv6=True)(19216811)(19216811 enter valid IP address)gtgtgt IS_IPADDRESS(is_ipv6=True error_message=Bad ip)(19216811)(19216811 bad ip)gtgtgt IS_IPADDRESS(is_link_local=True)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPADDRESS(is_link_local=False)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_link_local=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_multicast=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_multicast=True)(ff00126c8ffafe22b3af)(ff00126c8ffafe22b3af None)gtgtgt IS_IPADDRESS(is_routeable=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af None)gtgtgt IS_IPADDRESS(is_routeable=True)(ff00126c8ffafe22b3af)(ff00126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(subnets=200132)(20018ffafe22b3af)(20018ffafe22b3af None)gtgtgt IS_IPADDRESS(subnets=fb008)(20018ffafe22b3af)(20018ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(subnets=[fc008200132])(20018ffafe22b3af)(20018ffafe22b3af None)gtgtgt IS_IPADDRESS(subnets=invalidsubnet)(20018ffafe22b3af)(20018ffafe22b3af invalid subnet provided)

371 Validators 161

web2py Documentation Release 2146-stable

class gluonvalidatorsIS_LENGTH(maxsize=255 minsize=0 error_message=rsquoEnter from(min)g to (max)g charactersrsquo)

Bases gluonvalidatorsValidator

Checks if length of fieldrsquos value fits between given boundaries Works for both text and file inputs

Parameters

bull maxsize ndash maximum allowed length size

bull minsize ndash minimum allowed length size

Examples

Check if text string is shorter than 33 characters

INPUT(_type=text _name=name requires=IS_LENGTH(32))

Check if password string is longer than 5 characters

INPUT(_type=password _name=name requires=IS_LENGTH(minsize=6))

Check if uploaded file has size between 1KB and 1MB

INPUT(_type=file _name=name requires=IS_LENGTH(1048576 1024))

Other examples

gtgtgt IS_LENGTH()()( None)gtgtgt IS_LENGTH()(1234567890)(1234567890 None)gtgtgt IS_LENGTH(maxsize=5 minsize=0)(1234567890) too long(1234567890 enter from 0 to 5 characters)gtgtgt IS_LENGTH(maxsize=50 minsize=20)(1234567890) too short(1234567890 enter from 20 to 50 characters)

class gluonvalidatorsIS_LIST_OF(other=None minimum=0 maximum=100 er-ror_message=None)

Bases gluonvalidatorsValidator

class gluonvalidatorsIS_LOWERBases gluonvalidatorsValidator

Converts to lower case

gtgtgt IS_LOWER()(ABC)(abc None)gtgtgt IS_LOWER()(Ntilde)(xc3xb1 None)

class gluonvalidatorsIS_MATCH(expression error_message=rsquoInvalid expressionrsquo strict=Falsesearch=False extract=False is_unicode=False)

Bases gluonvalidatorsValidator

Example

Used as

162 Chapter 37 validators Module

web2py Documentation Release 2146-stable

INPUT(_type=text _name=name requires=IS_MATCH(+))

The argument of IS_MATCH is a regular expression

gtgtgt IS_MATCH(+)(hello)(hello None)

gtgtgt IS_MATCH(hell)(hello)(hello None)

gtgtgt IS_MATCH(hell strict=False)(hello)(hello None)

gtgtgt IS_MATCH(hello)(shello)(shello invalid expression)

gtgtgt IS_MATCH(hello search=True)(shello)(shello None)

gtgtgt IS_MATCH(hello search=True strict=False)(shellox)(shellox None)

gtgtgt IS_MATCH(hello search=True strict=False)(shellox)(shellox None)

gtgtgt IS_MATCH(+)()( invalid expression)

class gluonvalidatorsIS_EQUAL_TO(expression error_message=rsquoNo matchrsquo)Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=password)INPUT(_type=text _name=password2

requires=IS_EQUAL_TO(requestvarspassword))

The argument of IS_EQUAL_TO is a string

gtgtgt IS_EQUAL_TO(aaa)(aaa)(aaa None)

gtgtgt IS_EQUAL_TO(aaa)(aab)(aab no match)

class gluonvalidatorsIS_NOT_EMPTY(error_message=rsquoEnter a valuersquo empty_regex=None)Bases gluonvalidatorsValidator

Example

Used as

371 Validators 163

web2py Documentation Release 2146-stable

INPUT(_type=text _name=name requires=IS_NOT_EMPTY())

gtgtgt IS_NOT_EMPTY()(1)(1 None)gtgtgt IS_NOT_EMPTY()(0)(0 None)gtgtgt IS_NOT_EMPTY()(x)(x None)gtgtgt IS_NOT_EMPTY()( x )(x None)gtgtgt IS_NOT_EMPTY()(None)(None enter a value)gtgtgt IS_NOT_EMPTY()()( enter a value)gtgtgt IS_NOT_EMPTY()( )( enter a value)gtgtgt IS_NOT_EMPTY()( nt)( enter a value)gtgtgt IS_NOT_EMPTY()([])([] enter a value)gtgtgt IS_NOT_EMPTY(empty_regex=def)(def)( enter a value)gtgtgt IS_NOT_EMPTY(empty_regex=de[fg])(deg)( enter a value)gtgtgt IS_NOT_EMPTY(empty_regex=def)(abc)(abc None)

class gluonvalidatorsIS_NOT_IN_DB(dbset field error_message=rsquoValue already indatabase or emptyrsquo allowed_override=[] ig-nore_common_filters=False)

Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=name requires=IS_NOT_IN_DB(db dbtable))

makes the field unique

set_self_id(id)

gluonvalidatorsIS_NULL_ORalias of gluonvalidatorsIS_EMPTY_OR

class gluonvalidatorsIS_SLUG(maxlen=80 check=False error_message=rsquoMust be slugrsquokeep_underscores=False)

Bases gluonvalidatorsValidator

converts arbitrary text string to a slug

gtgtgt IS_SLUG()(abc123)(abc123 None)gtgtgt IS_SLUG()(ABC123)(abc123 None)gtgtgt IS_SLUG()(abc-123)(abc-123 None)

(continues on next page)

164 Chapter 37 validators Module

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_SLUG()(abc--123)(abc-123 None)gtgtgt IS_SLUG()(abc 123)(abc-123 None)gtgtgt IS_SLUG()(abc _123)(abc-123 None)gtgtgt IS_SLUG()(-abc-)(abc None)gtgtgt IS_SLUG()(--a--b--_ -c--)(a-b-c None)gtgtgt IS_SLUG()(abcampamp123)(abc123 None)gtgtgt IS_SLUG()(abcampamp123ampampdef)(abc123def None)gtgtgt IS_SLUG()(ntilde)(n None)gtgtgt IS_SLUG(maxlen=4)(abc123)(abc1 None)gtgtgt IS_SLUG()(abc_123)(abc-123 None)gtgtgt IS_SLUG(keep_underscores=False)(abc_123)(abc-123 None)gtgtgt IS_SLUG(keep_underscores=True)(abc_123)(abc_123 None)gtgtgt IS_SLUG(check=False)(abc)(abc None)gtgtgt IS_SLUG(check=True)(abc)(abc None)gtgtgt IS_SLUG(check=False)(a bc)(a-bc None)gtgtgt IS_SLUG(check=True)(a bc)(a bc must be slug)

static urlify(value maxlen=80 keep_underscores=False)

class gluonvalidatorsIS_STRONG(min=None max=None upper=None lower=Nonenumber=None entropy=None special=Nonespecials=rsquo~$^amp()_+-=ltgt []|rsquo invalid=rsquorsquo error_message=None es=False)

Bases object

Examples

Use as

INPUT(_type=password _name=passwdrequires=IS_STRONG(min=10 special=2 upper=2))

enforces complexity requirements on a field

gtgtgt IS_STRONG(es=True)(Abcd1234)(Abcd1234Must include at least 1 of the following ~$^amp()_+-=ltgt[]|)gtgtgt IS_STRONG(es=True)(Abcd1234)(Abcd1234 None)

(continues on next page)

371 Validators 165

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_STRONG(es=True entropy=1)(a)(a None)gtgtgt IS_STRONG(es=True entropy=1 min=2)(a)(a Minimum length is 2)gtgtgt IS_STRONG(es=True entropy=100)(abc123)(abc123 Entropy (3235) less than required (100))gtgtgt IS_STRONG(es=True entropy=100)(and)(and Entropy (1457) less than required (100))gtgtgt IS_STRONG(es=True entropy=100)(aaa)(aaa Entropy (1442) less than required (100))gtgtgt IS_STRONG(es=True entropy=100)(a1d)(a1d Entropy (1597) less than required (100))gtgtgt IS_STRONG(es=True entropy=100)(antilded)(axc3xb1d Entropy (1813) less than required (100))

class gluonvalidatorsIS_TIME(error_message=rsquoEnter time as hhmmss (seconds am pm op-tional)rsquo)

Bases gluonvalidatorsValidator

Example

Use as

INPUT(_type=text _name=name requires=IS_TIME())

understands the following formats hhmmss [ampm] hhmm [ampm] hh [ampm]

[ampm] is optional lsquorsquo can be replaced by any other non-space non-digit

gtgtgt IS_TIME()(2130)(datetimetime(21 30) None)gtgtgt IS_TIME()(21-30)(datetimetime(21 30) None)gtgtgt IS_TIME()(2130)(datetimetime(21 30) None)gtgtgt IS_TIME()(213059)(datetimetime(21 30 59) None)gtgtgt IS_TIME()(530)(datetimetime(5 30) None)gtgtgt IS_TIME()(530 am)(datetimetime(5 30) None)gtgtgt IS_TIME()(530 pm)(datetimetime(17 30) None)gtgtgt IS_TIME()(530 whatever)(530 whatever enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()(530 20)(530 20 enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()(2430)(2430 enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()(2160)(2160 enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()(2130)(2130 enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()()( enter time as hhmmss (seconds am pm optional))ugrave

166 Chapter 37 validators Module

web2py Documentation Release 2146-stable

class gluonvalidatorsIS_UPLOAD_FILENAME(filename=None extension=None lastdot=Truecase=1 error_message=rsquoEnter valid filenamersquo)

Bases gluonvalidatorsValidator

Checks if name and extension of file uploaded through file input matches given criteria

Does not ensure the file type in any way Returns validation failure if no data was uploaded

Parameters

bull filename ndash filename (before dot) regex

bull extension ndash extension (after dot) regex

bull lastdot ndash which dot should be used as a filename extension separator True means lastdot eg filepng -gt file png False means first dot eg filetargz -gt file targz

bull case ndash 0 - keep the case 1 - transform the string into lowercase (default) 2 - transform thestring into uppercase

If there is no dot present extension checks will be done against empty string and filename checks against wholevalue

Examples

Check if file has a pdf extension (case insensitive)

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_UPLOAD_FILENAME(extension=rsquopdfrsquo))

Check if file has a targz extension and name starting with backup

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_UPLOAD_FILENAME(filename=rsquobackuprsquo exten-sion=rsquotargzrsquo lastdot=False))

Check if file has no extension and name matching README (case sensitive)

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_UPLOAD_FILENAME(filename=rsquo^README$rsquoextension=rsquo^$rsquo case=0)

class gluonvalidatorsIS_UPPERBases gluonvalidatorsValidator

Converts to upper case

gtgtgt IS_UPPER()(abc)(ABC None)gtgtgt IS_UPPER()(ntilde)(xc3x91 None)

class gluonvalidatorsIS_URL(error_message=rsquoEnter a valid URLrsquo mode=rsquohttprsquo al-lowed_schemes=None prepend_scheme=rsquohttprsquo al-lowed_tlds=None)

Bases gluonvalidatorsValidator

Rejects a URL string if any of the following is true

bull The string is empty or None

bull The string uses characters that are not allowed in a URL

bull The string breaks any of the HTTP syntactic rules

bull The URL scheme specified (if one is specified) is not lsquohttprsquo or lsquohttpsrsquo

371 Validators 167

web2py Documentation Release 2146-stable

bull The top-level domain (if a host name is specified) does not exist

(These rules are based on RFC 2616 httpwwwfaqsorgrfcsrfc2616html)

This function only checks the URLrsquos syntax It does not check that the URL points to a real document forexample or that it otherwise makes sense semantically This function does automatically prepend lsquohttprsquo infront of a URL in the case of an abbreviated URL (eg lsquogooglecarsquo)

If the parameter mode=rsquogenericrsquo is used then this functionrsquos behavior changes It then rejects a URL string ifany of the following is true

bull The string is empty or None

bull The string uses characters that are not allowed in a URL

bull The URL scheme specified (if one is specified) is not valid

(These rules are based on RFC 2396 httpwwwfaqsorgrfcsrfc2396html)

The list of allowed schemes is customizable with the allowed_schemes parameter If you exclude None fromthe list then abbreviated URLs (lacking a scheme such as lsquohttprsquo) will be rejected

The default prepended scheme is customizable with the prepend_scheme parameter If you set prepend_schemeto None then prepending will be disabled URLs that require prepending to parse will still be accepted but thereturn value will not be modified

IS_URL is compatible with the Internationalized Domain Name (IDN) standard specified in RFC 3490 (httptoolsietforghtmlrfc3490) As a result URLs can be regular strings or unicode strings If the URLrsquos domaincomponent (eg googleca) contains non-US-ASCII letters then the domain will be converted into Punycode(defined in RFC 3492 httptoolsietforghtmlrfc3492) IS_URL goes a bit beyond the standards and allowsnon-US-ASCII characters to be present in the path and query components of the URL as well These non-US-ASCII characters will be escaped using the standard lsquo20rsquo type syntax eg the unicode character with hexcode 0x4e86 will become lsquo4e86rsquo

Parameters

bull error_message ndash a string the error message to give the end user if the URL does notvalidate

bull allowed_schemes ndash a list containing strings or None Each element is a scheme theinputed URL is allowed to use

bull prepend_scheme ndash a string this scheme is prepended if itrsquos necessary to make the URLvalid

Code Examples

INPUT(_type=text _name=name requires=IS_URL())gtgtgt IS_URL()(abccom)(httpabccom None)

INPUT(_type=text _name=name requires=IS_URL(mode=generic))gtgtgt IS_URL(mode=generic)(abccom)(abccom None)

INPUT(_type=text _name=namerequires=IS_URL(allowed_schemes=[https] prepend_scheme=https))

gtgtgt IS_URL(allowed_schemes=[https] prepend_scheme=https)(httpsabccom)(httpsabccom None)

INPUT(_type=text _name=namerequires=IS_URL(prepend_scheme=https))

(continues on next page)

168 Chapter 37 validators Module

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_URL(prepend_scheme=https)(abccom)(httpsabccom None)

INPUT(_type=text _name=namerequires=IS_URL(mode=generic allowed_schemes=[ftps https]

prepend_scheme=https))gtgtgt IS_URL(mode=generic allowed_schemes=[ftps https] prepend_scheme=rarr˓https)(httpsabccom)(httpsabccom None)gtgtgt IS_URL(mode=generic allowed_schemes=[ftps https None] prepend_rarr˓scheme=https)(abccom)(abccom None)

author Jonathan Benn

class gluonvalidatorsIS_JSON(error_message=rsquoInvalid jsonrsquo native_json=False)Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=namerequires=IS_JSON(error_message=This is not a valid json input)

gtgtgt IS_JSON()(a 100)(ua 100 None)

gtgtgt IS_JSON()(spam1234)(spam1234 invalid json)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

371 Validators 169

web2py Documentation Release 2146-stable

170 Chapter 37 validators Module

CHAPTER 38

widget Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

381 The widget is called from web2py

class gluonwidgetIOBases object

write(data)

gluonwidgetcheck_existent_app(options appname)

gluonwidgetconsole()Defines the behavior of the console web2py execution

gluonwidgetget_code_for_scheduler(app options)

gluonwidgetget_url(host path=rsquorsquo proto=rsquohttprsquo port=80)

gluonwidgetrun_system_tests(options)Runs unittests for gluontests

gluonwidgetstart(cron=True)Starts server

gluonwidgetstart_browser(url startup=False)

gluonwidgetstart_schedulers(options)

class gluonwidgetweb2pyDialog(root options)Bases object

Main window dialog

171

web2py Documentation Release 2146-stable

checkTaskBar()Checks taskbar status

connect_pages()Connects pages

error(message)Shows error message

quit(justHide=False)Finishes the program execution

server_ready()

start()Starts web2py server

start_schedulers(app)

stop()Stops web2py server

try_start_scheduler(app)

try_stop_scheduler(app)

update(text)Updates app text

update_canvas()Updates canvas

update_schedulers(start=False)

172 Chapter 38 widget Module

CHAPTER 39

xmlrpc Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

gluonxmlrpchandler(request response methods)

173

web2py Documentation Release 2146-stable

174 Chapter 39 xmlrpc Module

CHAPTER 40

Indices and tables

bull genindex

bull modindex

bull search

175

web2py Documentation Release 2146-stable

176 Chapter 40 Indices and tables

Python Module Index

ggluonadmin 3gluoncache 7gluoncfs 9gluoncompileapp 11gluoncontenttype 15gluoncustom_import 17gluondal 19gluondebug 21gluondecoder 23gluonfileutils 25gluonglobals 27gluonhighlight 33gluonhtml 35gluonhttp 51gluonlanguages 53gluonmain 57gluonmessageboxhandler 59gluonmyregex 61gluonnewcron 63gluonportalocker 65gluonrecfile 67gluonrestricted 69gluonrewrite 71gluonsanitizer 75gluonscheduler 77gluonserializers 83gluonsettings 85gluonshell 87gluonsql 89gluonsqlhtml 97gluonstorage 107gluonstreamer 111gluontemplate 113gluontools 117gluonutf8 139gluonutils 143gluonvalidators 145gluonwidget 171

gluonxmlrpc 173

177

web2py Documentation Release 2146-stable

178 Python Module Index

Index

AA (class in gluonhtml) 35absolute_path_link() (in module gluonnewcron) 63abspath() (in module gluonfileutils) 25accepts() (gluonhtmlFORM method) 41accepts() (gluonsqlhtmlSQLFORM method) 101accessible_query() (gluontoolsAuth method) 121acf() (gluonrewriteMapUrlOut method) 72acquire() (gluonnewcronToken method) 63action() (gluoncacheCache method) 7add_button() (gluonhtmlFORM method) 41add_class() (in module gluonsqlhtml) 104add_deps() (gluonschedulerJobGraph method) 77add_group() (gluontoolsAuth method) 121add_membership() (gluontoolsAuth method) 121add_path_first() (in module gluonadmin) 3add_permission() (gluontoolsAuth method) 122adj_hibernation() (gluonschedulerScheduler method)

79AES_new() (in module gluonutils) 143allows_jwt() (gluontoolsAuth method) 122amfrpc() (gluontoolsService method) 131amfrpc3() (gluontoolsService method) 131ANY_OF (class in gluonvalidators) 145apath() (in module gluonadmin) 3API_SERVER (gluontoolsRecaptcha attribute) 129API_SSL_SERVER (gluontoolsRecaptcha attribute)

129API_URI (gluontoolsRecaptcha2 attribute) 130app_cleanup() (in module gluonadmin) 3app_compile() (in module gluonadmin) 3app_create() (in module gluonadmin) 4app_install() (in module gluonadmin) 4app_pack() (in module gluonadmin) 4app_pack_compiled() (in module gluonadmin) 4app_uninstall() (in module gluonadmin) 4append() (gluonhtmlDIV method) 37append() (gluontemplateBlockNode method) 113append() (gluontemplateContent method) 114

appfactory() (in module gluonmain) 58apply_filter() (gluonlanguagestranslator method) 53archive() (gluontoolsAuth static method) 122archive() (gluontoolsCrud static method) 130arg0 (gluonrewriteMapUrlIn attribute) 71as_dict() (gluonhtmlFORM method) 41as_dict() (gluonsqlDAL method) 92as_dict() (gluonsqlDALField method) 91as_dict() (gluonsqlDALRow method) 91as_dict() (gluonsqlDALTable method) 92as_dict() (gluonsqlField method) 96as_json() (gluonhtmlFORM method) 41as_json() (gluonsqlDALRow method) 91as_xml() (gluonhtmlFORM method) 41as_xml() (gluonsqlDALRow method) 91as_yaml() (gluonhtmlFORM method) 41assert_status() (gluonhtmlFORM method) 41assert_status() (gluonsqlhtmlSQLFORM method) 101assign_tasks() (gluonschedulerScheduler method) 79ASSIGNJS() (in module gluonhtml) 35async() (gluonschedulerMetaScheduler method) 77Auth (class in gluontools) 121AutocompleteWidget (class in gluonsqlhtml) 97autoDetectXMLEncoding() (in module gluondecoder)

23autokey (gluoncacheCache attribute) 8automatic (gluonvalidatorsIS_IPV4 attribute) 158automenu() (gluontoolsWiki method) 135AUTOTYPES (gluonsqlhtmlSQLFORM attribute) 101

BB (class in gluonhtml) 36basic() (gluontoolsAuth method) 122BEAUTIFY (class in gluonhtml) 36being_a_ticker() (gluonschedulerScheduler method) 79BlockNode (class in gluontemplate) 113BODY (class in gluonhtml) 36body (gluonglobalsRequest attribute) 28BooleanWidget (class in gluonsqlhtml) 97BR (class in gluonhtml) 36

179

web2py Documentation Release 2146-stable

build_acf() (gluonrewriteMapUrlOut method) 72build_environment() (in module gluoncompileapp) 12build_query() (gluonsqlhtmlSQLFORM static method)

101build_set() (gluonvalidatorsIS_IN_DB method) 154bulk_insert() (gluonsqlDALTable method) 92bulk_register() (gluontoolsAuth method) 123BUTTON (class in gluonhtml) 36

CCache (class in gluoncache) 7CacheRepresenter (class in gluonsqlhtml) 97callback() (gluonsqlhtmlAutocompleteWidget method)

97can_edit() (gluontoolsWiki method) 135can_join() (gluonsqlDAL method) 92can_manage() (gluontoolsWiki method) 135can_read() (gluontoolsWiki method) 135can_search() (gluontoolsWiki method) 135can_see_menu() (gluontoolsWiki method) 135capitalize() (gluonutf8Utf8 method) 139cas_login() (gluontoolsAuth method) 123cas_validate() (gluontoolsAuth method) 123cast_keys() (in module gluonserializers) 83CAT (class in gluonhtml) 36CENTER (class in gluonhtml) 36center() (gluonutf8Utf8 method) 139change_password() (gluontoolsAuth method) 123check_credentials() (in module gluonfileutils) 26check_existent_app() (in module gluonwidget) 171check_interaction() (in module gluondebug) 22check_new_version() (in module gluonadmin) 4check_reserved_keyword() (gluonsqlDAL method) 92CheckboxesWidget (class in gluonsqlhtml) 97checkTaskBar() (gluonwidgetweb2pyDialog method)

171cleanpath() (in module gluonfileutils) 25CLEANUP (class in gluonvalidators) 145clear() (gluonglobalsSession method) 30clear_content() (gluontemplateContent method) 114clear_interaction() (gluondebugWebDebugger method)

21clear_session_cookies() (gluonglobalsSession method)

30clone() (gluonsqlDALField method) 91clone() (gluonsqlField method) 96close() (gluonportalockerLockedFile method) 65close() (gluonsqlDAL method) 92cloud() (gluontoolsWiki method) 135CODE (class in gluonhtml) 36COL (class in gluonhtml) 37COLGROUP (class in gluonhtml) 37commit() (gluonsqlDAL method) 92communicate() (in module gluondebug) 22

compare() (in module gluonutils) 143compile2() (in module gluonrestricted) 69compile_application() (in module gluoncompileapp) 12compile_controllers() (in module gluoncompileapp) 12compile_models() (in module gluoncompileapp) 12compile_regex() (in module gluonrewrite) 72compile_views() (in module gluoncompileapp) 12component() (gluontoolsWiki static method) 135compute_uuid() (gluonglobalsRequest method) 28confirm() (gluonhtmlFORM static method) 41confirm_registration() (gluontoolsAuth method) 123connect() (gluonglobalsSession method) 30connect_pages() (gluonwidgetweb2pyDialog method)

172console() (in module gluonwidget) 171Content (class in gluontemplate) 114content_type (gluonsqlhtmlExportClass attribute) 98content_type (gluonsqlhtmlExporterCSV attribute) 98content_type (gluonsqlhtmlExporterCSV_hidden

attribute) 98content_type (gluonsqlhtmlExporterHTML attribute)

98content_type (gluonsqlhtmlExporterJSON attribute) 98content_type (gluonsqlhtmlExporterTSV attribute) 99content_type (gluonsqlhtmlExporterXML attribute) 99contenttype() (in module gluoncontenttype) 15cookies2headers() (gluonhttpHTTP method) 51count() (gluonsqlDALField method) 91count() (gluonsqlField method) 96count() (gluonutf8Utf8 method) 139create() (gluontoolsCrud method) 130create() (gluontoolsWiki method) 135create_missing_app_folders() (in module gluonadmin) 5create_missing_folders() (in module gluonadmin) 5createform() (gluonsqlhtmlSQLFORM method) 102crondance() (in module gluonnewcron) 63cronlauncher (class in gluonnewcron) 63Crud (class in gluontools) 130CRYPT (class in gluonvalidators) 146csv() (gluontoolsService method) 132csv() (in module gluonserializers) 83custom_import_install() (in module

gluoncustom_import) 17custom_importer() (in module gluoncustom_import) 17custom_json() (in module gluonserializers) 83CustomImportException 17

DDAL (class in gluonsql) 89DALField (class in gluonsql) 91DALRow (class in gluonsql) 91DALTable (class in gluonsql) 92DatetimeWidget (class in gluonsqlhtml) 98DateWidget (class in gluonsqlhtml) 98

180 Index

web2py Documentation Release 2146-stable

DecimalWidget (class in gluonsqlhtml) 98decode() (gluonutf8Utf8 method) 139decoder() (in module gluondecoder) 23default_delimiters (gluontemplateTemplateParser

attribute) 115default_messages (gluontoolsAuth attribute) 123default_settings (gluontoolsAuth attribute) 124DEFAULT_WIDTH (gluonsqlhtmlUploadWidget

attribute) 104define_signature() (gluontoolsAuth method) 125define_table() (gluonsqlDAL method) 93define_tables() (gluonschedulerScheduler method) 79define_tables() (gluontoolsAuth method) 125del_group() (gluontoolsAuth method) 125del_membership() (gluontoolsAuth method) 125del_permission() (gluontoolsAuth method) 125delete() (gluontoolsCrud method) 130DELETE_FILE (gluonsqlhtmlUploadWidget attribute)

104dictform() (gluonsqlhtmlSQLFORM static method) 102die() (gluonschedulerMetaScheduler method) 78die() (in module gluonshell) 87disable() (gluonschedulerScheduler method) 79distributed_transaction_begin() (gluonsqlDAL static

method) 93distributed_transaction_commit() (gluonsqlDAL static

method) 93DIV (class in gluonhtml) 37do_continue() (gluondebugWebDebugger method) 21do_exec() (gluondebugWebDebugger method) 21do_next() (gluondebugWebDebugger method) 21do_quit() (gluondebugWebDebugger method) 21do_return() (gluondebugWebDebugger method) 21do_step() (gluondebugWebDebugger method) 21DoubleWidget (class in gluonsqlhtml) 98download() (gluonglobalsResponse method) 28drop() (gluonsqlDALTable method) 92DummyResponse (class in gluontemplate) 114

Eedit() (gluontoolsWiki method) 135editmedia() (gluontoolsWiki method) 135element() (gluonhtmlDIV method) 38elements() (gluonhtmlDIV method) 38elements() (gluonhtmlXML method) 49EM (class in gluonhtml) 40email_registration() (gluontoolsAuth method) 125email_reset_password() (gluontoolsAuth method) 125EMBED (class in gluonhtml) 40embed64() (in module gluonhtml) 50emit() (gluonmessageboxhandlerMessageBoxHandler

method) 59emit() (gluonmessageboxhandlerNotifySendHandler

method) 59

enable_autocomplete_and_history() (in modulegluonshell) 87

enable_record_versioning() (gluontoolsAuth method)125

encode() (gluonutf8Utf8 method) 140endswith() (gluonutf8Utf8 method) 140env() (in module gluonshell) 87error() (gluontoolsService method) 132error() (gluonwidgetweb2pyDialog method) 172everybody (gluontoolsWiki attribute) 135exception() (gluondebugWebDebugger method) 21exec_environment() (in module gluonshell) 87exec_pythonrc() (in module gluonshell) 87execute_from_command_line() (in module gluonshell)

87executesql() (gluonsqlDAL method) 93executor() (in module gluonscheduler) 82exists() (in module gluonrecfile) 67expandtabs() (gluonutf8Utf8 method) 140export() (gluonsqlhtmlExportClass method) 98export() (gluonsqlhtmlExporterCSV method) 98export() (gluonsqlhtmlExporterCSV_hidden method)

98export() (gluonsqlhtmlExporterHTML method) 98export() (gluonsqlhtmlExporterJSON method) 98export() (gluonsqlhtmlExporterTSV method) 99export() (gluonsqlhtmlExporterXML method) 99export_to_csv_file() (gluonsqlDAL method) 93ExportClass (class in gluonsqlhtml) 98ExporterCSV (class in gluonsqlhtml) 98ExporterCSV_hidden (class in gluonsqlhtml) 98ExporterHTML (class in gluonsqlhtml) 98ExporterJSON (class in gluonsqlhtml) 98ExporterTSV (class in gluonsqlhtml) 99ExporterXML (class in gluonsqlhtml) 99extcron (class in gluonnewcron) 63extend() (gluontemplateBlockNode method) 113extend() (gluontemplateContent method) 114extend() (gluontemplateTemplateParser method) 115

Ffactory() (gluonsqlhtmlSQLFORM static method) 102fast_urandom16() (in module gluonutils) 143fetch() (in module gluontools) 137Field (class in gluonsql) 95FIELDKEY_DELETE_RECORD

(gluonsqlhtmlSQLFORM attribute) 101FIELDNAME_REQUEST_DELETE

(gluonsqlhtmlSQLFORM attribute) 101fields (gluonsqlDALTable attribute) 92FIELDSET (class in gluonhtml) 40file_ext (gluonsqlhtmlExportClass attribute) 98file_ext (gluonsqlhtmlExporterCSV attribute) 98

Index 181

web2py Documentation Release 2146-stable

file_ext (gluonsqlhtmlExporterCSV_hidden attribute)98

file_ext (gluonsqlhtmlExporterHTML attribute) 98file_ext (gluonsqlhtmlExporterJSON attribute) 98file_ext (gluonsqlhtmlExporterTSV attribute) 99file_ext (gluonsqlhtmlExporterXML attribute) 99filter_err() (in module gluonrewrite) 72filter_url() (in module gluonrewrite) 72find() (gluonutf8Utf8 method) 140find_exposed_functions() (in module gluoncompileapp)

12findT() (in module gluonlanguages) 55first_paragraph() (gluontoolsWiki method) 135fix_hostname() (gluontoolsWiki method) 135fix_newlines() (in module gluonfileutils) 26fixup_missing_path_info() (in module gluonrewrite) 72flatten() (gluonhtmlDIV method) 39flatten() (gluonhtmlMARKMIN method) 44flatten() (gluonhtmlXML method) 49flush() (gluondebugPipe method) 21force() (gluonlanguagestranslator method) 53forget() (gluonglobalsSession method) 30FORM (class in gluonhtml) 40form_factory() (in module gluonsqlhtml) 104format() (gluonutf8Utf8 method) 140formatter() (gluonsqlDALField method) 91formatter() (gluonsqlField method) 96formatter() (gluonvalidatorsANY_OF method) 145formatter() (gluonvalidatorsIS_DATE method) 148formatter() (gluonvalidatorsIS_DATETIME method)

149formatter() (gluonvalidatorsIS_DECIMAL_IN_RANGE

method) 150formatter() (gluonvalidatorsIS_EMPTY_OR method)

152formatter() (gluonvalidatorsIS_FLOAT_IN_RANGE

method) 153formatter() (gluonvalidatorsIS_JSON method) 169formatter() (gluonvalidatorsIS_LIST_OF_EMAILS

method) 152formstyle_bootstrap() (in module gluonsqlhtml) 105formstyle_bootstrap3_inline_factory() (in module

gluonsqlhtml) 105formstyle_bootstrap3_stacked() (in module

gluonsqlhtml) 105formstyle_divs() (in module gluonsqlhtml) 105formstyle_inline() (in module gluonsqlhtml) 105formstyle_table2cols() (in module gluonsqlhtml) 105formstyle_table3cols() (in module gluonsqlhtml) 105formstyle_ul() (in module gluonsqlhtml) 105formstyles (gluonsqlhtmlSQLFORM attribute) 102FormWidget (class in gluonsqlhtml) 99frameset (gluonhtmlHTML attribute) 43frameset (gluonhtmlXHTML attribute) 49

Ggenerate() (in module gluonrecfile) 67GENERIC_DESCRIPTION

(gluonsqlhtmlUploadWidget attribute)104

geocode() (in module gluontools) 137get() (gluonhtmlDIV method) 39get() (gluonsqlDALRow method) 91get_callable_argspec() (in module gluonutils) 143get_code_for_scheduler() (in module gluonwidget) 171get_digest() (in module gluonutils) 143get_effective_router() (in module gluonrewrite) 72get_format() (gluontoolsCrud method) 130get_instances() (gluonsqlDAL static method) 93get_or_create_key() (gluontoolsAuth static method)

125get_or_create_user() (gluontoolsAuth method) 125get_parsed() (in module gluontemplate) 115get_possible_languages() (gluonlanguagestranslator

method) 54get_possible_languages_info()

(gluonlanguagestranslator method) 54get_query() (gluontoolsCrud method) 130get_renderer() (gluontoolsWiki method) 135get_session() (in module gluonfileutils) 26get_t() (gluonlanguagestranslator method) 54get_url() (in module gluonwidget) 171get_usage() (in module gluonshell) 87get_vars (gluonglobalsRequest attribute) 28get_vars_next() (gluontoolsAuth method) 126get_workers() (gluonschedulerScheduler method) 79getcfs() (in module gluoncfs) 9getfirst() (gluonstorageStorage method) 108getipaddrinfo() (in module gluonutils) 143getlast() (gluonstorageStorage method) 108getlist() (gluonstorageStorage method) 108give_up() (gluonschedulerMetaScheduler method) 78gluonadmin (module) 3gluoncache (module) 7gluoncfs (module) 9gluoncompileapp (module) 11gluoncontenttype (module) 15gluoncustom_import (module) 17gluondal (module) 19gluondebug (module) 21gluondecoder (module) 23gluonfileutils (module) 25gluonglobals (module) 27gluonhighlight (module) 33gluonhtml (module) 35gluonhttp (module) 51gluonlanguages (module) 53gluonmain (module) 57gluonmessageboxhandler (module) 59

182 Index

web2py Documentation Release 2146-stable

gluonmyregex (module) 61gluonnewcron (module) 63gluonportalocker (module) 65gluonrecfile (module) 67gluonrestricted (module) 69gluonrewrite (module) 71gluonsanitizer (module) 75gluonscheduler (module) 77gluonserializers (module) 83gluonsettings (module) 85gluonshell (module) 87gluonsql (module) 89gluonsqlhtml (module) 97gluonstorage (module) 107gluonstreamer (module) 111gluontemplate (module) 113gluontools (module) 117gluonutf8 (module) 139gluonutils (module) 143gluonvalidators (module) 145gluonwidget (module) 171gluonxmlrpc (module) 173grid() (gluonsqlhtmlSQLFORM static method) 102groups() (gluontoolsAuth method) 126

HH1 (class in gluonhtml) 42H2 (class in gluonhtml) 42H3 (class in gluonhtml) 42H4 (class in gluonhtml) 42H5 (class in gluonhtml) 42H6 (class in gluonhtml) 42handler() (in module gluonxmlrpc) 173hardcron (class in gluonnewcron) 64harg0 (gluonrewriteMapUrlIn attribute) 71has_membership() (gluontoolsAuth method) 126has_options() (gluonsqlhtmlOptionsWidget static

method) 100has_permission() (gluontoolsAuth method) 126has_permission() (gluontoolsCrud method) 130has_representer() (gluonsqlDAL method) 94HEAD (class in gluonhtml) 42here() (gluontoolsAuth method) 126hidden_fields() (gluonhtmlFORM method) 41highlight() (in module gluonhighlight) 33HR (class in gluonhtml) 42HTML (class in gluonhtml) 42html5 (gluonhtmlHTML attribute) 43html_render() (gluontoolsWiki method) 135HTTP 51HttpServer (class in gluonmain) 58

II (class in gluonhtml) 43

ics() (in module gluonserializers) 83ID_DELETE_SUFFIX (gluonsqlhtmlUploadWidget at-

tribute) 104id_group() (gluontoolsAuth method) 126ID_LABEL_SUFFIX (gluonsqlhtmlSQLFORM at-

tribute) 101ID_ROW_SUFFIX (gluonsqlhtmlSQLFORM attribute)

101IFRAME (class in gluonhtml) 43IMG (class in gluonhtml) 43impersonate() (gluontoolsAuth method) 126import_from_csv_file() (gluonsqlDAL method) 94import_from_csv_file() (gluonsqlDALTable method)

92import_table_definitions() (gluonsqlDAL method) 94include() (gluontemplateTemplateParser method) 115include_files() (gluonglobalsResponse method) 28include_meta() (gluonglobalsResponse method) 28index() (gluonutf8Utf8 method) 140initialize_urandom() (in module gluonutils) 143INPUT (class in gluonhtml) 43insert() (gluonhtmlDIV method) 40insert() (gluonsqlDALTable method) 92insert() (gluontemplateContent method) 114instances (gluontoolsPluginManager attribute) 137IntegerWidget (class in gluonsqlhtml) 99interaction() (gluondebugWebDebugger method) 22invalid_url() (in module gluonrewrite) 72IO (class in gluonwidget) 171IS_ALPHANUMERIC (class in gluonvalidators) 147IS_DATE (class in gluonvalidators) 148IS_DATE_IN_RANGE (class in gluonvalidators) 147IS_DATETIME (class in gluonvalidators) 148IS_DATETIME_IN_RANGE (class in gluonvalidators)

148IS_DECIMAL_IN_RANGE (class in gluonvalidators)

149IS_EMAIL (class in gluonvalidators) 150IS_EMPTY_OR (class in gluonvalidators) 152IS_EQUAL_TO (class in gluonvalidators) 163is_expired() (gluonglobalsSession method) 30IS_EXPR (class in gluonvalidators) 152IS_FLOAT_IN_RANGE (class in gluonvalidators) 153IS_IMAGE (class in gluonvalidators) 153is_image() (gluonsqlhtmlUploadWidget static method)

104is_impersonating() (gluontoolsAuth method) 126IS_IN_DB (class in gluonvalidators) 154IS_IN_SET (class in gluonvalidators) 154IS_INT_IN_RANGE (class in gluonvalidators) 155IS_IPADDRESS (class in gluonvalidators) 159IS_IPV4 (class in gluonvalidators) 156IS_IPV6 (class in gluonvalidators) 158IS_JSON (class in gluonvalidators) 169

Index 183

web2py Documentation Release 2146-stable

IS_LENGTH (class in gluonvalidators) 161IS_LIST_OF (class in gluonvalidators) 162IS_LIST_OF_EMAILS (class in gluonvalidators) 152is_logged_in() (gluontoolsAuth method) 126is_loopback_ip_address() (in module gluonutils) 144IS_LOWER (class in gluonvalidators) 162IS_MATCH (class in gluonvalidators) 162is_new() (gluonglobalsSession method) 30IS_NOT_EMPTY (class in gluonvalidators) 163IS_NOT_IN_DB (class in gluonvalidators) 164IS_NULL_OR (in module gluonvalidators) 164IS_SLUG (class in gluonvalidators) 164IS_STRONG (class in gluonvalidators) 165IS_TIME (class in gluonvalidators) 166is_tracking_changes() (in module gluoncustom_import)

17IS_UPLOAD_FILENAME (class in gluonvalidators)

166IS_UPPER (class in gluonvalidators) 167IS_URL (class in gluonvalidators) 167is_valid_ip_address() (in module gluonutils) 144isalnum() (gluonutf8Utf8 method) 140isalpha() (gluonutf8Utf8 method) 140isdigit() (gluonutf8Utf8 method) 140islower() (gluonutf8Utf8 method) 140isodatetime (gluonvalidatorsIS_DATETIME attribute)

149isspace() (gluonutf8Utf8 method) 140istitle() (gluonutf8Utf8 method) 140isupper() (gluonutf8Utf8 method) 140

JJobGraph (class in gluonscheduler) 77join() (gluonutf8Utf8 method) 140json() (gluonglobalsResponse method) 28json() (gluontoolsService method) 132json() (in module gluonserializers) 83jsonrpc() (gluontoolsService method) 132jsonrpc2() (gluontoolsService method) 132jsonrpc_errors (gluontoolsService attribute) 133JSONWidget (class in gluonsqlhtml) 99jwt() (gluontoolsAuth method) 126

Kkeys() (gluontoolsPluginManager method) 137kill() (gluonschedulerScheduler method) 79

LLABEL (class in gluonhtml) 44label (gluonsqlhtmlExportClass attribute) 98label (gluonsqlhtmlExporterCSV attribute) 98label (gluonsqlhtmlExporterCSV_hidden attribute) 98label (gluonsqlhtmlExporterHTML attribute) 98label (gluonsqlhtmlExporterJSON attribute) 98

label (gluonsqlhtmlExporterTSV attribute) 99label (gluonsqlhtmlExporterXML attribute) 99launch() (gluonnewcronhardcron method) 64Lazy (gluonsqlDALField attribute) 91Lazy (gluonsqlField attribute) 95lazy_cache() (in module gluoncache) 8lazy_define_table() (gluonsqlDAL method) 94LEGEND (class in gluonhtml) 44LI (class in gluonhtml) 44LINK (class in gluonhtml) 44List (class in gluonstorage) 107listdir() (in module gluonfileutils) 25ListWidget (class in gluonsqlhtml) 99ljust() (gluonutf8Utf8 method) 140load() (gluonrestrictedRestrictedError method) 69load() (gluonrestrictedTicketStorage method) 69LOAD() (in module gluoncompileapp) 11load() (in module gluonrewrite) 72load_routers() (in module gluonrewrite) 73load_storage() (in module gluonstorage) 109LoadFactory (class in gluoncompileapp) 12loads_json() (in module gluonserializers) 83loads_yaml() (in module gluonserializers) 83local_import_aux() (in module gluoncompileapp) 12localhost (gluonvalidatorsIS_IPV4 attribute) 158lock() (in module gluonportalocker) 66LockedFile (class in gluonportalocker) 65log() (gluonrestrictedRestrictedError method) 69log_event() (gluontoolsAuth method) 127log_event() (gluontoolsCrud method) 130log_rewrite() (in module gluonrewrite) 73logger (gluonsqlDAL attribute) 94login() (gluontoolsAuth method) 127login_bare() (gluontoolsAuth method) 127login_user() (gluontoolsAuth method) 127logout() (gluontoolsAuth method) 127logout_bare() (gluontoolsAuth method) 127loop() (gluonschedulerMetaScheduler method) 78loop() (gluonschedulerScheduler method) 79lower() (gluonutf8Utf8 method) 141lstrip() (gluonutf8Utf8 method) 141

MM() (gluonlanguagestranslator method) 53Mail (class in gluontools) 117MailAttachment (class in gluontools) 118main() (in module gluonscheduler) 82make_fake_file_like_object() (in module gluonfileutils)

26manage_tokens() (gluontoolsAuth method) 127map_app() (gluonrewriteMapUrlIn method) 71map_controller() (gluonrewriteMapUrlIn method) 71map_function() (gluonrewriteMapUrlIn method) 71map_language() (gluonrewriteMapUrlIn method) 71

184 Index

web2py Documentation Release 2146-stable

map_prefix() (gluonrewriteMapUrlIn method) 71map_root_static() (gluonrewriteMapUrlIn method) 72map_static() (gluonrewriteMapUrlIn method) 72map_url_in() (in module gluonrewrite) 73map_url_out() (in module gluonrewrite) 73MapUrlIn (class in gluonrewrite) 71MapUrlOut (class in gluonrewrite) 72MARKMIN (class in gluonhtml) 44markmin_base() (gluontoolsWiki method) 135markmin_render() (gluontoolsWiki method) 135maybe_add() (gluonvalidatorsIS_IN_DB method) 154md5_hash() (in module gluonutils) 144media() (gluontoolsWiki method) 135MENU (class in gluonhtml) 44menu() (gluontoolsWiki method) 135message (gluonhttpHTTP attribute) 51MessageBoxHandler (class in

gluonmessageboxhandler) 59Messages (class in gluonstorage) 108META (class in gluonhtml) 45MetaScheduler (class in gluonscheduler) 77Method (gluonsqlDALField attribute) 91Method (gluonsqlField attribute) 95mktree() (in module gluonfileutils) 25model_cmp() (in module gluoncompileapp) 12model_cmp_sep() (in module gluoncompileapp) 12MultipleOptionsWidget (class in gluonsqlhtml) 99mybuiltin (class in gluoncompileapp) 12

Nnavbar() (gluontoolsAuth method) 127nice() (gluonvalidatorsIS_DATETIME static method)

149no_underscore() (gluonhtmlBEAUTIFY static method)

36Node (class in gluontemplate) 114NOESCAPE (class in gluontemplate) 114not_authorized() (gluontoolsAuth method) 127not_authorized() (gluontoolsWiki method) 135NotifySendHandler (class in gluonmessageboxhandler)

59now() (gluonschedulerScheduler method) 79numbers (gluonvalidatorsIS_IPV4 attribute) 158

OOBJECT (class in gluonhtml) 45OL (class in gluonhtml) 44omit_acf() (gluonrewriteMapUrlOut method) 72omit_lang() (gluonrewriteMapUrlOut method) 72on() (gluonsqlDALTable method) 92open() (in module gluonrecfile) 67OPTGROUP (class in gluonhtml) 45OPTION (class in gluonhtml) 45options() (gluonvalidatorsIS_IN_DB method) 154

options() (gluonvalidatorsIS_IN_SET method) 155OptionsWidget (class in gluonsqlhtml) 100output() (gluontemplateBlockNode method) 113output_aux() (in module gluontemplate) 115

PP (class in gluonhtml) 45PACKAGE_PATH_SUFFIX

(gluoncustom_importTrackImporter at-tribute) 17

pad() (in module gluonutils) 144pages() (gluontoolsWiki method) 136params_substitution() (gluonlanguagestranslator

method) 54parse() (gluontemplateTemplateParser method) 115parse_all_vars() (gluonglobalsRequest method) 28parse_as_rest() (gluonsqlDAL method) 94parse_get_vars() (gluonglobalsRequest method) 28parse_path_info() (in module gluonshell) 87parse_post_vars() (gluonglobalsRequest method) 28parse_template() (in module gluontemplate) 115parse_version() (in module gluonfileutils) 25parsecronline() (in module gluonnewcron) 64partition() (gluonutf8Utf8 method) 141PasswordWidget (class in gluonsqlhtml) 100pbkdf2_hex() (in module gluonutils) 144Pipe (class in gluondebug) 21plugin_install() (in module gluonadmin) 5plugin_pack() (in module gluonadmin) 5PluginManager (class in gluontools) 136plural() (gluonlanguagestranslator method) 55pop_arg_if() (gluonrewriteMapUrlIn method) 72pop_task() (gluonschedulerMetaScheduler method) 78pop_task() (gluonschedulerScheduler method) 79post_vars (gluonglobalsRequest attribute) 28PRE (class in gluonhtml) 45prettydate() (in module gluontools) 137preview() (gluontoolsWiki method) 136private (gluonvalidatorsIS_IPV4 attribute) 158process() (gluonhtmlFORM method) 41profile() (gluontoolsAuth method) 127

Qqueue_task() (gluonschedulerScheduler method) 79quit() (gluonwidgetweb2pyDialog method) 172

Rr_multiline (gluontemplateTemplateParser attribute)

115r_tag (gluontemplateTemplateParser attribute) 115RadioWidget (class in gluonsqlhtml) 100random_password() (gluontoolsAuth method) 127rangetolist() (in module gluonnewcron) 64re_block (gluontemplateTemplateParser attribute) 115

Index 185

web2py Documentation Release 2146-stable

re_compile() (in module gluoncompileapp) 12re_pass (gluontemplateTemplateParser attribute) 115re_unblock (gluontemplateTemplateParser attribute)

115read() (gluondebugPipe method) 21read() (gluonportalockerLockedFile method) 66read() (gluontoolsCrud method) 130read() (gluontoolsWiki method) 136read_file() (in module gluonfileutils) 25read_locked() (in module gluonportalocker) 66read_pyc() (in module gluoncompileapp) 12readline() (gluondebugPipe method) 21readline() (gluonportalockerLockedFile method) 66readlines() (gluonportalockerLockedFile method) 66readlines_file() (in module gluonfileutils) 25Recaptcha (class in gluontools) 129Recaptcha2 (class in gluontools) 129recursive_unlink() (in module gluonfileutils) 25redirect() (in module gluonhttp) 51REDIRECT_JS (gluonhtmlFORM attribute) 41regex (gluonvalidatorsIS_EMAIL attribute) 151regex (gluonvalidatorsIS_IPV4 attribute) 158regex_attr (gluonhtmlDIV attribute) 40regex_class (gluonhtmlDIV attribute) 40REGEX_CLEANUP (gluonvalidatorsCLEANUP

attribute) 146regex_filter_in() (in module gluonrewrite) 73regex_filter_out() (in module gluonrewrite) 73regex_id (gluonhtmlDIV attribute) 40regex_proposed_but_failed (gluonvalidatorsIS_EMAIL

attribute) 151regex_select() (in module gluonrewrite) 73regex_tag (gluonhtmlDIV attribute) 40regex_uri() (in module gluonrewrite) 73regex_url_in() (in module gluonrewrite) 73register() (gluontoolsAuth method) 127register_bare() (gluontoolsAuth method) 127reindent() (gluontemplateTemplateParser method) 115release() (gluonnewcronToken method) 63remove() (in module gluonrecfile) 67remove_compiled_application() (in module

gluoncompileapp) 12render() (gluonglobalsResponse method) 28render() (in module gluontemplate) 115render_tags() (gluontoolsWiki method) 136renew() (gluonglobalsSession method) 30replace() (gluonutf8Utf8 method) 141report_task() (gluonschedulerMetaScheduler method)

78report_task() (gluonschedulerScheduler method) 80represent() (gluonsqlDAL method) 94represent() (gluonsqlhtmlUploadWidget class method)

104represent() (in module gluonsqlhtml) 105

represented() (gluonsqlhtmlExportClass method) 98representers (gluonsqlDAL attribute) 94Request (class in gluonglobals) 27request_reset_password() (gluontoolsAuth method) 127requires() (gluontoolsAuth method) 127requires_https() (gluonglobalsRequest method) 28requires_login() (gluontoolsAuth method) 127requires_login_or_token() (gluontoolsAuth method)

127requires_membership() (gluontoolsAuth method) 128requires_permission() (gluontoolsAuth method) 128requires_signature() (gluontoolsAuth method) 128reset_password() (gluontoolsAuth method) 128reset_password_deprecated() (gluontoolsAuth method)

128Response (class in gluonglobals) 28restful() (gluonglobalsRequest method) 28restricted() (in module gluonrestricted) 69RestrictedError 69resume() (gluonschedulerScheduler method) 80retrieve() (gluonsqlDALField method) 91retrieve() (gluonsqlField method) 96retrieve_file_properties() (gluonsqlDALField method)

91retrieve_file_properties() (gluonsqlField method) 96retrieve_password() (gluontoolsAuth method) 128retrieve_username() (gluontoolsAuth method) 128reverse_geocode() (in module gluontools) 137rfind() (gluonutf8Utf8 method) 141rindex() (gluonutf8Utf8 method) 141rjust() (gluonutf8Utf8 method) 141rollback() (gluonsqlDAL method) 94rows() (gluontoolsCrud method) 130rows_page (gluontoolsWiki attribute) 136rpartition() (gluonutf8Utf8 method) 141rsplit() (gluonutf8Utf8 method) 141rss() (gluontoolsService method) 133rss() (in module gluonserializers) 83rstrip() (gluonutf8Utf8 method) 141run() (gluondebugWebDebugger method) 22run() (gluonnewcroncronlauncher method) 63run() (gluonnewcronextcron method) 64run() (gluonnewcronhardcron method) 64run() (gluonnewcronsoftcron method) 64run() (gluonschedulerMetaScheduler method) 78run() (gluontoolsService method) 133run() (in module gluonshell) 88run_controller_in() (in module gluoncompileapp) 13run_login_onaccept() (gluontoolsAuth method) 128run_models_in() (in module gluoncompileapp) 13run_system_tests() (in module gluonwidget) 171run_view_in() (in module gluoncompileapp) 13

186 Index

web2py Documentation Release 2146-stable

Ssafe_encode() (in module gluonserializers) 83safe_float() (in module gluonsqlhtml) 105safe_int() (in module gluonsqlhtml) 105sanitize() (in module gluonsanitizer) 75save_password() (in module gluonmain) 58save_pyc() (in module gluoncompileapp) 13save_session_id_cookie() (gluonglobalsSession

method) 31save_storage() (in module gluonstorage) 109Scheduler (class in gluonscheduler) 78SCRIPT (class in gluonhtml) 45search() (gluontoolsCrud method) 130search() (gluontoolsWiki method) 136search_menu() (gluonsqlhtmlSQLFORM static

method) 102secure() (gluonglobalsSession method) 31secure_dumps() (in module gluonutils) 144secure_loads() (in module gluonutils) 144SELECT (class in gluonhtml) 45select() (gluontoolsCrud method) 131select_host() (gluontoolsAuth method) 128send() (gluontoolsMail method) 119send_heartbeat() (gluonschedulerMetaScheduler

method) 78send_heartbeat() (gluonschedulerScheduler method) 80serialize() (gluonhtmlMENU method) 45serialize_mobile() (gluonhtmlMENU method) 45serializers (gluonsqlDAL attribute) 95serve_amfrpc() (gluontoolsService method) 133serve_csv() (gluontoolsService method) 134serve_json() (gluontoolsService method) 134serve_jsonrpc() (gluontoolsService method) 134serve_jsonrpc2() (gluontoolsService method) 134serve_rss() (gluontoolsService method) 134serve_run() (gluontoolsService method) 134serve_soap() (gluontoolsService method) 134serve_xml() (gluontoolsService method) 134serve_xmlrpc() (gluontoolsService method) 134server_ready() (gluonwidgetweb2pyDialog method)

172Service (class in gluontools) 131ServiceJsonRpcException 131Session (class in gluonglobals) 29set_attributes() (gluonsqlDALField method) 91set_attributes() (gluonsqlField method) 96set_current_languages() (gluonlanguagestranslator

method) 55set_folder() (gluonsqlDAL static method) 95set_requirements() (gluonschedulerScheduler method)

80set_self_id() (gluonvalidatorsIS_EMPTY_OR method)

152set_self_id() (gluonvalidatorsIS_IN_DB method) 154

set_self_id() (gluonvalidatorsIS_NOT_IN_DB method)164

set_trace() (in module gluondebug) 22set_worker_status() (gluonschedulerScheduler method)

80Settings (class in gluonstorage) 108show_if() (in module gluonsqlhtml) 105sibling() (gluonhtmlDIV method) 40siblings() (gluonhtmlDIV method) 40simple_hash() (in module gluonutils) 144sleep() (gluonschedulerMetaScheduler method) 78sleep() (gluonschedulerScheduler method) 80sluggify() (gluonrewriteMapUrlIn method) 72sluggify() (in module gluonrewrite) 73smart_query() (gluonsqlDAL method) 95smartdictform() (gluonsqlhtmlSQLFORM static

method) 102smartgrid() (gluonsqlhtmlSQLFORM static method)

102soap() (gluontoolsService method) 134softcron (class in gluonnewcron) 64SPAN (class in gluonhtml) 46split() (gluonutf8Utf8 method) 141split_emails (gluonvalidatorsIS_LIST_OF_EMAILS at-

tribute) 152splitlines() (gluonutf8Utf8 method) 141SQLFORM (class in gluonsqlhtml) 100sqlsafe (gluonsqlDALField attribute) 91sqlsafe (gluonsqlDALTable attribute) 92sqlsafe (gluonsqlField attribute) 96sqlsafe_alias (gluonsqlDALTable attribute) 92sqlsafe_name (gluonsqlDALField attribute) 91sqlsafe_name (gluonsqlField attribute) 96SQLTABLE (class in gluonsqlhtml) 103start() (gluonmainHttpServer method) 58start() (gluonwidgetweb2pyDialog method) 172start() (in module gluonwidget) 171start_browser() (in module gluonwidget) 171start_heartbeats() (gluonschedulerMetaScheduler

method) 78start_schedulers() (gluonwidgetweb2pyDialog method)

172start_schedulers() (in module gluonwidget) 171startswith() (gluonutf8Utf8 method) 141stop() (gluonmainHttpServer method) 58stop() (gluonwidgetweb2pyDialog method) 172stop_task() (gluonschedulerScheduler method) 80stop_trace() (in module gluondebug) 22stopcron() (in module gluonnewcron) 64Storage (class in gluonstorage) 107StorageList (class in gluonstorage) 109store() (gluonrestrictedTicketStorage method) 69store() (gluonsqlDALField method) 91store() (gluonsqlField method) 96

Index 187

web2py Documentation Release 2146-stable

stream() (gluonglobalsResponse method) 28stream_file_or_304_or_206() (in module

gluonstreamer) 111streamer() (in module gluonstreamer) 111strict (gluonhtmlHTML attribute) 43strict (gluonhtmlXHTML attribute) 49StringWidget (class in gluonsqlhtml) 103strip() (gluonutf8Utf8 method) 141STRONG (class in gluonhtml) 46STYLE (class in gluonhtml) 46style() (gluonsqlhtmlSQLTABLE method) 103SuperNode (class in gluontemplate) 114swapcase() (gluonutf8Utf8 method) 142

TTABLE (class in gluonhtml) 46table_cas() (gluontoolsAuth method) 128table_event() (gluontoolsAuth method) 128table_group() (gluontoolsAuth method) 128table_membership() (gluontoolsAuth method) 128table_permission() (gluontoolsAuth method) 128table_token() (gluontoolsAuth method) 128table_user() (gluontoolsAuth method) 128tables (gluonsqlDAL attribute) 95tables() (gluontoolsCrud method) 131tag (gluonhtmlA attribute) 35tag (gluonhtmlB attribute) 36tag (gluonhtmlBEAUTIFY attribute) 36tag (gluonhtmlBODY attribute) 36tag (gluonhtmlBR attribute) 36tag (gluonhtmlBUTTON attribute) 36tag (gluonhtmlCAT attribute) 36tag (gluonhtmlCENTER attribute) 36tag (gluonhtmlCOL attribute) 37tag (gluonhtmlCOLGROUP attribute) 37tag (gluonhtmlDIV attribute) 40tag (gluonhtmlEM attribute) 40tag (gluonhtmlEMBED attribute) 40tag (gluonhtmlFIELDSET attribute) 40tag (gluonhtmlFORM attribute) 41tag (gluonhtmlH1 attribute) 42tag (gluonhtmlH2 attribute) 42tag (gluonhtmlH3 attribute) 42tag (gluonhtmlH4 attribute) 42tag (gluonhtmlH5 attribute) 42tag (gluonhtmlH6 attribute) 42tag (gluonhtmlHEAD attribute) 42tag (gluonhtmlHR attribute) 42tag (gluonhtmlHTML attribute) 43tag (gluonhtmlI attribute) 43tag (gluonhtmlIFRAME attribute) 43tag (gluonhtmlIMG attribute) 43tag (gluonhtmlINPUT attribute) 44tag (gluonhtmlLABEL attribute) 44

tag (gluonhtmlLEGEND attribute) 44tag (gluonhtmlLI attribute) 44tag (gluonhtmlLINK attribute) 44tag (gluonhtmlMENU attribute) 45tag (gluonhtmlMETA attribute) 45tag (gluonhtmlOBJECT attribute) 45tag (gluonhtmlOL attribute) 44tag (gluonhtmlOPTGROUP attribute) 45tag (gluonhtmlOPTION attribute) 45tag (gluonhtmlP attribute) 45tag (gluonhtmlPRE attribute) 45tag (gluonhtmlSCRIPT attribute) 45tag (gluonhtmlSELECT attribute) 46tag (gluonhtmlSPAN attribute) 46tag (gluonhtmlSTRONG attribute) 46tag (gluonhtmlSTYLE attribute) 46tag (gluonhtmlTABLE attribute) 46tag (gluonhtmlTBODY attribute) 47tag (gluonhtmlTD attribute) 46tag (gluonhtmlTEXTAREA attribute) 46tag (gluonhtmlTFOOT attribute) 47tag (gluonhtmlTH attribute) 47tag (gluonhtmlTHEAD attribute) 47tag (gluonhtmlTITLE attribute) 47tag (gluonhtmlTR attribute) 47tag (gluonhtmlTT attribute) 47tag (gluonhtmlUL attribute) 44tag (gluonhtmlXHTML attribute) 49TAG (in module gluonhtml) 46tar() (in module gluonfileutils) 26tar_compiled() (in module gluonfileutils) 26Task (class in gluonscheduler) 81task_status() (gluonschedulerScheduler method) 81TaskReport (class in gluonscheduler) 82TBODY (class in gluonhtml) 47TD (class in gluonhtml) 46TemplateParser (class in gluontemplate) 114terminate() (gluonschedulerScheduler method) 81terminate_process() (gluonschedulerMetaScheduler

method) 78test() (in module gluoncompileapp) 13test() (in module gluonshell) 88TEXTAREA (class in gluonhtml) 46TextWidget (class in gluonsqlhtml) 103TFOOT (class in gluonhtml) 47TH (class in gluonhtml) 46THEAD (class in gluonhtml) 47THREAD_LOCAL (gluoncustom_importTrackImporter

attribute) 17TicketStorage (class in gluonrestricted) 69TimeWidget (class in gluonsqlhtml) 104TITLE (class in gluonhtml) 47title() (gluonutf8Utf8 method) 142to() (gluonhttpHTTP method) 51

188 Index

web2py Documentation Release 2146-stable

to_string() (gluontemplateTemplateParser method) 115Token (class in gluonnewcron) 63toolbar() (gluonglobalsResponse method) 29total_seconds() (gluonschedulerScheduler static

method) 81TR (class in gluonhtml) 47track_changes() (in module gluoncustom_import) 17TrackImporter (class in gluoncustom_import) 17transitional (gluonhtmlHTML attribute) 43transitional (gluonhtmlXHTML attribute) 49translate() (gluonlanguagestranslator method) 55translate() (gluonutf8Utf8 method) 142translator (class in gluonlanguages) 53truncate() (gluonsqlDALTable method) 92try_redirect_on_error() (in module gluonrewrite) 73try_rewrite_on_error() (in module gluonrewrite) 73try_start_scheduler() (gluonwidgetweb2pyDialog

method) 172try_stop_scheduler() (gluonwidgetweb2pyDialog

method) 172TT (class in gluonhtml) 47TYPE (class in gluonscheduler) 81

UUL (class in gluonhtml) 44unlock() (in module gluonportalocker) 66untar() (in module gluonfileutils) 26unzip() (in module gluonadmin) 5up() (in module gluonfileutils) 25update() (gluonhtmlDIV method) 40update() (gluonsqlDALTable method) 92update() (gluontoolsCrud method) 131update() (gluonwidgetweb2pyDialog method) 172update_all_languages() (in module gluonlanguages) 55update_canvas() (gluonwidgetweb2pyDialog method)

172update_dependencies() (gluonschedulerScheduler

method) 81update_groups() (gluontoolsAuth method) 128update_or_insert() (gluonsqlDALTable method) 92update_request() (gluonrewriteMapUrlIn method) 72update_schedulers() (gluonwidgetweb2pyDialog

method) 172upgrade() (in module gluonadmin) 5UploadWidget (class in gluonsqlhtml) 104upper() (gluonutf8Utf8 method) 142url() (gluontoolsAuth method) 128url() (gluontoolsCrud method) 131URL() (in module gluonhtml) 47url_in() (in module gluonrewrite) 73url_out() (in module gluonrewrite) 73urlify() (gluonvalidatorsIS_SLUG static method) 165user_agent() (gluonglobalsRequest method) 28user_group() (gluontoolsAuth method) 128

user_group_role() (gluontoolsAuth method) 128user_id (gluontoolsAuth attribute) 128Utf8 (class in gluonutf8) 139uuid (gluonglobalsRequest attribute) 28uuid() (gluonsqlDAL method) 95

Vvalidate() (gluonhtmlFORM method) 41validate() (gluonschedulerJobGraph method) 77validate() (gluonsqlDALField method) 91validate() (gluonsqlField method) 96validate_and_insert() (gluonsqlDALTable method) 92validate_and_update() (gluonsqlDALTable method) 92validate_and_update_or_insert() (gluonsqlDALTable

method) 92validate_args() (gluonrewriteMapUrlIn method) 72validators (gluonsqlDAL attribute) 95validators_method() (gluonsqlDAL method) 95vars (gluonglobalsRequest attribute) 28verify_email() (gluontoolsAuth method) 128VERIFY_SERVER (gluontoolsRecaptcha attribute)

129VERIFY_SERVER (gluontoolsRecaptcha2 attribute)

130Virtual (gluonsqlDALField attribute) 91Virtual (gluonsqlField attribute) 96

Ww2p_pack() (in module gluonfileutils) 26w2p_pack_plugin() (in module gluonfileutils) 26w2p_unpack() (in module gluonfileutils) 26w2p_unpack_plugin() (in module gluonfileutils) 26web2py_uuid() (in module gluonutils) 144web2pyDialog (class in gluonwidget) 171WebDebugger (class in gluondebug) 21when_is_logged_in_bypass_next_in_url()

(gluontoolsAuth method) 128where() (gluonsqlDAL method) 95widget() (gluonsqlhtmlBooleanWidget class method)

97widget() (gluonsqlhtmlCheckboxesWidget class

method) 97widget() (gluonsqlhtmlFormWidget class method) 99widget() (gluonsqlhtmlJSONWidget class method) 99widget() (gluonsqlhtmlListWidget class method) 99widget() (gluonsqlhtmlMultipleOptionsWidget class

method) 100widget() (gluonsqlhtmlOptionsWidget class method)

100widget() (gluonsqlhtmlPasswordWidget class method)

100widget() (gluonsqlhtmlRadioWidget class method) 100widget() (gluonsqlhtmlStringWidget class method) 103widget() (gluonsqlhtmlTextWidget class method) 104

Index 189

web2py Documentation Release 2146-stable

widget() (gluonsqlhtmlUploadWidget class method)104

widgets (gluonsqlhtmlSQLFORM attribute) 103Wiki (class in gluontools) 135wiki() (gluontoolsAuth method) 129wikimenu() (gluontoolsAuth method) 129with_alias() (gluonsqlDALTable method) 92with_prefix() (gluoncacheCache static method) 8wrapped_assign_tasks() (gluonschedulerScheduler

method) 81wrapped_pop_task() (gluonschedulerScheduler

method) 81wrapped_report_task() (gluonschedulerScheduler

method) 81write() (gluondebugPipe method) 21write() (gluonglobalsResponse method) 29write() (gluonportalockerLockedFile method) 66write() (gluontemplateDummyResponse method) 114write() (gluonwidgetIO method) 171write_file() (in module gluonfileutils) 25write_locked() (in module gluonportalocker) 66wsgibase() (in module gluonmain) 57

XXHTML (class in gluonhtml) 49XML (class in gluonhtml) 49xml() (gluonhtmlA method) 35xml() (gluonhtmlCODE method) 37xml() (gluonhtmlDIV method) 40xml() (gluonhtmlFORM method) 42xml() (gluonhtmlHTML method) 43xml() (gluonhtmlINPUT method) 44xml() (gluonhtmlMARKMIN method) 44xml() (gluonhtmlMENU method) 45xml() (gluonhtmlP method) 45xml() (gluonhtmlSCRIPT method) 45xml() (gluonhtmlSTYLE method) 46xml() (gluonhtmlXHTML method) 49xml() (gluonhtmlXML method) 50xml() (gluontemplateNOESCAPE method) 114xml() (gluontoolsRecaptcha method) 129xml() (gluontoolsRecaptcha2 method) 130xml() (gluontoolsService method) 134xml() (in module gluonserializers) 83xml_rec() (in module gluonserializers) 83xmlescape() (in module gluonhtml) 50xmlns (gluonhtmlXHTML attribute) 49xmlrpc() (gluonglobalsResponse method) 29xmlrpc() (gluontoolsService method) 134

Yyaml() (in module gluonserializers) 83

Zzfill() (gluonutf8Utf8 method) 142

190 Index

  • admin Module
    • Utility functions for the Admin application
      • cache Module
        • Basic caching classes and methods
          • cfs Module
            • Functions required to execute app components
              • compileapp Module
                • Functions required to execute app components
                  • contenttype Module
                  • custom_import Module
                    • Support for smart import syntax for web2py applications
                      • dal Module
                        • Takes care of adapting pyDAL to web2pyrsquos needs
                          • debug Module
                            • Debugger support classes
                              • decoder Module
                              • fileutils Module
                                • File operations
                                  • globals Module
                                  • highlight Module
                                  • html Module
                                    • Template helpers
                                      • http Module
                                        • HTTP statuses helpers
                                          • languages Module
                                            • Translation system
                                              • main Module
                                                • The gluon wsgi application
                                                  • messageboxhandler Module
                                                  • myregex Module
                                                    • Useful regexes
                                                      • newcron Module
                                                      • portalocker Module
                                                      • recfile Module
                                                        • Generates names for cache and session files
                                                          • restricted Module
                                                            • Restricted environment to execute applicationrsquos code
                                                              • rewrite Module
                                                              • sanitizer Module
                                                                • Cross-site scripting (XSS) defense
                                                                  • scheduler Module
                                                                    • Background processes made simple
                                                                      • serializers Module
                                                                      • settings Module
                                                                      • shell Module
                                                                        • Web2py environment in the shell
                                                                          • sql Module
                                                                            • Just for backward compatibility
                                                                              • sqlhtml Module
                                                                              • storage Module
                                                                              • streamer Module
                                                                                • Facilities to handle file streaming
                                                                                  • template Module
                                                                                    • Templating syntax
                                                                                      • tools Module
                                                                                        • Auth Mail PluginManager and various utilities
                                                                                          • utf8 Module
                                                                                            • Utilities and class for UTF8 strings managing
                                                                                              • utils Module
                                                                                                • This file specifically includes utilities for security
                                                                                                  • validators Module
                                                                                                    • Validators
                                                                                                      • widget Module
                                                                                                        • The widget is called from web2py
                                                                                                          • xmlrpc Module
                                                                                                          • Indices and tables
                                                                                                          • Python Module Index
Page 3: web2py Documentation - Read the Docs

15 languages Module 53151 Translation system 53

16 main Module 57161 The gluon wsgi application 57

17 messageboxhandler Module 59

18 myregex Module 61181 Useful regexes 61

19 newcron Module 63

20 portalocker Module 65

21 recfile Module 67211 Generates names for cache and session files 67

22 restricted Module 69221 Restricted environment to execute applicationrsquos code 69

23 rewrite Module 71

24 sanitizer Module 75241 Cross-site scripting (XSS) defense 75

25 scheduler Module 77251 Background processes made simple 77

26 serializers Module 83

27 settings Module 85

28 shell Module 87281 Web2py environment in the shell 87

29 sql Module 89291 Just for backward compatibility 89

30 sqlhtml Module 97

31 storage Module 107

32 streamer Module 111321 Facilities to handle file streaming 111

33 template Module 113331 Templating syntax 113

34 tools Module 117341 Auth Mail PluginManager and various utilities 117

35 utf8 Module 139351 Utilities and class for UTF8 strings managing 139

36 utils Module 143361 This file specifically includes utilities for security 143

ii

37 validators Module 145371 Validators 145

38 widget Module 171381 The widget is called from web2py 171

39 xmlrpc Module 173

40 Indices and tables 175

Python Module Index 177

iii

iv

web2py Documentation Release 2146-stable

Contents

Contents 1

web2py Documentation Release 2146-stable

2 Contents

CHAPTER 1

admin Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

11 Utility functions for the Admin application

gluonadminadd_path_first(path)

gluonadminapath(path=rdquo r=None)Builds a path inside an application folder

Parameters

bull path (str) ndash path within the application folder

bull r ndash the global request object

gluonadminapp_cleanup(app request)Removes session cache and error files

Parameters

bull app (str) ndash application name

bull request ndash the global request object

Returns True if everything went ok False otherwise

gluonadminapp_compile(app request skip_failed_views=False)Compiles the application

Parameters

bull app (str) ndash application name

bull request ndash the global request object

3

web2py Documentation Release 2146-stable

Returns None if everything went ok traceback text if errors are found

gluonadminapp_create(app request force=False key=None info=False)Create a copy of welcomew2p (scaffolding) app

Parameters

bull app (str) ndash application name

bull request ndash the global request object

gluonadminapp_install(app fobj request filename overwrite=None)Installs an application

bull Identifies file type by filename

bull Writes fobj contents to the deposit folder

bull Calls w2p_unpack() to do the job

Parameters

bull app (str) ndash new application name

bull fobj (obj) ndash file object containing the application to be installed

bull request ndash the global request object

bull filename (str) ndash original filename of the fobj required to determine extension

bull overwrite (bool) ndash force overwrite of existing application

Returns name of the file where app is temporarily stored or None on failure

gluonadminapp_pack(app request raise_ex=False filenames=None)Builds a w2p package for the application

Parameters

bull app (str) ndash application name

bull request ndash the global request object

Returns filename of the w2p file or None on error

gluonadminapp_pack_compiled(app request raise_ex=False)Builds a w2p bytecode-compiled package for the application

Parameters

bull app (str) ndash application name

bull request ndash the global request object

Returns filename of the w2p file or None on error

gluonadminapp_uninstall(app request)Uninstalls the application

Parameters

bull app (str) ndash application name

bull request ndash the global request object

Returns True on success False on failure

4 Chapter 1 admin Module

web2py Documentation Release 2146-stable

gluonadmincheck_new_version(myversion version_url)Compares current web2pyrsquos version with the latest stable web2py version

Parameters

bull myversion ndash the current version as stored in file web2pyVERSION

bull version_URL ndash the URL that contains the version of the latest stable release

Returns

state version

bull state True if upgrade available False if current version is up-to-date -1 on error

bull version the most up-to-version available

Return type tuple

gluonadmincreate_missing_app_folders(request)

gluonadmincreate_missing_folders()

gluonadminplugin_install(app fobj request filename)Installs a plugin

bull Identifies file type by filename

bull Writes fobj contents to the deposit folder

bull Calls w2p_unpack_plugin() to do the job

Parameters

bull app (str) ndash new application name

bull fobj ndash file object containing the application to be installed

bull request ndash the global request object

bull filename ndash original filename of the fobj required to determine extension

Returns name of the file where plugin is temporarily stored or False on failure

gluonadminplugin_pack(app plugin_name request)Builds a w2p package for the plugin

Parameters

bull app (str) ndash application name

bull plugin_name (str) ndash the name of the plugin without plugin_ prefix

bull request ndash the current request app

Returns filename of the w2p file or False on error

gluonadminunzip(filename dir subfolder=rdquo)Unzips filename into dir (zip only no gz etc)

Parameters

bull filename (str) ndash archive

bull dir (str) ndash destination

bull subfolder (str) ndash if = lsquorsquo unzips only files in subfolder

11 Utility functions for the Admin application 5

web2py Documentation Release 2146-stable

gluonadminupgrade(request url=rsquohttpweb2pycomrsquo)Upgrades web2py (src osx win) if a new version is posted It detects whether src osx or win is running anddownloads the right one

Parameters

bull request ndash the current request object (required to determine version and path)

bull url ndash the incomplete url where to locate the latest web2py (actual url isurl+rsquoexamplesstaticweb2py_(src|osx|win)ziprsquo)

Returns tuple completed traceback

bull completed True on success False on failure (network problem or old version)

bull traceback None on success raised exception details on failure

6 Chapter 1 admin Module

CHAPTER 2

cache Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

21 Basic caching classes and methods

bull Cache - The generic caching object interfacing with the others

bull CacheInRam - providing caching in ram

bull CacheOnDisk - provides caches on disk

Memcache is also available via a different module (see gluoncontribmemcache)

When web2py is running on Google App Engine caching will be provided by the GAE memcache (seegluoncontribgae_memcache)

class gluoncacheCache(request)Bases object

Sets up generic caching creating an instance of both CacheInRam and CacheOnDisk In case of GAE will makeuse of gluoncontribgae_memcache

bull selfram is an instance of CacheInRam

bull selfdisk is an instance of CacheOnDisk

action(time_expire=300 cache_model=None prefix=None session=False vars=True lang=Trueuser_agent=False public=True valid_statuses=None quick=None)

Better fit for caching an action

Warning Experimental

7

web2py Documentation Release 2146-stable

Currently only HTTP 11 compliant reference httpcodegooglecompdoctype-mirrorwikiArticleHttpCaching

Parameters

bull time_expire (int) ndash same as cache

bull cache_model (str) ndash same as cache

bull prefix (str) ndash add a prefix to the calculated key

bull session (bool) ndash adds responsesession_id to the key

bull vars (bool) ndash adds requestenvquery_string

bull lang (bool) ndash adds Taccepted_language

bull user_agent (bool or dict) ndash if True adds is_mobile and is_tablet tothe key Pass a dict to use all the needed values (uses str(items())) (eguser_agent=requestuser_agent()) Used only if session is not True

bull public (bool) ndash if False forces the Cache-Control to be lsquoprivatersquo

bull valid_statuses ndash by default only status codes starting with 123 will be cached passan explicit list of statuses on which turn the cache on

bull quick ndash SessionVarsLangUser-agentPublic fast overrides with initials eg lsquoSVLPrsquoor lsquoVLPrsquo or lsquoVLPrsquo

autokey = (name)s(args)s(vars)s

static with_prefix(cache_model prefix)allow replacing cacheram with cachewith_prefix(cacheramrsquoprefixrsquo) it will add prefix to all the cachekeys used

gluoncachelazy_cache(key=None time_expire=None cache_model=rsquoramrsquo)Can be used to cache any function including ones in modules as long as the cached function is only calledwithin a web2py request

If a key is not provided one is generated from the function name time_expire defaults to None (no cacheexpiration)

If cache_model is ldquoramrdquo then the model is currentcacheram etc

8 Chapter 2 cache Module

CHAPTER 3

cfs Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

31 Functions required to execute app components

Note FOR INTERNAL USE ONLY

gluoncfsgetcfs(key filename filter=None)Caches the filtered file filename with key until the file is modified

Parameters

bull key (str) ndash the cache key

bull filename ndash the file to cache

bull filter ndash is the function used for filtering Normally filename is a py file and filter is afunction that bytecode compiles the file In this way the bytecode compiled file is cached(Default = None)

This is used on Google App Engine since pyc files cannot be saved

9

web2py Documentation Release 2146-stable

10 Chapter 3 cfs Module

CHAPTER 4

compileapp Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

41 Functions required to execute app components

Note FOR INTERNAL USE ONLY

gluoncompileappLOAD(c=None f=rsquoindexrsquo args=None vars=None extension=None target=Noneajax=False ajax_trap=False url=None user_signature=False time-out=None times=1 content=rsquoloadingrsquo post_vars= attr)

LOADs a component into the actionrsquos document

Parameters

bull c (str) ndash controller

bull f (str) ndash function

bull args (tuple or list) ndash arguments

bull vars (dict) ndash vars

bull extension (str) ndash extension

bull target (str) ndash id of the target

bull ajax (bool) ndash True to enable AJAX bahaviour

bull ajax_trap (bool) ndash True if ajax is set to True traps both links and forms ldquoinsiderdquo thetarget

bull url (str) ndash overrides clsquoflsquolsquoargslsquo and vars

11

web2py Documentation Release 2146-stable

bull user_signature (bool) ndash adds hmac signature to all links with a key that is differentfor every user

bull timeout (int) ndash in milliseconds specifies the time to wait before starting the request orthe frequency if times is greater than 1 or ldquoinfinityrdquo

bull times (integer or str) ndash how many times the component will be requested ldquoinfin-ityrdquo or ldquocontinuousrdquo are accepted to reload indefinitely the component

class gluoncompileappLoadFactory(environment)Bases object

Attention this helper is new and experimental

gluoncompileappbuild_environment(request response session store_current=True)Build the environment dictionary into which web2py files are executed

gluoncompileappcompile_application(folder skip_failed_views=False)Compiles all models views controller for the application in folder

gluoncompileappcompile_controllers(folder)Compiles all the controllers in the application specified by folder

gluoncompileappcompile_models(folder)Compiles all the models in the application specified by folder

gluoncompileappcompile_views(folder skip_failed_views=False)Compiles all the views in the application specified by folder

gluoncompileappfind_exposed_functions(data)

gluoncompileapplocal_import_aux(name reload_force=False app=rsquowelcomersquo)In apps instead of importing a local module (in applicationsappmodules) with

import abc as d

you should do

d = local_import(abc)

or (to force a reload)

d = local_import(lsquoabcrsquo reload=True)

This prevents conflict between applications and un-necessary execs It can be used to import any moduleincluding regular Python modules

gluoncompileappmodel_cmp(a b sep=rsquorsquo)

gluoncompileappmodel_cmp_sep(a b sep=rsquorsquo)

class gluoncompileappmybuiltinBases object

NOTE could simple use a dict and populate it NOTE not sure if this changes things though if monkey patchingimport

gluoncompileappre_compile(regex)

gluoncompileappread_pyc(filename)Read the code inside a bytecode compiled file if the MAGIC number is compatible

Returns a code object

12 Chapter 4 compileapp Module

web2py Documentation Release 2146-stable

gluoncompileappremove_compiled_application(folder)Deletes the folder compiled containing the compiled application

gluoncompileapprun_controller_in(controller function environment)Runs the controllerfunction() (for the app specified by the current folder) It tries pre-compiled con-troller_functionpyc first before compiling it

gluoncompileapprun_models_in(environment)Runs all models (in the app specified by the current folder) It tries pre-compiled models first before compilingthem

gluoncompileapprun_view_in(environment)Executes the view for the requested action The view is the one specified in responseview or determined by theurl or viewgenericextension It tries the pre-compiled views_controller_functionpyc before compiling it

gluoncompileappsave_pyc(filename)Bytecode compiles the file filename

gluoncompileapptest()Example

gtgtgt import traceback typesgtgtgt environment=x1gtgtgt open(apy w)write(print 1x)gtgtgt save_pyc(apy)gtgtgt osunlink(apy)gtgtgt if type(read_pyc(apyc))==typesCodeType print codecodegtgtgt exec read_pyc(apyc) in environment1

41 Functions required to execute app components 13

web2py Documentation Release 2146-stable

14 Chapter 4 compileapp Module

CHAPTER 5

contenttype Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

CONTENT_TYPE dictionary created against freedesktoporgrsquos shared mime info database version 11

Deviations from official standards

bull md applicationx-genesis-rom ndashgt textx-markdown

bull png imagex-apple-ios-png ndashgt imagepng

Additions

bull load texthtml

bull json applicationjson

bull jsonp applicationjsonp

bull pickle applicationpython-pickle

bull w2prsquo applicationw2p

gluoncontenttypecontenttype(filename default=rsquotextplainrsquo)Returns the Content-Type string matching extension of the given filename

15

web2py Documentation Release 2146-stable

16 Chapter 5 contenttype Module

CHAPTER 6

custom_import Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

61 Support for smart import syntax for web2py applications

exception gluoncustom_importCustomImportExceptionBases exceptionsImportError

class gluoncustom_importTrackImporterBases object

An importer tracking the date of the module files and reloading them when they are changed

PACKAGE_PATH_SUFFIX = __init__py

THREAD_LOCAL = ltthread_local objectgt

gluoncustom_importcustom_import_install()

gluoncustom_importcustom_importer(name globals=None locals=None fromlist=Nonelevel=-1)

web2pyrsquos custom importer It behaves like the standard Python importer but it tries to transform importstatements as something like ldquoimport applicationsapp_namemodulesxrdquo If the import fails it falls back onnaive_importer

gluoncustom_importis_tracking_changes()

gluoncustom_importtrack_changes(track=True)

17

web2py Documentation Release 2146-stable

18 Chapter 6 custom_import Module

CHAPTER 7

dal Module

Go to httppydalreadthedocsorgenlatest for docs on pyDAL

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

71 Takes care of adapting pyDAL to web2pyrsquos needs

19

web2py Documentation Release 2146-stable

20 Chapter 7 dal Module

CHAPTER 8

debug Module

This file is part of the web2py Web FrameworkDeveloped by Massimo Di Pierro ltmdipierrocsdepauledugtlimodou ltlimodougmailcomgt and srackham ltsrackhamgmailcomgtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

81 Debugger support classes

class gluondebugPipe(name mode=rsquorrsquo args kwargs)Bases QueueQueue

flush()

read(count=None timeout=None)

readline()

write(data)

class gluondebugWebDebugger(pipe completekey=rsquotabrsquo stdin=None stdout=None)Bases gluoncontribqdbFrontend

Qdb web2py interface

clear_interaction()

do_continue(args kwargs)

do_exec(statement)

do_next(args kwargs)

do_quit(args kwargs)

do_return(args kwargs)

do_step(args kwargs)

21

web2py Documentation Release 2146-stable

exception(title extype exvalue trace request)Show a user_exception

interaction(filename lineno line context)

run()Main method dispatcher (infinite loop)

gluondebugcheck_interaction(fn)Decorator to clean and prevent interaction when not available

gluondebugcommunicate(command=None)send command to debbuger wait result

gluondebugset_trace()breakpoint shortcut (like pdb)

gluondebugstop_trace()stop waiting for the debugger (called atexit)

22 Chapter 8 debug Module

CHAPTER 9

decoder Module

Caller will hand this library a buffer and ask it to either convert it or auto-detect the type

Based on httpcodeactivestatecomrecipes52257

Licensed under the PSF License

gluondecoderautoDetectXMLEncoding(buffer)buffer -gt encoding_name The buffer should be at least 4 bytes long Returns None if encoding cannot bedetected Note that encoding_name might not have an installed decoder (eg EBCDIC)

gluondecoderdecoder(buffer)

23

web2py Documentation Release 2146-stable

24 Chapter 9 decoder Module

CHAPTER 10

fileutils Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

101 File operations

gluonfileutilsparse_version(version)Attempts to parse SemVer fallbacks on legacy

gluonfileutilsread_file(filename mode=rsquorrsquo)Returns content from filename making sure to close the file explicitly on exit

gluonfileutilswrite_file(filename value mode=rsquowrsquo)Writes ltvaluegt to filename making sure to close the file explicitly on exit

gluonfileutilsreadlines_file(filename mode=rsquorrsquo)Applies split(lsquo lsquo) to the output of read_file()

gluonfileutilsup(path)

gluonfileutilsabspath(relpath base)Converts relative path to absolute path based (by default) on applications_parent

gluonfileutilsmktree(path)

gluonfileutilslistdir(path expression=rsquo^+$rsquo drop=True add_dirs=False sort=Truemaxnum=None exclude_content_from=None)

Like oslistdir() but you can specify a regex pattern to filter files If add_dirs is True the returned items willhave the full path

gluonfileutilsrecursive_unlink(f)Deletes f If itrsquos a folder also its contents will be deleted

gluonfileutilscleanpath(path)Turns any expressionpath into a valid filename replaces with _ and removes special characters

25

web2py Documentation Release 2146-stable

gluonfileutilstar(file dir expression=rsquo^+$rsquo filenames=None exclude_content_from=None)Tars dir into file only tars file that match expression

gluonfileutilsuntar(file dir)Untar file into dir

gluonfileutilstar_compiled(file dir expression=rsquo^+$rsquo exclude_content_from=None)Used to tar a compiled application The content of models views controllers is not stored in the tar file

gluonfileutilsget_session(request other_application=rsquoadminrsquo)Checks that user is authorized to access other_application

gluonfileutilscheck_credentials(request other_application=rsquoadminrsquo expiration=3600gae_login=True)

Checks that user is authorized to access other_application

gluonfileutilsw2p_pack(filename path compiled=False filenames=None)Packs a web2py application

Parameters

bull filename (str) ndash path to the resulting archive

bull path (str) ndash path to the application

bull compiled (bool) ndash if True packs the compiled version

bull filenames (list) ndash adds filenames to the archive

gluonfileutilsw2p_unpack(filename path delete_tar=True)

gluonfileutilsw2p_pack_plugin(filename path plugin_name)Packs the given plugin into a w2p file Will match files at

ltpathgtplugin_[name]ltpathgtplugin_[name]

gluonfileutilsw2p_unpack_plugin(filename path delete_tar=True)

gluonfileutilsfix_newlines(path)

gluonfileutilsmake_fake_file_like_object()

26 Chapter 10 fileutils Module

CHAPTER 11

globals Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

Contains the classes for the global used variables

bull Request

bull Response

bull Session

class gluonglobalsRequest(env)Bases gluonstorageStorage

Defines the request object and the default values of its members

bull env environment variables by gluonmainwsgibase()

bull cookies

bull get_vars

bull post_vars

bull vars

bull folder

bull application

bull function

bull args

bull extension

bull now datetimedatetimenow()

27

web2py Documentation Release 2146-stable

bull utcnow datetimedatetimeutcnow()

bull is_local

bull is_https

bull restful()

body

compute_uuid()

get_varsLazily parses the query string into get_vars

parse_all_vars()Merges get_vars and post_vars to vars

parse_get_vars()Takes the QUERY_STRING and unpacks it to get_vars

parse_post_vars()Takes the body of the request and unpacks it into post_vars applicationjson is also automatically parsed

post_varsLazily parse the body into post_vars

requires_https()If request comes in over HTTP redirects it to HTTPS and secures the session

restful()

user_agent()

uuidLazily uuid

varsLazily parses all get_vars and post_vars to fill vars

class gluonglobalsResponseBases gluonstorageStorage

Defines the response object and the default values of its members responsewrite( ) can be used to write in theoutput html

download(request db chunk_size=65536 attachment=True download_filename=None)Example of usage in controller

def download()return responsedownload(request db)

Downloads from http downloadfilename

include_files(extensions=None)Includes files (usually in the head) Can minify and cache local files By default caches in ram for 5minutes To change responsecache_includes = (cache_method time_expire) Example (cachedisk 60) caches to disk for 1 minute

include_meta()

json(data default=None)

render(a b)

28 Chapter 11 globals Module

web2py Documentation Release 2146-stable

stream(stream chunk_size=65536 request=None attachment=False filename=None)If in a controller function

return responsestream(file 100)

the file content will be streamed at 100 bytes at the time

Parameters

bull stream ndash filename or read()able content

bull chunk_size (int) ndash Buffer size

bull request ndash the request object

bull attachment (bool) ndash prepares the correct headers to download the file as an attach-ment Usually creates a pop-up download window on browsers

bull filename (str) ndash the name for the attachment

Note for using the stream name (filename) with attachments the option must be explicitly set as functionparameter (will default to the last request argument otherwise)

toolbar()

write(data escape=True)

xmlrpc(request methods)assuming

def add(a b)return a+b

if a controller function ldquofuncrdquo

return responsexmlrpc(request [add])

the controller will be able to handle xmlrpc requests for the add function Example

import xmlrpclibconnection = xmlrpclibServerProxy(

httphostnameappcontrfunc)print connectionadd(3 4)

class gluonglobalsSessionBases gluonstorageStorage

Defines the session object and the default values of its members (None)

bull session_storage_type lsquofilersquo lsquodbrsquo or lsquocookiersquo

bull session_cookie_compression_level

bull session_cookie_expires cookie expiration

bull session_cookie_key for encrypted sessions in cookies

bull session_id a number or None if no session

bull session_id_name

bull session_locked

29

web2py Documentation Release 2146-stable

bull session_masterapp

bull session_new a new session obj is being created

bull session_hash hash of the pickled loaded session

bull session_pickled picked session

if session in cookie

bull session_data_name name of the cookie for session data

if session in db

bull session_db_record_id

bull session_db_table

bull session_db_unique_key

if session in file

bull session_file

bull session_filename

clear()rarr None Remove all items from D

clear_session_cookies()

connect(request=None response=None db=None tablename=rsquoweb2py_sessionrsquo master-app=None migrate=True separate=None check_client=False cookie_key=Nonecookie_expires=None compression_level=None)

Used in models allows to customize Session handling

Parameters

bull request ndash the request object

bull response ndash the response object

bull db ndash to storeretrieve sessions in db (a table is created)

bull tablename (str) ndash table name

bull masterapp (str) ndash points to anotherrsquos app sessions This enables a ldquoSSOrdquo environmentamong apps

bull migrate ndash passed to the underlying db

bull separate ndash with True creates a folder with the 2 initials of the session id Can also bea function eg

separate=lambda(session_name) session_name[-2]

bull check_client ndash if True sessions can only come from the same ip

bull cookie_key (str) ndash secret for cookie encryption

bull cookie_expires ndash sets the expiration of the cookie

bull compression_level (int) ndash 0-9 sets zlib compression on the data before the en-cryption

forget(response=None)

is_expired(seconds=3600)

is_new()

30 Chapter 11 globals Module

web2py Documentation Release 2146-stable

renew(clear_session=False)

save_session_id_cookie()

secure()

31

web2py Documentation Release 2146-stable

32 Chapter 11 globals Module

CHAPTER 12

highlight Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

gluonhighlighthighlight(code language link=rsquoexamplesglobalsvarsrsquo counter=1styles=None highlight_line=None context_lines=None at-tributes=None)

33

web2py Documentation Release 2146-stable

34 Chapter 12 highlight Module

CHAPTER 13

html Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

131 Template helpers

class gluonhtmlA(components attributes)Bases gluonhtmlDIV

Generates an A() link A() in web2py is really important and with the included web2pyjs allows lots of Ajaxinteractions in the page

On top of ldquousualrdquo _attributes it takes

Parameters

bull callback ndash an url to call but not redirect to

bull cid ndash if you want to load the _href into an element of the page (component) pass its id(without the ) here

bull delete ndash element to delete after calling callback

bull target ndash same thing as cid

bull confirm ndash text to display upon a callback with a delete

bull noconfirm ndash donrsquot display alert upon a callback with delete

tag = a

xml()generates the xml for this component

gluonhtmlASSIGNJS(kargs)

35

web2py Documentation Release 2146-stable

Example

ASSIGNJS(var1=lsquo1rsquo var2=lsquo2rsquo) will return the following javascript variables assignations

var var1 = ldquo1rdquo var var2 = ldquo2rdquo

Parameters kargs ndash Any keywords arguments and assigned values

Returns Javascript vars assignations for the keyvalue passed

class gluonhtmlB(components attributes)Bases gluonhtmlDIV

tag = b

class gluonhtmlBEAUTIFY(component attributes)Bases gluonhtmlDIV

Turns any list dictionary etc into decent looking html

Two special attributes are

bull sorted a function that takes the dict and returned sorted keys

bull keyfilter a function that takes a key and returns its representation or None if the key is to be skipped Bydefault key[1]==rsquo_rsquo is skipped

Examples

gtgtgt BEAUTIFY([a b hello world])xml()ltdivgtlttablegtlttrgtlttdgtltdivgtaltdivgtlttdgtlttrgtlttrgtlttdgtltdivgtbltdivgtlttdgtlttrgtlttrgtlttdgtrarr˓ltdivgtlttablegtlttrgtlttd style=font-weightboldvertical-aligntopgthellolttdgtlttdrarr˓style=vertical-aligntopgtlttdgtlttdgtltdivgtworldltdivgtlttdgtlttrgtlttablegtltdivgtltrarr˓tdgtlttrgtlttablegtltdivgt

static no_underscore(key)

tag = div

class gluonhtmlBODY(components attributes)Bases gluonhtmlDIV

tag = body

class gluonhtmlBR(components attributes)Bases gluonhtmlDIV

tag = br

class gluonhtmlBUTTON(components attributes)Bases gluonhtmlDIV

tag = button

class gluonhtmlCENTER(components attributes)Bases gluonhtmlDIV

tag = center

class gluonhtmlCAT(components attributes)Bases gluonhtmlDIV

tag =

36 Chapter 13 html Module

web2py Documentation Release 2146-stable

class gluonhtmlCODE(components attributes)Bases gluonhtmlDIV

Displays code in HTML with syntax highlighting

Parameters

bull language ndash indicates the language otherwise PYTHON is assumed

bull link ndash can provide a link

bull styles ndash for styles

Examples

=CODE(ldquoprint lsquohello worldrsquordquo language=rsquopythonrsquo link=None counter=1 styles= high-light_line=None)

supported languages are

ldquopythonrdquo ldquohtml_plainrdquo ldquocrdquo ldquocpprdquo ldquoweb2pyrdquo ldquohtmlrdquo

The ldquohtmlrdquo language interprets and tags as ldquoweb2pyrdquo code ldquohtml_plainrdquo doesnrsquot

if a link=rsquoexamplesglobalvarsrsquo is provided web2py keywords are linked to the online docs

the counter is used for line numbering counter can be None or a prompt string

xml()generates the xml for this component

class gluonhtmlCOL(components attributes)Bases gluonhtmlDIV

tag = col

class gluonhtmlCOLGROUP(components attributes)Bases gluonhtmlDIV

tag = colgroup

class gluonhtmlDIV(components attributes)Bases gluonhtmlXmlComponent

HTML helper for easy generating and manipulating a DOM structure Little or no validation is done

Behaves like a dictionary regarding updating of attributes Behaves like a list regarding insertingappendingcomponents

Examples

gtgtgt DIV(hello world _style=colorred)xml()ltdiv style=colorredgthelloworldltdivgt

All other HTML helpers are derived from DIV

_something=rdquovaluerdquo attributes are transparently translated into something=rdquovaluerdquo HTML attributes

append(value)list style appending of components

Examples

131 Template helpers 37

web2py Documentation Release 2146-stable

gtgtgt a=DIV()gtgtgt aappend(SPAN(x))gtgtgt print altdivgtltspangtxltspangtltdivgt

element(args kargs)Finds the first component that matches the supplied attribute dictionary or None if nothing could be found

Also the components of the components are searched

elements(args kargs)Find all components that match the supplied attribute dictionary or None if nothing could be found

All components of the components are searched

Examples

gtgtgt a = DIV(DIV(SPAN(x)3DIV(SPAN(y))))gtgtgt for c in aelements(span first_only=True) c[0]=zgtgtgt print altdivgtltdivgtltspangtzltspangt3ltdivgtltspangtyltspangtltdivgtltdivgtltdivgtgtgtgt for c in aelements(span) c[0]=zgtgtgt print altdivgtltdivgtltspangtzltspangt3ltdivgtltspangtzltspangtltdivgtltdivgtltdivgt

It also supports a syntax compatible with jQuery

Examples

gtgtgt a=TAG(ltdivgtltspangtlta id=1-1 uv=$gthelloltagtltspangtltp class=this is ararr˓testgtworldltpgtltdivgt)gtgtgt for e in aelements(div a1-1 pis) print eflatten()helloworldgtgtgt for e in aelements(1-1) print eflatten()hellogtgtgt aelements(a[uv=$])[0]xml()lta id=1-1 uv=$gthelloltagtgtgtgt a=FORM( INPUT(_type=text) SELECT(range(1)) TEXTAREA() )gtgtgt for c in aelements(input select textarea) c[_disabled] = disabledrarr˓gtgtgt axml()ltform action= enctype=multipartform-data method=postgtltinput disabled=rarr˓disabled type=text gtltselect disabled=disabledgtltoption value=0gt0ltrarr˓optiongtltselectgtlttextarea cols=40 disabled=disabled rows=10gtltrarr˓textareagtltformgt

Elements that are matched can also be replaced or removed by specifying a ldquoreplacerdquo argument (note alist of the original matching elements is still returned as usual)

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=abc) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(spanabc replace=P(x _class=xyz))gtgtgt print a We should xml() here instead of printltdivgtltdivgtltp class=xyzgtxltpgtltdivgtltp class=xyzgtxltpgtltp class=xyzgtxltpgtltrarr˓divgtltdivgtltdivgt

38 Chapter 13 html Module

web2py Documentation Release 2146-stable

ldquoreplacerdquo can be a callable which will be passed the original element and should return a new element toreplace it

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=abc) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(spanabc replace=lambda el P(el[0] _class=xyz))gtgtgt print altdivgtltdivgtltp class=xyzgtxltpgtltdivgtltp class=xyzgtyltpgtltp class=xyzgtzltpgtltrarr˓divgtltdivgtltdivgt

If replace=None matching elements will be removed completely

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=abc) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(span find=y replace=None)gtgtgt print altdivgtltdivgtltspan class=abcgtxltspangtltdivgtltspan class=abcgtzltspangtltdivgtltrarr˓divgtltdivgt

If a ldquofind_textrdquo argument is specified elements will be searched for text components that match find_textand any matching text components will be replaced (find_text is ignored if ldquoreplacerdquo is not also specified)Like the ldquofindrdquo argument ldquofind_textrdquo can be a string or a compiled regex

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=abc) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(find_text=recompile(x|y|z) replace=hello)gtgtgt print altdivgtltdivgtltspan class=abcgthelloltspangtltdivgtltspan class=abcgthelloltspangtrarr˓ltspan class=abcgthelloltspangtltdivgtltdivgtltdivgt

If other attributes are specified along with find_text then only components that match the specified at-tributes will be searched for find_text

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=efg) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(spanefg find_text=recompile(x|y|z) replace=hello)gtgtgt print altdivgtltdivgtltspan class=abcgtxltspangtltdivgtltspan class=efggthelloltspangtltspanrarr˓class=abcgtzltspangtltdivgtltdivgtltdivgt

flatten(render=None)Returns the text stored by the DIV object rendered by the render function the render function must taketext tagname and attributes render=None is equivalent to render=lambda text tag attr text

Examples

gtgtgt markdown = lambda text tag=None attributes=rarr˓None resub(s+ text) h1+text+nnrarr˓ ptext+nget(tagtext)gtgtgt a=TAG(lth1gtHeaderlth1gtltpgtthis is a testltpgt)gtgtgt aflatten(markdown)Headernnthis is a testn

131 Template helpers 39

web2py Documentation Release 2146-stable

get(i)

insert(i value)List-style inserting of components

Examples

gtgtgt a=DIV()gtgtgt ainsert(0 SPAN(x))gtgtgt print altdivgtltspangtxltspangtltdivgt

regex_attr = lt_sreSRE_Pattern objectgt

regex_class = lt_sreSRE_Pattern objectgt

regex_id = lt_sreSRE_Pattern objectgt

regex_tag = lt_sreSRE_Pattern objectgt

sibling(args kargs)Finds the first sibling component that match the supplied argument list and attribute dictionary or None ifnothing could be found

siblings(args kargs)Finds all sibling components that match the supplied argument list and attribute dictionary or None ifnothing could be found

tag = div

update(kargs)dictionary like updating of the tag attributes

xml()generates the xml for this component

class gluonhtmlEM(components attributes)Bases gluonhtmlDIV

tag = em

class gluonhtmlEMBED(components attributes)Bases gluonhtmlDIV

tag = embed

class gluonhtmlFIELDSET(components attributes)Bases gluonhtmlDIV

tag = fieldset

class gluonhtmlFORM(components attributes)Bases gluonhtmlDIV

Examples

gtgtgt from validators import IS_NOT_EMPTYgtgtgt form=FORM(INPUT(_name=test requires=IS_NOT_EMPTY()))gtgtgt formxml()ltform action= enctype=multipartform-data method=postgtltinput name=testrarr˓type=text gtltformgt

a FORM is container for INPUT TEXTAREA SELECT and other helpers

form has one important method

40 Chapter 13 html Module

web2py Documentation Release 2146-stable

formaccepts(requestvars session)

if form is accepted (and all validators pass) formvars contains the accepted vars otherwise formerrors containsthe errors in case of errors the form is modified to present the errors to the user

REDIRECT_JS = windowlocation=sreturn false

accepts(request_vars session=None formname=rsquodefaultrsquo keepvalues=False onvalidation=Nonehideerror=False kwargs)

kwargs is not used but allows to specify the same interface for FORM and SQLFORM

add_button(value url _class=None)

as_dict(flat=False sanitize=True)EXPERIMENTAL

Sanitize is naive It should catch any unsafe value for client retrieval

as_json(sanitize=True)

as_xml(sanitize=True)

as_yaml(sanitize=True)

assert_status(status request_vars)

static confirm(text=rsquoOKrsquo buttons=None hidden=None)

hidden_fields()

process(kwargs)Perform the validate() method but returns the form

Usage in controllers

directly on returndef action()

some code herereturn dict(form=FORM()process())

You can use it with FORM SQLFORM or FORM based plugins

responseflash messagesdef action()

form = SQLFORM(dbtable)process(message_onsuccess=Sucess)return dict(form=form)

callback function callback receives True or False as first arg and a list of argsdef my_callback(status msg)

responseflash = Success +msg if status else Errors occured

after argument can be flash to responseflash messages or a function name to use as callback or None to do nothingdef action()

return dict(form=SQLFORM(dbtable)process(onsuccess=my_callback)

tag = form

validate(kwargs)This function validates the form you can use it instead of directly formaccepts

Usage In controller

131 Template helpers 41

web2py Documentation Release 2146-stable

def action()form=FORM(INPUT(_name=test requires=IS_NOT_EMPTY()))formvalidate() you can pass some args here - see belowreturn dict(form=form)

This can receive a bunch of arguments

onsuccess = lsquoflashrsquo - will show message_onsuccess in responseflash None - will do nothing can be afunction (lambda form pass)

onfailure = lsquoflashrsquo - will show message_onfailure in responseflash None - will do nothing can be afunction (lambda form pass)

onchange = lsquoflashrsquo - will show message_onchange in responseflash None - will do nothing can be afunction (lambda form pass)

message_onsuccess message_onfailure message_onchange next = where to redirect in case of success anyother kwargs will be passed for formaccepts( )

xml()generates the xml for this component

class gluonhtmlH1(components attributes)Bases gluonhtmlDIV

tag = h1

class gluonhtmlH2(components attributes)Bases gluonhtmlDIV

tag = h2

class gluonhtmlH3(components attributes)Bases gluonhtmlDIV

tag = h3

class gluonhtmlH4(components attributes)Bases gluonhtmlDIV

tag = h4

class gluonhtmlH5(components attributes)Bases gluonhtmlDIV

tag = h5

class gluonhtmlH6(components attributes)Bases gluonhtmlDIV

tag = h6

class gluonhtmlHEAD(components attributes)Bases gluonhtmlDIV

tag = head

class gluonhtmlHR(components attributes)Bases gluonhtmlDIV

tag = hr

class gluonhtmlHTML(components attributes)Bases gluonhtmlDIV

42 Chapter 13 html Module

web2py Documentation Release 2146-stable

There are four predefined document type definitions They can be specified in the lsquodoctypersquo parameter

bull lsquostrictrsquo enables strict doctype

bull lsquotransitionalrsquo enables transitional doctype (default)

bull lsquoframesetrsquo enables frameset doctype

bull lsquohtml5rsquo enables HTML 5 doctype

bull any other string will be treated as userrsquos own doctype

lsquolangrsquo parameter specifies the language of the document Defaults to lsquoenrsquo

See also DIV

frameset = ltDOCTYPE HTML PUBLIC -W3CDTD HTML 401 FramesetEN httpwwww3orgTRhtml4framesetdtdgtn

html5 = ltDOCTYPE HTMLgtn

strict = ltDOCTYPE HTML PUBLIC -W3CDTD HTML 401EN httpwwww3orgTRhtml4strictdtdgtn

tag = html

transitional = ltDOCTYPE HTML PUBLIC -W3CDTD HTML 401 TransitionalEN httpwwww3orgTRhtml4loosedtdgtn

xml()generates the xml for this component

class gluonhtmlI(components attributes)Bases gluonhtmlDIV

tag = i

class gluonhtmlIFRAME(components attributes)Bases gluonhtmlDIV

tag = iframe

class gluonhtmlIMG(components attributes)Bases gluonhtmlDIV

tag = img

class gluonhtmlINPUT(components attributes)Bases gluonhtmlDIV

INPUT Component

Takes two special attributes value= and requires=

Parameters

bull value ndash used to pass the initial value for the input field value differs from _value becauseit works for checkboxes radio textarea and selectoption too For a checkbox value shouldbe lsquorsquo or lsquoonrsquo For a radio or selectoption value should be the _value of the checkedselecteditem

bull requires ndash should be None or a validator or a list of validators for the value of the field

Examples

gtgtgt INPUT(_type=text _name=name value=Max)xml()ltinput name=name type=text value=Max gt

gtgtgt INPUT(_type=checkbox _name=checkbox value=on)xml()ltinput checked=checked name=checkbox type=checkbox value=on gt

131 Template helpers 43

web2py Documentation Release 2146-stable

gtgtgt INPUT(_type=radio _name=radio _value=yes value=yes)xml()ltinput checked=checked name=radio type=radio value=yes gt

gtgtgt INPUT(_type=radio _name=radio _value=no value=yes)xml()ltinput name=radio type=radio value=no gt

tag = input

xml()generates the xml for this component

class gluonhtmlLABEL(components attributes)Bases gluonhtmlDIV

tag = label

class gluonhtmlLEGEND(components attributes)Bases gluonhtmlDIV

tag = legend

class gluonhtmlLI(components attributes)Bases gluonhtmlDIV

tag = li

class gluonhtmlLINK(components attributes)Bases gluonhtmlDIV

tag = link

class gluonhtmlOL(components attributes)Bases gluonhtmlUL

tag = ol

class gluonhtmlUL(components attributes)Bases gluonhtmlDIV

UL Component

If subcomponents are not LI-components they will be wrapped in a LI

tag = ul

class gluonhtmlMARKMIN(text extra=None allowed=None sep=rsquoprsquo url=None environ-ment=None latex=rsquogooglersquo autolinks=rsquodefaultrsquo protolinks=rsquodefaultrsquoclass_prefix=rdquo id_prefix=rsquomarkmin_rsquo kwargs)

Bases gluonhtmlXmlComponent

For documentation httpweb2pycomexamplesstaticmarkminhtml

flatten()

xml()

class gluonhtmlMENU(data args)Bases gluonhtmlDIV

Used to build menus

Parameters

bull _class ndash defaults to lsquoweb2py-menu web2py-menu-verticalrsquo

bull ul_class ndash defaults to lsquoweb2py-menu-verticalrsquo

44 Chapter 13 html Module

web2py Documentation Release 2146-stable

bull li_class ndash defaults to lsquoweb2py-menu-expandrsquo

bull li_first ndash defaults to lsquoweb2py-menu-firstrsquo

bull li_last ndash defaults to lsquoweb2py-menu-lastrsquo

Use like

menu = MENU([[name False URL() [submenu]] ])=menu

serialize(data level=0)

serialize_mobile(data select=None prefix=rdquo)

tag = ul

xml()generates the xml for this component

class gluonhtmlMETA(components attributes)Bases gluonhtmlDIV

tag = meta

class gluonhtmlOBJECT(components attributes)Bases gluonhtmlDIV

tag = object

class gluonhtmlOPTION(components attributes)Bases gluonhtmlDIV

tag = option

class gluonhtmlP(components attributes)Bases gluonhtmlDIV

Will replace n by ltbr gt if the cr2br attribute is provided

see also DIV

tag = p

xml()generates the xml for this component

class gluonhtmlPRE(components attributes)Bases gluonhtmlDIV

tag = pre

class gluonhtmlSCRIPT(components attributes)Bases gluonhtmlDIV

tag = script

xml()generates the xml for this component

class gluonhtmlOPTGROUP(components attributes)Bases gluonhtmlDIV

tag = optgroup

131 Template helpers 45

web2py Documentation Release 2146-stable

class gluonhtmlSELECT(components attributes)Bases gluonhtmlINPUT

Examples

gtgtgt from validators import IS_IN_SETgtgtgt SELECT(yes no _name=selector value=yes requires=IS_IN_SET([yes no]))xml()ltselect name=selectorgtltoption selected=selected value=yesgtyesltoptiongtrarr˓ltoption value=nogtnoltoptiongtltselectgt

tag = select

class gluonhtmlSPAN(components attributes)Bases gluonhtmlDIV

tag = span

class gluonhtmlSTRONG(components attributes)Bases gluonhtmlDIV

tag = strong

class gluonhtmlSTYLE(components attributes)Bases gluonhtmlDIV

tag = style

xml()generates the xml for this component

class gluonhtmlTABLE(components attributes)Bases gluonhtmlDIV

TABLE Component

If subcomponents are not TRTBODYTHEADTFOOT-components they will be wrapped in a TR

tag = table

gluonhtmlTAGTAG factory

Examples

gtgtgt print TAGfirst(TAGsecond(test) _key = 3)ltfirst key=3gtltsecondgttestltsecondgtltfirstgt

class gluonhtmlTD(components attributes)Bases gluonhtmlDIV

tag = td

class gluonhtmlTEXTAREA(components attributes)Bases gluonhtmlINPUT

Examples

TEXTAREA(_name=sometext value=blah 100 requires=IS_NOT_EMPTY())

lsquoblah blah blah rsquo will be the content of the textarea field

tag = textarea

46 Chapter 13 html Module

web2py Documentation Release 2146-stable

class gluonhtmlTH(components attributes)Bases gluonhtmlDIV

tag = th

class gluonhtmlTHEAD(components attributes)Bases gluonhtmlDIV

tag = thead

class gluonhtmlTBODY(components attributes)Bases gluonhtmlDIV

tag = tbody

class gluonhtmlTFOOT(components attributes)Bases gluonhtmlDIV

tag = tfoot

class gluonhtmlTITLE(components attributes)Bases gluonhtmlDIV

tag = title

class gluonhtmlTR(components attributes)Bases gluonhtmlDIV

TR Component

If subcomponents are not TDTH-components they will be wrapped in a TD

tag = tr

class gluonhtmlTT(components attributes)Bases gluonhtmlDIV

tag = tt

gluonhtmlURL(a=None c=None f=None r=None args=None vars=None an-chor=rdquo extension=None env=None hmac_key=None hash_vars=Truesalt=None user_signature=None scheme=None host=None port=None en-code_embedded_slash=False url_encode=True language=None)

generates a url lsquoacfrsquo corresponding to application a controller c and function f If r=request is passed a c fare set respectively to rapplication rcontroller rfunction

The more typical usage is

URL(lsquoindexrsquo)

that generates a url for the index function within the present application and controller

Parameters

bull a ndash application (default to current if r is given)

bull c ndash controller (default to current if r is given)

bull f ndash function (default to current if r is given)

bull r ndash request (optional)

bull args ndash any arguments (optional) Additional ldquopathrdquo elements

bull vars ndash any variables (optional) Querystring elements

bull anchor ndash anchorname without (optional)

131 Template helpers 47

web2py Documentation Release 2146-stable

bull extension ndash force an extension

bull hmac_key ndash key to use when generating hmac signature (optional)

bull hash_vars ndash which of the vars to include in our hmac signature True (default) - hash allvars False - hash none of the vars iterable - hash only the included vars [lsquokey1rsquorsquokey2rsquo]

bull salt ndash salt hashing with this string

bull user_signature ndash signs automatically the URL in such way that only the user canaccess the URL (use with URLverify or authrequires_signature())

bull scheme ndash URI scheme (True lsquohttprsquo or lsquohttpsrsquo etc) forces absolute URL (optional)

bull host ndash string to force absolute URL with host (True means http_host)

bull port ndash optional port number (forces absolute URL)

bull encode_embedded_slash ndash encode slash characters included in args

bull url_encode ndash encode characters included in vars

Raises SyntaxError ndash when no application controller or function is available or when a CRLFis found in the generated url

Examples

gtgtgt str(URL(a=a c=c f=f args=[x y z] vars=p1 q2 anchor=1))acfxyzp=1ampq=21

gtgtgt str(URL(a=a c=c f=f args=[x y z] vars=p(13) q2 anchor=1))acfxyzp=1ampp=3ampq=21

gtgtgt str(URL(a=a c=c f=f args=[x y z] vars=p(31) q2 anchor=1))acfxyzp=3ampp=1ampq=21

gtgtgt str(URL(a=a c=c f=f anchor=1+2))acf12B2

gtgtgt str(URL(a=a c=c f=f args=[x y z] vars=p(13) q2 anchor=1 hmac_key=key))acfxyzp=1ampp=3ampq=2amp_signature=a32530f0d0caa80964bb92aad2bedf8a4486a31f1

gtgtgt str(URL(a=a c=c f=f args=[wx yz]))acfwxyz

gtgtgt str(URL(a=a c=c f=f args=[wx yz] encode_embedded_slash=True))acfw2Fxy2Fz

gtgtgt str(URL(a=a c=c f=f args=[(id)d] url_encode=False))acf(id)d

gtgtgt str(URL(a=a c=c f=f args=[(id)d] url_encode=True))acf2528id29d

48 Chapter 13 html Module

web2py Documentation Release 2146-stable

gtgtgt str(URL(a=a c=c f=f vars=id (id)d url_encode=False))acfid=(id)d

gtgtgt str(URL(a=a c=c f=f vars=id (id)d url_encode=True))acfid=2528id29d

gtgtgt str(URL(a=a c=c f=f anchor=(id)d url_encode=False))acf(id)d

gtgtgt str(URL(a=a c=c f=f anchor=(id)d url_encode=True))acf2528id29d

class gluonhtmlXHTML(components attributes)Bases gluonhtmlDIV

This is XHTML version of the HTML helper

There are three predefined document type definitions They can be specified in the lsquodoctypersquo parameter

bull lsquostrictrsquo enables strict doctype

bull lsquotransitionalrsquo enables transitional doctype (default)

bull lsquoframesetrsquo enables frameset doctype

bull any other string will be treated as userrsquos own doctype

lsquolangrsquo parameter specifies the language of the document and the xml document Defaults to lsquoenrsquo

lsquoxmlnsrsquo parameter specifies the xml namespace Defaults to lsquohttpwwww3org1999xhtmlrsquo

See also DIV

frameset = ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 FramesetEN httpwwww3orgTRxhtml1DTDxhtml1-framesetdtdgtn

strict = ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgtn

tag = html

transitional = ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 TransitionalEN httpwwww3orgTRxhtml1DTDxhtml1-transitionaldtdgtn

xml()generates the xml for this component

xmlns = httpwwww3org1999xhtml

class gluonhtmlXML(text sanitize=False permitted_tags=[rsquoarsquo rsquobrsquo rsquoblockquotersquo rsquobrrsquo rsquoirsquo rsquolirsquo rsquoolrsquorsquoulrsquo rsquoprsquo rsquocitersquo rsquocodersquo rsquoprersquo rsquoimgrsquo rsquoh1rsquo rsquoh2rsquo rsquoh3rsquo rsquoh4rsquo rsquoh5rsquo rsquoh6rsquo rsquotablersquo rsquotrrsquorsquotdrsquo rsquodivrsquo rsquostrongrsquo rsquospanrsquo] allowed_attributes=rsquoarsquo [rsquohrefrsquo rsquotitlersquo rsquotargetrsquo]rsquoblockquotersquo [rsquotypersquo] rsquoimgrsquo [rsquosrcrsquo rsquoaltrsquo] rsquotdrsquo [rsquocolspanrsquo])

Bases gluonhtmlXmlComponent

use it to wrap a string that contains XMLHTML so that it will not be escaped by the template

Examples

gtgtgt XML(lth1gtHellolth1gt)xml()lth1gtHellolth1gt

elements(args kargs)to be considered experimental since the behavior of this method is questionable another option could beTAG(selftext)elements(args kwargs)

131 Template helpers 49

web2py Documentation Release 2146-stable

flatten(render=None)returns the text stored by the XML object rendered by the render function

xml()

gluonhtmlxmlescape(data quote=True)Returns an escaped string of the provided data

Parameters

bull data ndash the data to be escaped

bull quote ndash optional (default False)

gluonhtmlembed64(filename=None file=None data=None extension=rsquoimagegifrsquo)helper to encode the provided (binary) data into base64

Parameters

bull filename ndash if provided opens and reads this file in lsquorbrsquo mode

bull file ndash if provided reads this file

bull data ndash if provided uses the provided data

50 Chapter 13 html Module

CHAPTER 14

http Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

141 HTTP statuses helpers

exception gluonhttpHTTP(status body=rdquo cookies=None headers)Bases exceptionsException

Raises an HTTP response

Parameters

bull status ndash usually an integer If itrsquos a well known status code the ERROR message will beautomatically added A string can also be passed as 510 Foo Bar and in that case the statuscode and the error message will be parsed accordingly

bull body ndash what to return as body If left as is will return the error code and the status messagein the body itself

bull cookies ndash pass cookies along (usually not needed)

bull headers ndash pass headers as usual dict mapping

cookies2headers(cookies)

messagecompose a message describing this exception

ldquostatus defined_status [web2py_error]rdquo

message elements that are not defined are omitted

to(responder env=None)

51

web2py Documentation Release 2146-stable

gluonhttpredirect(location=rdquo how=303 client_side=False headers=None)Raises a redirect (303)

Parameters

bull location ndash the url where to redirect

bull how ndash what HTTP status code to use when redirecting

bull client_side ndash if set to True it triggers a reload of the entire page when the fragmenthas been loaded as a component

52 Chapter 14 http Module

CHAPTER 15

languages Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)Plural subsystem is created by Vladyslav Kozlovskyy (Ukraine) ltdbdevelopgmailcomgt

151 Translation system

class gluonlanguagestranslator(langpath http_accept_language)Bases object

This class is instantiated by gluoncompileappbuild_environment as the T object

Example

Tforce(None) turns off translation Tforce(lsquofr itrsquo) forces web2py to translate using frpy or itpy

T(ldquoHello Worldrdquo) translates ldquoHello Worldrdquo using the selected file

Note

bull there is no need to force since by default T uses http_accept_language to determine a translation file

bull en and en-en are considered different languages

bull if language xx-yy is not found force() probes other similar languages using such algorithm xx-yypy -gtxxpy -gt xx-yypy -gt xxpy

M(message symbols= language=None lazy=None filter=None ftag=None ns=None)Gets cached translated markmin-message with inserted parametes if lazy==True lazyT object is returned

apply_filter(message symbols= filter=None ftag=None)

53

web2py Documentation Release 2146-stable

force(languages)Selects language(s) for translation

if a list of languages is passed as a parameter the first language from this list that matches the ones fromthe possible_languages dictionary will be selected

default language will be selected if none of them matches possible_languages

get_possible_languages()Gets list of all possible languages for current application

get_possible_languages_info(lang=None)Returns info for selected language or dictionary with all possible languages info from APPlanguagespyIt Returns

bull a tuple containing

langcode langname langfile_mtimepluraldict_fname pluraldict_mtimeprules_langcode npluralsget_plural_id construct_plural_form

or None

bull if lang is NOT defined a dictionary with all possible languages

langcode(from filename)( langcode language code from langcodelangname

language name in national spelling from langnamelangfile_mtime m_time of language filepluraldict_fname name of plural dictionary file or None (when

rarr˓defaultpy is not exist)pluraldict_mtime m_time of plural dictionary file or 0 if file is

rarr˓not existprules_langcode code of plural rules language or defaultnplurals nplurals for current languageget_plural_id get_plural_id() for current languageconstruct_plural_form) construct_plural_form() for current

rarr˓language

Parameters lang (str) ndash language

get_t(message prefix=rdquo)Use to add a comment into a translation string the comment can be useful do discriminate differentpossible translations for the same string (for example different locations)

T( hello world ) -gt hello world T( hello world token) -gt hello world T(hello world token) -gt hello world

the notation is ignored in multiline strings and strings that start with This is needed to allow markminsyntax to be translated

params_substitution(message symbols)Substitutes parameters from symbols into message using also parse placeholders for plural-formsprocessing

Returns string with parameters

54 Chapter 15 languages Module

web2py Documentation Release 2146-stable

Note symbols MUST BE OR tuple OR dict of parameters

plural(word n)Gets plural form of word for number n invoked from T()TM() in tag

Note ldquowordrdquo MUST be defined in current language (Taccepted_language)

Parameters

bull word (str) ndash word in singular

bull n (numeric) ndash number plural form created for

Returns word in appropriate singularplural form

Return type word (str)

set_current_languages(languages)Sets current AKA ldquodefaultrdquo languages Setting one of this languages makes the force() function to turntranslation off

translate(message symbols)Gets cached translated message with inserted parameters(symbols)

gluonlanguagesfindT(path language=rsquoenrsquo)

Note Must be run by the admin app

gluonlanguagesupdate_all_languages(application_path)

Note Must be run by the admin app

151 Translation system 55

web2py Documentation Release 2146-stable

56 Chapter 15 languages Module

CHAPTER 16

main Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

161 The gluon wsgi application

gluonmainwsgibase(environ responder)The gluon wsgi application The first function called when a page is requested (static or dynamic) It can becalled by pastehttpserver or by apache mod_wsgi (or any WSGI-compatible server)

bull fills request with info

bull the environment variables replacing lsquorsquo with lsquo_rsquo

bull adds web2py path and version info

bull compensates for fcgi missing path_info and query_string

bull validates the path in url

The url path must be either

1 for static pages

bull ltapplicationgtstaticltfilegt

2 for dynamic pages

bull ltapplicationgt[ltcontrollergt[ltfunctiongt[ltsubgt]]][ltextensiongt]

The naming conventions are

bull application controller function and extension may only contain [a-zA-Z0-9_]

57

web2py Documentation Release 2146-stable

bull file and sub may also contain lsquo-lsquo lsquo=rsquo lsquorsquo and lsquorsquo

gluonmainsave_password(password port)Used by main() to save the password in the parameters_portpy file

gluonmainappfactory(wsgiapp=ltfunction wsgibasegt logfilename=rsquohttpserverlogrsquo pro-filer_dir=None profilerfilename=None)

generates a wsgi application that does logging and profiling and calls wsgibase

Parameters

bull wsgiapp ndash the base application

bull logfilename ndash where to store apache-compatible requests log

bull profiler_dir ndash where to store profile files

class gluonmainHttpServer(ip=rsquo127001rsquo port=8000 password=rdquopid_filename=rsquohttpserverpidrsquo log_filename=rsquohttpserverlogrsquoprofiler_dir=None ssl_certificate=None ssl_private_key=Nonessl_ca_certificate=None min_threads=None max_threads=Noneserver_name=None request_queue_size=5 timeout=10socket_timeout=1 shutdown_timeout=None path=None inter-faces=None)

Bases object

the web2py web server (Rocket)

start()start the web server

stop(stoplogging=False)stop cron and the web server

58 Chapter 16 main Module

CHAPTER 17

messageboxhandler Module

class gluonmessageboxhandlerMessageBoxHandlerBases loggingHandler

emit(record)Do whatever it takes to actually log the specified logging record

This version is intended to be implemented by subclasses and so raises a NotImplementedError

class gluonmessageboxhandlerNotifySendHandlerBases loggingHandler

emit(record)Do whatever it takes to actually log the specified logging record

This version is intended to be implemented by subclasses and so raises a NotImplementedError

59

web2py Documentation Release 2146-stable

60 Chapter 17 messageboxhandler Module

CHAPTER 18

myregex Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

181 Useful regexes

61

web2py Documentation Release 2146-stable

62 Chapter 18 myregex Module

CHAPTER 19

newcron Module

This file is part of the web2py Web FrameworkCreated by Attila Csipa ltweb2pycsipainrsgtModified by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

Cron-style interface

class gluonnewcronToken(path)Bases object

acquire(startup=False)Returns the time when the lock is acquired or None if cron already running

lock is implemented by writing a pickle (start stop) in cronmaster start is time when cron job starts andstop is time when cron completed stop == 0 if job started but did not yet complete if a cron job startedwithin less than 60 seconds acquire returns None if a cron job started before 60 seconds and did not stopa warning is issue ldquoStale cronmaster detectedrdquo

release()Writes into cronmaster the time when cron job was completed

gluonnewcronabsolute_path_link(path)Returns an absolute path for the destination of a symlink

gluonnewcroncrondance(applications_parent ctype=rsquosoftrsquo startup=False apps=None)

class gluonnewcroncronlauncher(cmd shell=True)Bases threadingThread

run()Method representing the threadrsquos activity

You may override this method in a subclass The standard run() method invokes the callable object passedto the objectrsquos constructor as the target argument if any with sequential and keyword arguments takenfrom the args and kwargs arguments respectively

63

web2py Documentation Release 2146-stable

class gluonnewcronextcron(applications_parent apps=None)Bases threadingThread

run()Method representing the threadrsquos activity

You may override this method in a subclass The standard run() method invokes the callable object passedto the objectrsquos constructor as the target argument if any with sequential and keyword arguments takenfrom the args and kwargs arguments respectively

class gluonnewcronhardcron(applications_parent)Bases threadingThread

launch()

run()Method representing the threadrsquos activity

You may override this method in a subclass The standard run() method invokes the callable object passedto the objectrsquos constructor as the target argument if any with sequential and keyword arguments takenfrom the args and kwargs arguments respectively

gluonnewcronparsecronline(line)

gluonnewcronrangetolist(s period=rsquominrsquo)

class gluonnewcronsoftcron(applications_parent)Bases threadingThread

run()Method representing the threadrsquos activity

You may override this method in a subclass The standard run() method invokes the callable object passedto the objectrsquos constructor as the target argument if any with sequential and keyword arguments takenfrom the args and kwargs arguments respectively

gluonnewcronstopcron()Graceful shutdown of cron

64 Chapter 19 newcron Module

CHAPTER 20

portalocker Module

Cross-platform (posixnt) API for flock-style file locking

Synopsis

import portalockerfile = open(somefile r+)portalockerlock(file portalockerLOCK_EX)fileseek(12)filewrite(foo)fileclose()

If you know what yoursquore doing you may choose to

portalockerunlock(file)

before closing the file but why

Methods

lock( file flags )unlock( file )

Constants

LOCK_EXLOCK_SHLOCK_NB

I learned the win32 technique for locking files from sample code provided by John Nielsen ltnielsenjfmy-dejacomgtin the documentation that accompanies the win32 modules

Author Jonathan Feinberg ltjdfpoboxcomgt Version $Id portalockerpyv 13 20010529 184755 AdministratorExp $

class gluonportalockerLockedFile(filename mode=rsquorbrsquo)Bases object

65

web2py Documentation Release 2146-stable

close()

read(size=None)

readline()

readlines()

write(data)

gluonportalockerlock(file flags)

gluonportalockerread_locked(filename)

gluonportalockerunlock(file)

gluonportalockerwrite_locked(filename data)

66 Chapter 20 portalocker Module

CHAPTER 21

recfile Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

211 Generates names for cache and session files

gluonrecfileexists(filename path=None)

gluonrecfilegenerate(filename depth=2 base=512)

gluonrecfileopen(filename mode=rsquorrsquo path=None)

gluonrecfileremove(filename path=None)

67

web2py Documentation Release 2146-stable

68 Chapter 21 recfile Module

CHAPTER 22

restricted Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

221 Restricted environment to execute applicationrsquos code

exception gluonrestrictedRestrictedError(layer=rdquo code=rdquo output=rdquo environ-ment=None)

Bases exceptionsException

Class used to wrap an exception that occurs in the restricted environment below The traceback is used to logthe exception and generate a ticket

load(request app ticket_id)Loads a logged exception

log(request)Logs the exception

gluonrestrictedrestricted(code environment=None layer=rsquoUnknownrsquo)Runs code in environment and returns the output If an exception occurs in code it raises a RestrictedErrorcontaining the traceback Layer is passed to RestrictedError to identify where the error occurred

class gluonrestrictedTicketStorage(db=None tablename=rsquoweb2py_ticketrsquo)Bases gluonstorageStorage

Defines the ticket object and the default values of its members (None)

load(request app ticket_id)

store(request ticket_id ticket_data)Stores the ticket It will figure out if this must be on disk or in db

gluonrestrictedcompile2(code layer)The +n is necessary else compile fails when code ends in a comment

69

web2py Documentation Release 2146-stable

70 Chapter 22 restricted Module

CHAPTER 23

rewrite Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

gluonrewrite parses incoming URLs and formats outgoing URLs for gluonhtmlURL

In addition it rewrites both incoming and outgoing URLs based on the (optional) user-supplied routespy which alsoallows for rewriting of certain error messages

routespy supports two styles of URL rewriting depending on whether lsquoroutersrsquo is defined Refer to routerexamplepyand routesexamplepy for additional documentation

class gluonrewriteMapUrlIn(request=None env=None)Bases object

Logic for mapping incoming URLs

arg0Returns first arg

harg0Returns first arg with optional hyphen mapping

map_app()Determines application name

map_controller()Identifies controller

map_function()Handles functionextension

map_language()Handles language (no hyphen mapping)

71

web2py Documentation Release 2146-stable

map_prefix()Strips path prefix if present in its entirety

map_root_static()Handles root-static files (no hyphen mapping)

a root-static file is one whose incoming URL expects it to be at the root typically robotstxt amp faviconico

map_static()Handles static files file_match but no hyphen mapping

pop_arg_if(dopop)Conditionally removes first arg and returns new first arg

sluggify()

update_request()Updates request from self Builds envrequest_uri Makes lower-case versions of http headers in env

validate_args()Checks args against validation pattern

class gluonrewriteMapUrlOut(request env application controller function args other schemehost port language)

Bases object

Logic for mapping outgoing URLs

acf()Converts components to applangcontrollerfunction

build_acf()Builds acf from components

omit_acf()Omits what we can of acf

omit_lang()Omits language if possible

gluonrewritecompile_regex(k v env=None)Preprocess and compile the regular expressions in routes_appinout The resulting regex will match a pattern ofthe form

[remote address][protocol][host][method] [path]

We allow abbreviated regexes on input here we try to complete them

gluonrewritefilter_err(status application=rsquoapprsquo ticket=rsquotktrsquo)doctestunittest interface to routes_onerror

gluonrewritefilter_url(url method=rsquogetrsquo remote=rsquo0000rsquo out=False app=False lang=Nonedomain=(None None) env=False scheme=None host=Noneport=None language=None)

doctestunittest interface to regex_filter_in() and regex_filter_out()

gluonrewritefixup_missing_path_info(environ)

gluonrewriteget_effective_router(appname)Returns a private copy of the effective router for the specified application

gluonrewriteinvalid_url(routes)

72 Chapter 23 rewrite Module

web2py Documentation Release 2146-stable

gluonrewriteload(routes=rsquoroutespyrsquo app=None data=None rdict=None)load read (if file) and parse routes store results in params (called from mainpy at web2py initialization time)If data is present itrsquos used instead of the routespy contents If rdict is present it must be a dict to be used forrouters (unit test)

gluonrewriteload_routers(all_apps)Load-time post-processing of routers

gluonrewritelog_rewrite(string)Log rewrite activity under control of routespy

gluonrewritemap_url_in(request env app=False)Routes incoming URL

gluonrewritemap_url_out(request env application controller function args other scheme hostport language=None)

Supply acf (or alangcf) portion of outgoing url

The basic rule is that we can only make transformations that map_url_in can reverse

Suppose that the incoming arguments are acfargslang and that the router defaults are da dc df dl

We can perform these transformations trivially if args=[] and lang=None or dl

dadcdf =gt adcdf =gt aacdf =gt ac

We would also like to be able to strip the default application or applicationcontroller from URLs with func-tionargs present thus

dacfargs =gt cfargsdadcfargs =gt fargs

We use [applications] and [controllers] and functions to suppress ambiguous omissions

We assume that language names do not collide with acf names

gluonrewriteregex_filter_in(e)Regex rewrite incoming URL

gluonrewriteregex_filter_out(url e=None)Regex rewrite outgoing URL

gluonrewriteregex_select(env=None app=None request=None)Selects a set of regex rewrite params for the current request

gluonrewriteregex_uri(e regexes tag default=None)Filters incoming URI against a list of regexes

gluonrewriteregex_url_in(request environ)Rewrites and parses incoming URL

gluonrewritesluggify(key)

gluonrewritetry_redirect_on_error(http_object request ticket=None)Called from mainwsgibase to rewrite the http response

gluonrewritetry_rewrite_on_error(http_response request environ ticket=None)Called from mainwsgibase to rewrite the http response

gluonrewriteurl_in(request environ)Parses and rewrites incoming URL

73

web2py Documentation Release 2146-stable

gluonrewriteurl_out(request environ application controller function args other scheme hostport language=None)

Assembles and rewrites outgoing URL

74 Chapter 23 rewrite Module

CHAPTER 24

sanitizer Module

From httpaspnactivestatecomASPNCookbookPythonRecipe496942Submitter Josh Goldfoot (other recipes)Last Updated 20060805Version 10

241 Cross-site scripting (XSS) defense

gluonsanitizersanitize(text permitted_tags=[rsquoarsquo rsquobrsquo rsquoblockquotersquo rsquobrrsquo rsquoirsquo rsquolirsquo rsquoolrsquo rsquoulrsquorsquoprsquo rsquocitersquo rsquocodersquo rsquoprersquo rsquoimgrsquo rsquoh1rsquo rsquoh2rsquo rsquoh3rsquo rsquoh4rsquo rsquoh5rsquo rsquoh6rsquo rsquota-blersquo rsquotbodyrsquo rsquotheadrsquo rsquotfootrsquo rsquotrrsquo rsquotdrsquo rsquodivrsquo rsquostrongrsquo rsquospanrsquo] al-lowed_attributes=rsquoarsquo [rsquohrefrsquo rsquotitlersquo] rsquoblockquotersquo [rsquotypersquo] rsquoimgrsquo[rsquosrcrsquo rsquoaltrsquo] rsquotdrsquo [rsquocolspanrsquo] escape=True)

75

web2py Documentation Release 2146-stable

76 Chapter 24 sanitizer Module

CHAPTER 25

scheduler Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

251 Background processes made simple

class gluonschedulerJobGraph(db job_name)Bases object

Experimental dependencies amongs tasks

add_deps(task_parent task_child)Create a dependency between task_parent and task_child

validate(job_name=None)Validate if all tasks job_name can be completed

Checks if there are no mutual dependencies among tasks Commits at the end if successfull or it rollbacksthe entire transaction Handle with care

class gluonschedulerMetaSchedulerBases threadingThread

Base class documenting schedulerrsquos base methods

async(task)Start the background process

Parameters task ndash a Task object

Returns

containing

77

web2py Documentation Release 2146-stable

(okresultoutput)(errorexceptionNone)(timeoutNoneNone)(terminatedNoneNone)

Return type tuple

die()Forces termination of the worker process along with any running task

give_up()Waits for any running task to be executed then exits the worker process

loop()Main loop fetching tasks and starting executorrsquos background processes

pop_task()Fetches a task ready to be executed

report_task(task task_report)Creates a task report

run()This is executed by the main thread to send heartbeats

send_heartbeat(counter)

sleep()

start_heartbeats()

terminate_process()Terminates any running tasks (internal use only)

class gluonschedulerScheduler(db tasks=None migrate=True worker_name=Nonegroup_names=None heartbeat=3 max_empty_runs=0discard_results=False utc_time=False)

Bases gluonschedulerMetaScheduler

Scheduler object

Parameters

bull db ndash DAL connection where Scheduler will create its tables

bull tasks (dict) ndash either a dict containing namendashgtfunc or None If None functions will besearched in the environment

bull migrate (bool) ndash turn migration onoff for the Schedulerrsquos tables

bull worker_name (str) ndash force worker_name to identify each process Leave it to None toautoassign a name (hostnamepid)

bull group_names (list) ndash process tasks belonging to this group defaults to [lsquomainrsquo] if noth-ing gets passed

bull heartbeat (int) ndash how many seconds the worker sleeps between one execution and thefollowing one Indirectly sets how many seconds will pass between checks for new tasks

bull max_empty_runs (int) ndash how many loops are allowed to pass without processing anytasks before exiting the process 0 to keep always the process alive

78 Chapter 25 scheduler Module

web2py Documentation Release 2146-stable

bull discard_results (bool) ndash Scheduler stores executionsrsquos details into the sched-uler_run table By default only if there is a result the details are kept Turning this toTrue means discarding results even for tasks that return something

bull utc_time (bool) ndash do all datetime calculations assuming UTC as the timezone Remem-ber to pass start_time and stop_time to tasks accordingly

adj_hibernation()Used to increase the ldquosleeprdquo interval for DISABLED workers

assign_tasks(db)Assign task to workers that can then pop them from the queue

Deals with group_name(s) logic in order to assign linearly tasks to available workers for those groups

being_a_ticker()Elect a TICKER process that assigns tasks to available workers

Does its best to elect a worker that is not busy processing other tasks to allow a proper distribution of tasksamong all active workers ASAP

define_tables(db migrate)Define Scheduler tables structure

disable(group_names=None limit=None worker_name=None)Set DISABLED on the workers processing group_names tasks

A DISABLED worker will be kept alive but it wonrsquot be able to process any waiting tasks essentiallyputting it to sleep By default all group_names of Schedulerrsquos instantation are selected

get_workers(only_ticker=False)Returns a dict holding worker_name columns representing all ldquoregisteredrdquo workers only_ticker re-turns only the workers running as a TICKER if there are any

kill(group_names=None limit=None worker_name=None)Sets KILL as worker status The worker will be killed even if itrsquos processing a task

loop(worker_name=None)Main loop

This works basically as a neverending loop that

bull checks if the worker is ready to process tasks (is not DISABLED)

bull pops a task from the queue

bull if there is a task

ndash spawns the executor background process

ndash waits for the process to be finished

ndash sleeps heartbeat seconds

bull if there is not a task

ndash checks for max_empty_runs

ndash sleeps heartbeat seconds

now()Shortcut that fetches current time based on UTC preferences

pop_task(db)Grab a task ready to be executed from the queue

251 Background processes made simple 79

web2py Documentation Release 2146-stable

queue_task(function pargs=[] pvars= kwargs)Queue tasks This takes care of handling the validation of all parameters

Parameters

bull function ndash the function (anything callable with a __name__)

bull pargs ndash ldquorawrdquo args to be passed to the function Automatically jsonified

bull pvars ndash ldquorawrdquo kwargs to be passed to the function Automatically jsonified

bull kwargs ndash all the parameters available (basically every scheduler_task column) If argsand vars are here they should be jsonified already and they will override pargs and pvars

Returns a dict just as a normal validate_and_insert() plus a uuid key holding the uuid of thequeued task If validation is not passed ( ie some parameters are invalid) both id and uuidwill be None and yoursquoll get an ldquoerrorrdquo dict holding the errors found

report_task(task task_report)Take care of storing the result according to preferences

Deals with logic for repeating tasks

resume(group_names=None limit=None worker_name=None)Wakes a worker up (it will be able to process queued tasks)

send_heartbeat(counter)Coordination among available workers

It - sends the heartbeat - elects a ticker among available workers (the only process that

effectively dispatch tasks to workers)

bull deals with workerrsquos statuses

bull does ldquohousecleaningrdquo for dead workers

bull triggers tasks assignment to workers

set_requirements(scheduler_task)Called to set defaults for lazy_tables connections

set_worker_status(group_names=None action=rsquoACTIVErsquo exclude=None limit=Noneworker_name=None)

Internal function to set workerrsquos status

sleep()Calculate the number of seconds to sleep

stop_task(ref)Shortcut for task termination

If the task is RUNNING it will terminate it meaning that status will be set as FAILED

If the task is QUEUED its stop_time will be set as to ldquonowrdquo the enabled flag will be set to False andthe status to STOPPED

Parameters ref ndash can be

bull an integer lookup will be done by scheduler_taskid

bull a string lookup will be done by scheduler_taskuuid

Returns

bull 1 if task was stopped (meaning an update has been done)

80 Chapter 25 scheduler Module

web2py Documentation Release 2146-stable

bull None if task was not found or if task was not RUNNING or QUEUED

Note Experimental

task_status(ref output=False)Retrieves task status and optionally the result of the task

Parameters

bull ref ndash can be

ndash an integer lookup will be done by scheduler_taskid

ndash a string lookup will be done by scheduler_taskuuid

ndash a Query lookup as you wish eg

dbscheduler_tasktask_name == test1

bull output (bool) ndash if True fetch also the scheduler_run record

Returns a single Row object for the last queued task If output == True returns also the lastscheduler_run record The scheduler_run record is fetched by a left join so it can have allfields == None

terminate(group_names=None limit=None worker_name=None)Sets TERMINATE as worker status The worker will wait for any currently running tasks to be executedand then it will exit gracefully

static total_seconds(td)Backport for py26

update_dependencies(db task_id)Unblock execution paths for Jobs

wrapped_assign_tasks(db)Commodity function to call assign_tasks and trap exceptions

If an exception is raised assume it happened because of database contention and retries assign_task after05 seconds

wrapped_pop_task()Commodity function to call pop_task and trap exceptions

If an exception is raised assume it happened because of database contention and retries pop_task after 05seconds

wrapped_report_task(task task_report)Commodity function to call report_task and trap exceptions

If an exception is raised assume it happened because of database contention and retries pop_task after 05seconds

class gluonschedulerTYPE(myclass=lttype rsquolistrsquogt parse=False)Bases object

Validator that checks whether field is valid json and validates its type Used for args and vars of the sched-uler_task table

class gluonschedulerTask(app function timeout args=rsquo[]rsquo vars=rsquorsquo kwargs)Bases object

251 Background processes made simple 81

web2py Documentation Release 2146-stable

Defines a ldquotaskrdquo object that gets passed from the main thread to the executorrsquos one

class gluonschedulerTaskReport(status result=None output=None tb=None)Bases object

Defines a ldquotask reportrdquo object that gets passed from the executorrsquos thread to the main one

gluonschedulerexecutor(queue task out)The function used to execute tasks in the background process

gluonschedulermain()allows to run worker without python web2pypy by simply

python gluonschedulerpy

82 Chapter 25 scheduler Module

CHAPTER 26

serializers Module

This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

gluonserializerscast_keys(o cast=lttype rsquostrrsquogt encoding=rsquoutf-8rsquo)Builds a new object with ltcastgt type keys Use this function if you are in Python lt 265 This avoids syntaxerrors when unpacking dictionary arguments

Parameters

bull o ndash is the object input

bull cast ndash (defaults to str) is an object type or function which supports conversion such as

converted = cast(o)

bull encoding ndash (defaults to utf-8) is the encoding for unicode keys This is not used forcustom cast functions

gluonserializerscsv(value)

gluonserializerscustom_json(o)

gluonserializersics(events title=None link=None timeshift=0 calname=True ignored)

gluonserializersjson(value default=ltfunction custom_jsongt)

gluonserializersloads_json(o unicode_keys=True kwargs)

gluonserializersloads_yaml(data)

gluonserializersrss(feed)

gluonserializerssafe_encode(text)

gluonserializersxml(value encoding=rsquoUTF-8rsquo key=rsquodocumentrsquo quote=True)

gluonserializersxml_rec(value key quote=True)

gluonserializersyaml(data)

83

web2py Documentation Release 2146-stable

84 Chapter 26 serializers Module

CHAPTER 27

settings Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

85

web2py Documentation Release 2146-stable

86 Chapter 27 settings Module

CHAPTER 28

shell Module

This file is part of the web2py Web FrameworkDeveloped by Massimo Di Pierro ltmdipierrocsdepauledugtlimodou ltlimodougmailcomgt and srackham ltsrackhamgmailcomgtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

281 Web2py environment in the shell

gluonshelldie(msg)

gluonshellenable_autocomplete_and_history(adir env)

gluonshellenv(a import_models=False c=None f=None dir=rdquo extra_request=)Returns web2py execution environment for application (a) controller (c) function (f) If import_models is Truethe exec all application models into the environment

extra_request allows you to pass along any extra variables to the request object before your models get executedThis was mainly done to support web2py_utilstest_runner however you can use it with any wrapper scripts thatneed access to the web2py environment

gluonshellexec_environment(pyfile=rdquo request=None response=None session=None)Environment builder and module loader

Builds a web2py environment and optionally executes a Python file into the environment

A Storage dictionary containing the resulting environment is returned The working directory must be web2pyroot ndash this is the web2py default

gluonshellexec_pythonrc()

gluonshellexecute_from_command_line(argv=None)

gluonshellget_usage()

87

web2py Documentation Release 2146-stable

gluonshellparse_path_info(path_info av=False)Parses path info formatted like acf where c and f are optional and a leading is accepted Return tuple (a c f)If invalid path_info a is set to None If c or f are omitted they are set to None If av=True parse args and vars

gluonshellrun(appname plain=False import_models=False startfile=None bpython=Falsepython_code=False cronjob=False)

Start interactive shell or run Python script (startfile) in web2py controller environment appname is formattedlike

bull a web2py application name

bull ac exec the controller c into the application environment

gluonshelltest(testpath import_models=True verbose=False)Run doctests in web2py environment testpath is formatted like

bull a tests all controllers in application a

bull ac tests controller c in application a

bull acf test function f in controller c application a

Where a c and f are application controller and function names respectively If the testpath is a file name the fileis tested If a controller is specified models are executed by default

88 Chapter 28 shell Module

CHAPTER 29

sql Module

This file is part of the web2py Web FrameworkDeveloped by Massimo Di Pierro ltmdipierrocsdepauledugtlimodou ltlimodougmailcomgt and srackham ltsrackhamgmailcomgtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

291 Just for backward compatibility

class gluonsqlDAL(uri=rsquosqlitedummydbrsquo pool_size=0 folder=None db_codec=rsquoUTF-8rsquo check_reserved=None migrate=True fake_migrate=False mi-grate_enabled=True fake_migrate_all=False decode_credentials=Falsedriver_args=None adapter_args=None attempts=5 auto_import=False big-int_id=False debug=False lazy_tables=False db_uid=None do_connect=Trueafter_connection=None tables=None ignore_field_case=True en-tity_quoting=False table_hash=None)

Bases pydalhelpersclassesSerializable pydalhelpersclassesBasicStorage

An instance of this class represents a database connection

Parameters

bull uri (str) ndash contains information for connecting to a database Defaults tolsquosqlitedummydbrsquo

Note experimental you can specify a dictionary as uri parameter ie with

db = DAL(uri sqlitestoragesqlitetables )

for an example of dict input you can check the output of the scaffolding db model with

dbas_dict()

89

web2py Documentation Release 2146-stable

Note that for compatibility with Python older than version 265 you should cast your dictinput keys to str due to a syntax limitation on kwarg names for proper DAL dictionary inputyou can use one of

obj = serializerscast_keys(dict [encoding=utf-8])or else (for parsing json input)obj = serializersloads_json(data unicode_keys=False)

bull pool_size ndash How many open connections to make to the database object

bull folder ndash where table files will be created Automatically set within web2py Use anexplicit path when using DAL outside web2py

bull db_codec ndash string encoding of the database (default lsquoUTF-8rsquo)

bull table_hash ndash database identifier with tables If your connection hash change you canstill using old tables if they have db_hash as prefix

bull check_reserved ndash list of adapters to check tablenames and column names againstsqlnosql reserved keywords Defaults to None

ndash rsquocommonrsquo List of sql keywords that are common to all database types such as ldquoSELECTINSERTrdquo (recommended)

ndash rsquoallrsquo Checks against all known SQL keywords

ndash rsquoltadapternamegtrdquo Checks against the specific adapters list of keywords

ndash rsquoltadapternamegt_nonreservedrsquo Checks against the specific adapters list of nonreservedkeywords (if available)

bull migrate ndash sets default migrate behavior for all tables

bull fake_migrate ndash sets default fake_migrate behavior for all tables

bull migrate_enabled ndash If set to False disables ALL migrations

bull fake_migrate_all ndash If set to True fake migrates ALL tables

bull attempts ndash Number of times to attempt connecting

bull auto_import ndash If set to True tries import automatically table definitions from thedatabases folder (works only for simple models)

bull bigint_id ndash If set turn on bigint instead of int for id and reference fields

bull lazy_tables ndash delays table definition until table access

bull after_connection ndash can a callable that will be executed after the connection

Example

Use as

db = DAL(sqlitetestdb)

or

90 Chapter 29 sql Module

web2py Documentation Release 2146-stable

db = DAL(uri tables []) experimental

dbdefine_table(tablename Field(fieldname1)Field(fieldname2))

class Field(fieldname type=rsquostringrsquo length=None default=ltfunction ltlambdagtgt re-quired=False requires=ltfunction ltlambdagtgt ondelete=rsquoCASCADErsquo not-null=False unique=False uploadfield=True widget=None label=None com-ment=None writable=True readable=True update=None authorize=Noneautodelete=False represent=None uploadfolder=None uploadseparate=Falseuploadfs=None compute=None custom_store=None custom_retrieve=Nonecustom_retrieve_file_properties=None custom_delete=None filter_in=None fil-ter_out=None custom_qualifier=None map_none=None rname=None)

Bases pydalobjectsExpression pydalhelpersclassesSerializable

Lazyalias of FieldMethod

Methodalias of FieldMethod

Virtualalias of FieldVirtual

as_dict(flat=False sanitize=True)

clone(point_self_references_to=False args)

count(distinct=None)

formatter(value)

retrieve(name path=None nameonly=False)If nameonly==True return (filename fullfilename) instead of (filename stream)

retrieve_file_properties(name path=None)

set_attributes(args attributes)

sqlsafe

sqlsafe_name

store(file filename=None path=None)

validate(value)

class Row(args kwargs)Bases pydalhelpersclassesBasicStorage

A dictionary that lets you do d[lsquoarsquo] as well as da this is only used to store a Row

as_dict(datetime_to_str=False custom_types=None)

as_json(mode=rsquoobjectrsquo default=None colnames=None serialize=True kwargs)serializes the row to a JSON object kwargs are passed to as_dict method only ldquoobjectrdquo mode sup-ported

serialize = False used by Rowsas_json

TODO return array mode with query column order

mode and colnames are not implemented

as_xml(row_name=rsquorowrsquo colnames=None indent=rsquo rsquo)

291 Just for backward compatibility 91

web2py Documentation Release 2146-stable

get(key default=None)

class Table(db tablename fields args)Bases pydalhelpersclassesSerializable pydalhelpersclassesBasicStorage

Represents a database table

Example

You can create a table as db = DAL( ) dbdefine_table(lsquousersrsquo Field(lsquonamersquo))

And then

dbusersinsert(name=me) print dbusers_insert() to see SQLdbusersdrop()

as_dict(flat=False sanitize=True)

bulk_insert(items)here items is a list of dictionaries

drop(mode=rdquo)

fields

import_from_csv_file(csvfile id_map=None null=rsquoltNULLgtrsquo unique=rsquouuidrsquoid_offset=None args kwargs)

Import records from csv file Column headers must have same names as table fields Field lsquoidrsquo isignored If column names read lsquotablefilersquo the lsquotablersquo prefix is ignored

bull lsquouniquersquo argument is a field which must be unique (typically a uuid field)bull lsquorestorersquo argument is default False if set True will remove old values in table firstbull lsquoid_maprsquo if set to None will not map ids

The import will keep the id numbers in the restored table This assumes that there is an field of typeid that is integer and in incrementing order Will keep the id numbers in restored table

insert(fields)

on(query)

sqlsafe

sqlsafe_alias

truncate(mode=None)

update(args kwargs)

update_or_insert(_key=ltfunction ltlambdagtgt values)

validate_and_insert(fields)

validate_and_update(_key=ltfunction ltlambdagtgt fields)

validate_and_update_or_insert(_key=ltfunction ltlambdagtgt fields)

with_alias(alias)

as_dict(flat=False sanitize=True)

can_join()

check_reserved_keyword(name)Validates name against SQL keywords Uses selfcheck_reserve which is a list of operators to use

close()

92 Chapter 29 sql Module

web2py Documentation Release 2146-stable

commit()

define_table(tablename fields args)

static distributed_transaction_begin(instances)

static distributed_transaction_commit(instances)

executesql(query placeholders=None as_dict=False fields=None colnames=Noneas_ordered_dict=False)

Executes an arbitrary query

Parameters

bull query (str) ndash the query to submit to the backend

bull placeholders ndash is optional and will always be None If using raw SQL with place-holders placeholders may be a sequence of values to be substituted in or (if supported bythe DB driver) a dictionary with keys matching named placeholders in your SQL

bull as_dict ndash will always be None when using DAL If using raw SQL can be set to Trueand the results cursor returned by the DB driver will be converted to a sequence of dic-tionaries keyed with the db field names Results returned with as_dict=True are the sameas those returned when applying to_list() to a DAL query If ldquoas_ordered_dictrdquo=True thebehaviour is the same as when ldquoas_dictrdquo=True with the keys (field names) guaranteed tobe in the same order as returned by the select name executed on the database

bull fields ndash list of DAL Fields that match the fields returned from the DB The Field objectsshould be part of one or more Table objects defined on the DAL object The ldquofieldsrdquo listcan include one or more DAL Table objects in addition to or instead of including Fieldobjects or it can be just a single table (not in a list) In that case the Field objects will beextracted from the table(s)

Note if either fields or colnames is provided the results will be converted to a DAL Rowsobject using the db_adapterparse() method

bull colnames ndash list of field names in tablenamefieldname format

Note It is also possible to specify both ldquofieldsrdquo and the associated ldquocolnamesrdquo In that case ldquofieldsrdquocan also include DAL Expression objects in addition to Field objects For Field objects in ldquofieldsrdquo theassociated ldquocolnamesrdquo must still be in tablenamefieldname format For Expression objects in ldquofieldsrdquo theassociated ldquocolnamesrdquo can be any arbitrary labels

DAL Table objects referred to by ldquofieldsrdquo or ldquocolnamesrdquo can be dummy tables and do not have to representany real tables in the database Also note that the ldquofieldsrdquo and ldquocolnamesrdquo must be in the same order asthe fields in the results cursor returned from the DB

export_to_csv_file(ofile args kwargs)

static get_instances()Returns a dictionary with uri as key with timings and defined tables

sqlitestoragesqlite dbstats [(select auth_useremail from auth_user 002009)]dbtables

defined [auth_cas auth_event auth_groupauth_membership auth_permission auth_user]

(continues on next page)

291 Just for backward compatibility 93

web2py Documentation Release 2146-stable

(continued from previous page)

lazy []

has_representer(name)

import_from_csv_file(ifile id_map=None null=rsquoltNULLgtrsquo unique=rsquouuidrsquomap_tablenames=None ignore_missing_tables=False args kwargs)

import_table_definitions(path migrate=False fake_migrate=False tables=None)

lazy_define_table(tablename fields args)

logger = ltloggingLogger objectgt

parse_as_rest(patterns args vars queries=None nested_select=True)

Example

Use as

dbdefine_table(personField(name)Field(info))dbdefine_table(pet

Field(ownedbydbperson)Field(name)Field(info)

)

requestrestful()def index()

def GET(argsvars)patterns = [

friends[person]personnamefieldpersonnamepets[petownedby]personnamepets[petownedby]petnamepersonnamepets[petownedby]petnamefield(dogs[pet] dbpetinfo==dog)(dogs[pet]petnamestartswith dbpetinfo==dog)]

parser = dbparse_as_rest(patternsargsvars)if parserstatus == 200

return dict(content=parserresponse)else

raise HTTP(parserstatusparsererror)

def POST(table_namevars)if table_name == person

return dbpersonvalidate_and_insert(vars)elif table_name == pet

return dbpetvalidate_and_insert(vars)else

raise HTTP(400)return locals()

represent(name args kwargs)

representers = rows_render ltfunction represent at 0x7fcf10dcdb18gt rows_xml ltclass gluonsqlhtmlSQLTABLEgt

94 Chapter 29 sql Module

web2py Documentation Release 2146-stable

rollback()

serializers = json ltfunction custom_json at 0x7fcf11069488gt xml ltfunction xml at 0x7fcf11069578gt

static set_folder(folder)

smart_query(fields text)

tables

uuid()

validators = None

validators_method(field)Field type validation using web2pyrsquos validators mechanism

makes sure the content of a field is in line with the declared fieldtype

where(query=None ignore_common_filters=None)

class gluonsqlField(fieldname type=rsquostringrsquo length=None default=ltfunction ltlambdagtgtrequired=False requires=ltfunction ltlambdagtgt ondelete=rsquoCASCADErsquonotnull=False unique=False uploadfield=True widget=None label=Nonecomment=None writable=True readable=True update=None autho-rize=None autodelete=False represent=None uploadfolder=None upload-separate=False uploadfs=None compute=None custom_store=Nonecustom_retrieve=None custom_retrieve_file_properties=None cus-tom_delete=None filter_in=None filter_out=None custom_qualifier=Nonemap_none=None rname=None)

Bases pydalobjectsExpression pydalhelpersclassesSerializable

LazyRepresents a database field

Example

Usage

a = Field(name string length=32 default=None required=Falserequires=IS_NOT_EMPTY() ondelete=CASCADEnotnull=False unique=Falseuploadfield=True widget=None label=None comment=Noneuploadfield=True True means store on disk

a_field_name means store in this field in db False means file content will be discarded

writable=True readable=True update=None authorize=Noneautodelete=False represent=None uploadfolder=Noneuploadseparate=False upload to separate directories by uuid_keys

first 2 character and tablenamefieldname False - old behavior True - put uploaded file in ltuploaddirgtlttablenamegtltfieldnamegtuuid_key[2] directory)

uploadfs=None a pyfilesystem where to store upload)

to be used as argument of DALdefine_table

alias of FieldMethod

291 Just for backward compatibility 95

web2py Documentation Release 2146-stable

Methodalias of FieldMethod

Virtualalias of FieldVirtual

as_dict(flat=False sanitize=True)

clone(point_self_references_to=False args)

count(distinct=None)

formatter(value)

retrieve(name path=None nameonly=False)If nameonly==True return (filename fullfilename) instead of (filename stream)

retrieve_file_properties(name path=None)

set_attributes(args attributes)

sqlsafe

sqlsafe_name

store(file filename=None path=None)

validate(value)

96 Chapter 29 sql Module

CHAPTER 30

sqlhtml Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

Holds

bull SQLFORM provide a form for a table (withwithout record)

bull SQLTABLE provides a table for a set of records

bull form_factory provides a SQLFORM for an non-db backed table

class gluonsqlhtmlAutocompleteWidget(request field id_field=None db=None or-derby=None limitby=(0 10) distinct=False key-word=rsquo_autocomplete_(tablename)s_(fieldname)srsquomin_length=2 help_fields=Nonehelp_string=None at_beginning=True)

Bases object

callback()

class gluonsqlhtmlBooleanWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates an INPUT checkbox tag

see also FormWidgetwidget

class gluonsqlhtmlCacheRepresenterBases object

class gluonsqlhtmlCheckboxesWidgetBases gluonsqlhtmlOptionsWidget

classmethod widget(field value attributes)Generates a TABLE tag including INPUT checkboxes (multiple allowed)

97

web2py Documentation Release 2146-stable

see also FormWidgetwidget

class gluonsqlhtmlDateWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlDatetimeWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlDecimalWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlDoubleWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlExportClass(rows)Bases object

content_type = None

export()

file_ext = None

label = None

represented()

class gluonsqlhtmlExporterCSV(rows)Bases gluonsqlhtmlExportClass

content_type = textcsv

export()

file_ext = csv

label = CSV

class gluonsqlhtmlExporterCSV_hidden(rows)Bases gluonsqlhtmlExportClass

content_type = textcsv

export()

file_ext = csv

label = CSV

class gluonsqlhtmlExporterHTML(rows)Bases gluonsqlhtmlExportClass

content_type = texthtml

export()

file_ext = html

label = HTML

class gluonsqlhtmlExporterJSON(rows)Bases gluonsqlhtmlExportClass

content_type = applicationjson

export()

file_ext = json

98 Chapter 30 sqlhtml Module

web2py Documentation Release 2146-stable

label = JSON

class gluonsqlhtmlExporterTSV(rows)Bases gluonsqlhtmlExportClass

content_type = texttab-separated-values

export()

file_ext = csv

label = TSV

class gluonsqlhtmlExporterXML(rows)Bases gluonsqlhtmlExportClass

content_type = textxml

export()

file_ext = xml

label = XML

class gluonsqlhtmlFormWidgetBases object

Helper for SQLFORM to generate form input fields (widget) related to the fieldtype

classmethod widget(field value attributes)Generates the widget for the field

When serialized will provide an INPUT tag

bull id = tablename_fieldname

bull class = fieldtype

bull name = fieldname

Parameters

bull field ndash the field needing the widget

bull value ndash value

bull attributes ndash any other attributes to be applied

class gluonsqlhtmlIntegerWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlJSONWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates a TEXTAREA for JSON notation

see also FormWidgetwidget

class gluonsqlhtmlListWidgetBases gluonsqlhtmlStringWidget

classmethod widget(field value attributes)Generates an INPUT text tag

see also FormWidgetwidget

99

web2py Documentation Release 2146-stable

class gluonsqlhtmlMultipleOptionsWidgetBases gluonsqlhtmlOptionsWidget

classmethod widget(field value size=5 attributes)Generates a SELECT tag including OPTIONs (multiple options allowed)

see also FormWidgetwidget

Parameters size ndash optional param (default=5) to indicate how many rows must be shown

class gluonsqlhtmlOptionsWidgetBases gluonsqlhtmlFormWidget

static has_options(field)Checks if the field has selectable options

Parameters field ndash the field needing checking

Returns True if the field has options

classmethod widget(field value attributes)Generates a SELECT tag including OPTIONs (only 1 option allowed)

see also FormWidgetwidget

class gluonsqlhtmlPasswordWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates a INPUT password tag If a value is present it will be shown as a number of lsquorsquo not related tothe length of the actual value

see also FormWidgetwidget

class gluonsqlhtmlRadioWidgetBases gluonsqlhtmlOptionsWidget

classmethod widget(field value attributes)Generates a TABLE tag including INPUT radios (only 1 option allowed)

see also FormWidgetwidget

class gluonsqlhtmlSQLFORM(table record=None deletable=False linkto=None upload=Nonefields=None labels=None col3= submit_button=rsquoSubmitrsquodelete_label=rsquoCheck to deletersquo showid=True readonly=False com-ments=True keepopts=[] ignore_rw=False record_id=Noneformstyle=None buttons=[rsquosubmitrsquo] separator=None ex-tra_fields=None attributes)

Bases gluonhtmlFORM

SQLFORM is used to map a table (and a current record) into an HTML form

Given a Table like dbtable

Generates an insert form

SQLFORM(dbtable)

Generates an update form

record=dbtable[some_id]SQLFORM(dbtable record)

Generates an update with a delete button

100 Chapter 30 sqlhtml Module

web2py Documentation Release 2146-stable

SQLFORM(dbtable record deletable=True)

Parameters

bull table ndash Table object

bull record ndash either an int if the id is an int or the record fetched from the table

bull deletable ndash adds the delete checkbox

bull linkto ndash the URL of a controllerfunction to access referencedby records

bull upload ndash the URL of a controllerfunction to download an uploaded file

bull fields ndash a list of fields that should be placed in the form default is all

bull labels ndash a dictionary with labels for each field keys are the field names

bull col3 ndash a dictionary with content for an optional third column (right of each field) keys arefield names

bull submit_button ndash text to show in the submit button

bull delete_label ndash text to show next to the delete checkbox

bull showid ndash shows the id of the record

bull readonly ndash doesnrsquot allow for any modification

bull comments ndash show comments (stored in col3 or in Field definition)

bull ignore_rw ndash overrides readablewritable attributes

bull record_id ndash used to create session key against CSRF

bull formstyle ndash what to use to generate the form layout

bull buttons ndash override buttons as you please (will be also stored in formcustomsubmit)

bull separator ndash character as separator between labels and inputs

any named optional attribute is passed to the ltformgt tag for example _class _id _style _action _method etc

AUTOTYPES = lttype intgt (integer ltgluonvalidatorsIS_INT_IN_RANGE object at 0x7fcf10deb210gt) lttype floatgt (double ltgluonvalidatorsIS_FLOAT_IN_RANGE object at 0x7fcf10deb250gt) lttype unicodegt (string None) lttype boolgt (boolean None) lttype strgt (string None) lttype listgt (liststring None) lttype datetimedatetimegt (datetime ltgluonvalidatorsIS_DATETIME object at 0x7fcf10deb310gt) lttype datetimedategt (date ltgluonvalidatorsIS_DATE object at 0x7fcf10deb2d0gt)

FIELDKEY_DELETE_RECORD = delete_record

FIELDNAME_REQUEST_DELETE = delete_this_record

ID_LABEL_SUFFIX = __label

ID_ROW_SUFFIX = __row

accepts(request_vars session=None formname=rsquo(tablename)s(record_id)srsquo keepvalues=Noneonvalidation=None dbio=True hideerror=False detect_record_change=False kwargs)

Similar to FORMaccepts but also does insert update or delete in DAL If detect_record_change is Truethan

bull formrecord_changed = False (record is properly validatedsubmitted)

bull formrecord_changed = True (record cannot be submitted because changed)

If detect_record_change == False than

bull formrecord_changed = None

assert_status(status request_vars)

101

web2py Documentation Release 2146-stable

static build_query(fields keywords)

createform(xfields)

static dictform(dictionary kwargs)

static factory(fields attributes)Generates a SQLFORM for the given fields

Internally will build a non-database based data model to hold the fields

formstyles = bootstrap ltfunction formstyle_bootstrap at 0x7fcf10de99b0gt bootstrap3_inline ltfunction _inner at 0x7fcf10de9b90gt bootstrap3_stacked ltfunction formstyle_bootstrap3_stacked at 0x7fcf10de9a28gt divs ltfunction formstyle_divs at 0x7fcf10de9848gt inline ltfunction formstyle_inline at 0x7fcf10de98c0gt table2cols ltfunction formstyle_table2cols at 0x7fcf10de97d0gt table3cols ltfunction formstyle_table3cols at 0x7fcf10dcdde8gt ul ltfunction formstyle_ul at 0x7fcf10de9938gt

static grid(query fields=None field_id=None left=None headers= or-derby=None groupby=None searchable=True sortable=True pagi-nate=20 deletable=True editable=True details=True selectable=None cre-ate=True csv=True links=None links_in_grid=True upload=rsquoltdefaultgtrsquoargs=[] user_signature=True maxtextlengths= maxtextlength=20 on-validation=None onfailure=None oncreate=None onupdate=None on-delete=None sorter_icons=(ltgluonhtmlXML objectgt ltgluonhtmlXMLobjectgt) ui=rsquoweb2pyrsquo showbuttontext=True _class=rsquoweb2py_gridrsquo form-name=rsquoweb2py_gridrsquo search_widget=rsquodefaultrsquo advanced_search=True ig-nore_rw=False formstyle=None exportclasses=None formargs= cre-ateargs= editargs= viewargs= selectable_submit_button=rsquoSubmitrsquobuttons_placement=rsquorightrsquo links_placement=rsquorightrsquo noconfirm=Falsecache_count=None client_side_delete=False ignore_common_filters=Noneauto_pagination=True use_cursor=False)

static search_menu(fields search_options=None prefix=rsquow2prsquo)

static smartdictform(session name filename=None query=None kwargs)

static smartgrid(table constraints=None linked_tables=None links=None links_in_grid=Trueargs=None user_signature=True divider=rsquogtrsquo breadcrumbs_class=rdquokwargs)

Builds a system of SQLFORMgrid(s) between any referenced tables

Parameters

bull table ndash main table

bull constraints (dict) ndash lsquotablersquoquery that limits which records can be accessible

bull links (dict) ndash like lsquotablenamersquo[lambda row A( ) ] that will add buttons whentable tablename is displayed

bull linked_tables (list) ndash list of tables to be linked

Example

given you defined a model as

dbdefine_table(person Field(name) format=(name)s)dbdefine_table(dog

Field(name) Field(owner dbperson) format=(name)s)dbdefine_table(comment Field(body) Field(dog dbdog))if db(dbperson)isempty()

from gluoncontribpopulate import populatepopulate(dbperson 300)populate(dbdog 300)populate(dbcomment 1000)

102 Chapter 30 sqlhtml Module

web2py Documentation Release 2146-stable

in a controller you can do

authrequires_login()def index()

form=SQLFORMsmartgrid(db[requestargs(0) or person])return dict(form=form)

widgets = autocomplete ltclass gluonsqlhtmlAutocompleteWidgetgt blob None boolean ltclass gluonsqlhtmlBooleanWidgetgt checkboxes ltclass gluonsqlhtmlCheckboxesWidgetgt date ltclass gluonsqlhtmlDateWidgetgt datetime ltclass gluonsqlhtmlDatetimeWidgetgt decimal ltclass gluonsqlhtmlDecimalWidgetgt double ltclass gluonsqlhtmlDoubleWidgetgt integer ltclass gluonsqlhtmlIntegerWidgetgt json ltclass gluonsqlhtmlJSONWidgetgt list ltclass gluonsqlhtmlListWidgetgt multiple ltclass gluonsqlhtmlMultipleOptionsWidgetgt options ltclass gluonsqlhtmlOptionsWidgetgt password ltclass gluonsqlhtmlPasswordWidgetgt radio ltclass gluonsqlhtmlRadioWidgetgt string ltclass gluonsqlhtmlStringWidgetgt text ltclass gluonsqlhtmlTextWidgetgt time ltclass gluonsqlhtmlTimeWidgetgt upload ltclass gluonsqlhtmlUploadWidgetgt

class gluonsqlhtmlSQLTABLE(sqlrows linkto=None upload=None orderby=None headers=truncate=16 columns=None th_link=rdquo extracolumns=None se-lectid=None renderstyle=False cid=None colgroup=False at-tributes)

Bases gluonhtmlTABLE

Given with a Rows object as returned by a db()select() generates an html table with the rows

Parameters

bull sqlrows ndash the Rows object

bull linkto ndash URL (or lambda to generate a URL) to edit individual records

bull upload ndash URL to download uploaded files

bull orderby ndash Add an orderby link to column headers

bull headers ndash dictionary of headers to headers redefinions headers can also be a string to gen-erate the headers from data for now only headers=rdquofieldnamecapitalizerdquo headers=rdquolabelsrdquoand headers=None are supported

bull truncate ndash length at which to truncate text in table cells Defaults to 16 characters

bull columns ndash a list or dict contaning the names of the columns to be shown Defaults to all

bull th_link ndash base link to support orderby headers

bull extracolumns ndash a list of dicts

bull selectid ndash The id you want to select

bull renderstyle ndash Boolean render the style with the table

bull cid ndash use this cid for all links

bull colgroup ndash FIXME

Extracolumns example

[labelA(Extra _href=)class class name of the headerwidth width in pixels or contentlambda row rc A(Edit _href=editsrowid)selected False agregate class selected to this column]

style()

class gluonsqlhtmlStringWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates an INPUT text tag

see also FormWidgetwidget

103

web2py Documentation Release 2146-stable

class gluonsqlhtmlTextWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates a TEXTAREA tag

see also FormWidgetwidget

class gluonsqlhtmlTimeWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlUploadWidgetBases gluonsqlhtmlFormWidget

DEFAULT_WIDTH = 150px

DELETE_FILE = delete

GENERIC_DESCRIPTION = file download

ID_DELETE_SUFFIX = __delete

static is_image(value)Tries to check if the filename provided references to an image

Checking is based on filename extension Currently recognized gif png jp(e)g bmp

Parameters value ndash filename

classmethod represent(field value download_url=None)How to represent the file

bull with download url and if it is an image ltA href= gtltIMG gtltAgt

bull otherwise with download url ltA href= gtfileltAgt

bull otherwise file

Parameters

bull field ndash the field

bull value ndash the field value

bull download_url ndash url for the file download (default = None)

classmethod widget(field value download_url=None attributes)generates a INPUT file tag

Optionally provides an A link to the file including a checkbox so the file can be deleted

All is wrapped in a DIV

see also FormWidgetwidget

Parameters

bull field ndash the field

bull value ndash the field value

bull download_url ndash url for the file download (default = None)

gluonsqlhtmladd_class(a b)

104 Chapter 30 sqlhtml Module

web2py Documentation Release 2146-stable

gluonsqlhtmlform_factory(fields attributes)Generates a SQLFORM for the given fields

Internally will build a non-database based data model to hold the fields

gluonsqlhtmlformstyle_bootstrap(form fields)bootstrap 23x format form layout

gluonsqlhtmlformstyle_bootstrap3_inline_factory(col_label_size=3)bootstrap 3 horizontal form layout

Note Experimental

gluonsqlhtmlformstyle_bootstrap3_stacked(form fields)bootstrap 3 format form layout

Note Experimental

gluonsqlhtmlformstyle_divs(form fields)divs only

gluonsqlhtmlformstyle_inline(form fields)divs only but inline

gluonsqlhtmlformstyle_table2cols(form fields)2 column table

gluonsqlhtmlformstyle_table3cols(form fields)3 column table - default

gluonsqlhtmlformstyle_ul(form fields)unordered list

gluonsqlhtmlrepresent(field value record)

gluonsqlhtmlsafe_float(x)

gluonsqlhtmlsafe_int(x)

gluonsqlhtmlshow_if(cond)

105

web2py Documentation Release 2146-stable

106 Chapter 30 sqlhtml Module

CHAPTER 31

storage Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

Provides

bull List like list but returns None instead of IndexOutOfBounds

bull Storage like dictionary allowing also for objfoo for obj[lsquofoorsquo]

class gluonstorageListBases list

Like a regular python list but callable When a(i) is called if i is out of bounds returns None instead of IndexError

class gluonstorageStorageBases dict

A Storage object is like a dictionary except objfoo can be used in addition to obj[lsquofoorsquo] and setting objfoo =None deletes item foo

Example

gtgtgt o = Storage(a=1)gtgtgt print oa1

gtgtgt o[a]1

gtgtgt oa = 2gtgtgt print o[a]2

gtgtgt del oa

(continues on next page)

107

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt print oaNone

getfirst(key default=None)Returns the first value of a list or the value itself when given a requestvars style key

If the value is a list its first item will be returned otherwise the value will be returned as-is

Example output for a query string of x=abcampy=abcampy=def

gtgtgt request = Storage()gtgtgt requestvars = Storage()gtgtgt requestvarsx = abcgtgtgt requestvarsy = [abc def]gtgtgt requestvarsgetfirst(x)abcgtgtgt requestvarsgetfirst(y)abcgtgtgt requestvarsgetfirst(z)

getlast(key default=None)Returns the last value of a list or value itself when given a requestvars style key

If the value is a list the last item will be returned otherwise the value will be returned as-is

Simulated output with a query string of x=abcampy=abcampy=def

gtgtgt request = Storage()gtgtgt requestvars = Storage()gtgtgt requestvarsx = abcgtgtgt requestvarsy = [abc def]gtgtgt requestvarsgetlast(x)abcgtgtgt requestvarsgetlast(y)defgtgtgt requestvarsgetlast(z)

getlist(key)Returns a Storage value as a list

If the value is a list it will be returned as-is If object is None an empty list will be returned Otherwise[value] will be returned

Example output for a query string of x=abcampy=abcampy=def

gtgtgt request = Storage()gtgtgt requestvars = Storage()gtgtgt requestvarsx = abcgtgtgt requestvarsy = [abc def]gtgtgt requestvarsgetlist(x)[abc]gtgtgt requestvarsgetlist(y)[abc def]gtgtgt requestvarsgetlist(z)[]

class gluonstorageSettingsBases gluonstorageStorage

108 Chapter 31 storage Module

web2py Documentation Release 2146-stable

class gluonstorageMessages(T)Bases gluonstorageSettings

class gluonstorageStorageListBases gluonstorageStorage

Behaves like Storage but missing elements defaults to [] instead of None

gluonstorageload_storage(filename)

gluonstoragesave_storage(storage filename)

109

web2py Documentation Release 2146-stable

110 Chapter 31 storage Module

CHAPTER 32

streamer Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

321 Facilities to handle file streaming

gluonstreamerstream_file_or_304_or_206(static_file chunk_size=65536 request=Noneheaders= status=200 error_message=None)

gluonstreamerstreamer(stream chunk_size=65536 bytes=None)

111

web2py Documentation Release 2146-stable

112 Chapter 32 streamer Module

CHAPTER 33

template Module

This file is part of the web2py Web FrameworkLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)Author Thadeus BurgessContributors- Massimo Di Pierro for creating the original gluontemplatepy- Jonathan Lundell for extensively testing the regex on Jython- Limodou (creater of uliweb) who inspired the block-element support for web2py

331 Templating syntax

class gluontemplateBlockNode(name=rdquo pre_extend=False delimiters=(rsquorsquo rsquorsquo))Bases gluontemplateNode

Block Container

This Node can contain other Nodes and will render in a hierarchical order of when nodes were added

ie

block test This is default block test

end

append(node)Adds an element to the nodes

Parameters node ndash Node object or string to append

extend(other)Extends the list of nodes with another BlockNode class

Parameters other ndash BlockNode or Content object to extend from

113

web2py Documentation Release 2146-stable

output(blocks)Merges all nodes into a single string

Parameters blocks ndash Dictionary of blocks that are extending from this template

class gluontemplateContent(name=rsquoContentBlockrsquo pre_extend=False)Bases gluontemplateBlockNode

Parent Container ndash Used as the root level BlockNode

Contains functions that operate as such

Parameters name ndash Unique name for this BlockNode

append(node)Adds a node to list If it is a BlockNode then we assign a block for it

clear_content()

extend(other)Extends the objects list of nodes with another objects nodes

insert(other index=0)Inserts object at index

You may pass a list of objects and have them inserted

class gluontemplateDummyResponse

write(data escape=True)

class gluontemplateNOESCAPE(text)A little helper to avoid escaping

xml()

class gluontemplateNode(value=None pre_extend=False)Bases object

Basic Container Object

class gluontemplateSuperNode(name=rdquo pre_extend=False)Bases gluontemplateNode

class gluontemplateTemplateParser(text name=rsquoParserContainerrsquo context=path=rsquoviewsrsquo writer=rsquoresponsewritersquo lexers=delimiters=(rsquorsquo rsquorsquo) _super_nodes=[])

Bases object

Parse all blocks

Parameters

bull text ndash text to parse

bull context ndash context to parse in

bull path ndash folder path to templates

bull writer ndash string of writer class to use

bull lexers ndash dict of custom lexers to use

bull delimiters ndash for example (lsquolsquorsquorsquo)

114 Chapter 33 template Module

web2py Documentation Release 2146-stable

bull _super_nodes ndash a list of nodes to check for inclusion this should only be set byldquoselfextendrdquo It contains a list of SuperNodes from a child template that need to be han-dled

default_delimiters = ( )

extend(filename)Extends filename Anything not declared in a block defined by the parent will be placed in the parenttemplates include block

include(content filename)Includes filename here

parse(text)

r_multiline = lt_sreSRE_Pattern objectgt

r_tag = lt_sreSRE_Pattern objectgt

re_block = lt_sreSRE_Pattern objectgt

re_pass = lt_sreSRE_Pattern objectgt

re_unblock = lt_sreSRE_Pattern objectgt

reindent(text)Reindents a string of unindented python code

to_string()Returns the parsed template with correct indentation

Used to make it easier to port to python3

gluontemplateget_parsed(text)Returns the indented python code of text Useful for unit testing

gluontemplateoutput_aux(node blocks)

gluontemplateparse_template(filename path=rsquoviewsrsquo context= lexers= delimiters=(rsquorsquorsquorsquo))

Parameters

bull filename ndash can be a view filename in the views folder or an input stream

bull path ndash is the path of a views folder

bull context ndash is a dictionary of symbols used to render the template

bull lexers ndash dict of custom lexers to use

bull delimiters ndash opening and closing tags

gluontemplaterender(content=rsquohello worldrsquo stream=None filename=None path=None con-text= lexers= delimiters=(rsquorsquo rsquorsquo) writer=rsquoresponsewritersquo)

Generic render function

Parameters

bull content ndash default content

bull stream ndash file-like obj to read template from

bull filename ndash where to find template

bull path ndash base path for templates

bull context ndash env

331 Templating syntax 115

web2py Documentation Release 2146-stable

bull lexers ndash custom lexers to use

bull delimiters ndash opening and closing tags

bull writer ndash where to inject the resulting stream

Example

gtgtgt render()hello worldgtgtgt render(content=abc)abcgtgtgt render(content=abc)abcgtgtgt render(content=abc)abcgtgtgt render(content=anbc)anbcgtgtgt render(content=abcde)abcdegtgtgt render(content=anc)ancgtgtgt render(content=ac)acgtgtgt render(content=for i in range(a)=iltbr gtpassrarr˓context=dict(a=5))0ltbr gt1ltbr gt2ltbr gt3ltbr gt4ltbr gtgtgtgt render(content=for i in range(a)=iltbr gtpassrarr˓context=dict(a=5)delimiters=())0ltbr gt1ltbr gt2ltbr gt3ltbr gt4ltbr gtgtgtgt render(content==hellonworld)hellonworldgtgtgt render(content=for i in range(3)n=inpass)012

116 Chapter 33 template Module

CHAPTER 34

tools Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

341 Auth Mail PluginManager and various utilities

class gluontoolsMail(server=None sender=None login=None tls=True)Bases object

Class for configuring and sending emails with alternative text html body multiple attachments and encryptionsupport

Works with SMTP and Google App Engine

Parameters

bull server ndash SMTP server address in addressport notation

bull sender ndash sender email address

bull login ndash sender login name and password in loginpassword notation or None if no authen-tication is required

bull tls ndash enablesdisables encryption (True by default)

In Google App Engine use

server=gae

For sake of backward compatibility all fields are optional and default to None however to be able to send emailsat least server and sender must be specified They are available under following fields

117

web2py Documentation Release 2146-stable

mailsettingsservermailsettingssendermailsettingsloginmailsettingstimeout = 60 seconds (default)

When server is lsquologgingrsquo email is logged but not sent (debug mode)

Optionally you can use PGP encryption or X509

mailsettingscipher_type = Nonemailsettingsgpg_home = Nonemailsettingssign = Truemailsettingssign_passphrase = Nonemailsettingsencrypt = Truemailsettingsx509_sign_keyfile = Nonemailsettingsx509_sign_certfile = Nonemailsettingsx509_sign_chainfile = Nonemailsettingsx509_nocerts = Falsemailsettingsx509_crypt_certfiles = None

cipher_type Nonegpg - need a python-pyme package and gpgme libx509 - smime

gpg_home you can set a GNUPGHOME environment variableto specify home of gnupg

sign sign the message (True or False)sign_passphrase passphrase for key signingencrypt encrypt the message (True or False) It defaults

to True x509 only

x509_sign_keyfile the signers private key filename orstring containing the key (PEM format)

x509_sign_certfile the signers certificate filename orstring containing the cert (PEM format)

x509_sign_chainfile sets the optional all-in-one file where youcan assemble the certificates of CertificationAuthorities (CA) which form the certificatechain of email certificate It can be astring containing the certs to (PEM format)

x509_nocerts if True then no attached certificate in mailx509_crypt_certfiles the certificates file or strings to encrypt

the messages with can be a file name string or a list of file names strings (PEM format)

Examples

Create Mail object with authentication data for remote server

mail = Mail(examplecom25 meexamplecom mepassword)

Notice for GAE users attachments have an automatic content_id=rsquoattachment-irsquo where i is progressive num-ber in this way the can be referenced from the HTML as ltimg src=rdquocidattachment-0rdquo gt etc

118 Chapter 34 tools Module

web2py Documentation Release 2146-stable

class Attachment(payload filename=None content_id=None content_type=Noneencoding=rsquoutf-8rsquo)

Bases emailmimebaseMIMEBase

Email attachment

Parameters

bull payload ndash path to file or file-like object with read() method

bull filename ndash name of the attachment stored in message if set to None it will be fetchedfrom payload path file-like object payload must have explicit filename specified

bull content_id ndash id of the attachment automatically contained within lt and gt

bull content_type ndash content type of the attachment if set to None it will be fetched fromfilename using gluoncontenttype module

bull encoding ndash encoding of all strings passed to this function (except attachment body)

Content ID is used to identify attachments within the html body in example attached image with contentID lsquophotorsquo may be used in html message as a source of img tag ltimg src=rdquocidphotordquo gt

Example Create attachment from text file

attachment = MailAttachment(pathtofiletxt)

Content-Type textplainMIME-Version 10Content-Disposition attachment filename=filetxtContent-Transfer-Encoding base64

SOMEBASE64CONTENT=

Create attachment from image file with custom filename and cid

attachment = MailAttachment(pathtofilepngfilename=photopngcontent_id=photo)

Content-Type imagepngMIME-Version 10Content-Disposition attachment filename=photopngContent-Id ltphotogtContent-Transfer-Encoding base64

SOMEOTHERBASE64CONTENT=

send(to subject=rsquo[no subject]rsquo message=rsquo[no message]rsquo attachments=None cc=None bcc=Nonereply_to=None sender=None encoding=rsquoutf-8rsquo raw=False headers= from_address=Nonecipher_type=None sign=None sign_passphrase=None encrypt=None x509_sign_keyfile=Nonex509_sign_chainfile=None x509_sign_certfile=None x509_crypt_certfiles=Nonex509_nocerts=None)

Sends an email using data specified in constructor

Parameters

bull to ndash list or tuple of receiver addresses will also accept single object

bull subject ndash subject of the email

bull message ndash email body text depends on type of passed object

341 Auth Mail PluginManager and various utilities 119

web2py Documentation Release 2146-stable

ndash if 2-list or 2-tuple is passed first element will be source of plain text while second ofhtml text

ndash otherwise object will be the only source of plain text and html source will be set toNone

If text or html source is

ndash None content part will be ignored

ndash string content part will be set to it

ndash file-like object content part will be fetched from it using itrsquos read() method

bull attachments ndash list or tuple of MailAttachment objects will also accept single object

bull cc ndash list or tuple of carbon copy receiver addresses will also accept single object

bull bcc ndash list or tuple of blind carbon copy receiver addresses will also accept single object

bull reply_to ndash address to which reply should be composed

bull encoding ndash encoding of all strings passed to this method (including message bodies)

bull headers ndash dictionary of headers to refine the headers just before sending mail eg lsquoX-Mailerrsquo lsquoweb2py mailerrsquo

bull from_address ndash address to appear in the lsquoFromrsquo header this is not the envelopesender If not specified the sender will be used

bull cipher_type ndash gpg - need a python-pyme package and gpgme lib x509 - smime

bull gpg_home ndash you can set a GNUPGHOME environment variable to specify home ofgnupg

bull sign ndash sign the message (True or False)

bull sign_passphrase ndash passphrase for key signing

bull encrypt ndash encrypt the message (True or False) It defaults to True x509 only

bull x509_sign_keyfile ndash the signers private key filename or string containing the key(PEM format)

bull x509_sign_certfile ndash the signers certificate filename or string containing the cert(PEM format)

bull x509_sign_chainfile ndash sets the optional all-in-one file where you can assemblethe certificates of Certification Authorities (CA) which form the certificate chain of emailcertificate It can be a string containing the certs to (PEM format)

bull x509_nocerts ndash if True then no attached certificate in mail

bull x509_crypt_certfiles ndash the certificates file or strings to encrypt the messages withcan be a file name string or a list of file names strings (PEM format)

Examples

Send plain text message to single address

mailsend(youexamplecomMessage subjectPlain text body of the message)

120 Chapter 34 tools Module

web2py Documentation Release 2146-stable

Send html message to single address

mailsend(youexamplecomMessage subjectlthtmlgtPlain text body of the messagelthtmlgt)

Send text and html message to three addresses (two in cc)

mailsend(youexamplecomMessage subject(Plain text body lthtmlgthtml bodylthtmlgt)cc=[other1examplecom other2examplecom])

Send html only message with image attachment available from the message by lsquophotorsquo content id

mailsend(youexamplecomMessage subject(None lthtmlgtltimg src=cidphoto gtlthtmlgt)MailAttachment(pathtophotojpg

content_id=photo))

Send email with two attachments and no body text

mailsend(youexamplecomMessage subjectNone[MailAttachment(pathtofistfile)MailAttachment(pathtosecondfile)])

Returns True on success False on failure

Before return method updates two objectrsquos fields

bull selfresult return value of smtplibSMTPsendmail() or GAErsquos mailsend_mail() method

bull selferror Exception message or None if above was successful

class gluontoolsAuth(environment=None db=None mailer=True hmac_key=None con-troller=rsquodefaultrsquo function=rsquouserrsquo cas_provider=None signature=Truesecure=False csrf_prevention=True propagate_extension=Noneurl_index=None jwt=None host_names=None)

Bases object

accessible_query(name table user_id=None)Returns a query with all accessible records for user_id or the current logged in user this method does notwork on GAE because uses JOIN and IN

Example

Use as

db(authaccessible_query(read dbmytable))select(dbmytableALL)

add_group(role description=rdquo)Creates a group associated to a role

add_membership(group_id=None user_id=None role=None)Gives user_id membership of group_id or role if user is None than user_id is that of current logged in user

341 Auth Mail PluginManager and various utilities 121

web2py Documentation Release 2146-stable

add_permission(group_id name=rsquoanyrsquo table_name=rdquo record_id=0)Gives group_id lsquonamersquo access to lsquotable_namersquo and lsquorecord_idrsquo

allows_jwt(otherwise=None)

static archive(form archive_table=None current_record=rsquocurrent_recordrsquoarchive_current=False fields=None)

If you have a table (dbmytable) that needs full revision history you can just do

form = crudupdate(dbmytable myrecord onaccept=autharchive)

or

form = SQLFORM(dbmytable myrecord)process(onaccept=autharchive)

crudarchive will define a new table ldquomytable_archiverdquo and store a copy of the current record (ifarchive_current=True) or a copy of the previous record (if archive_current=False) in the newly createdtable including a reference to the current record

fields allows to specify extra fields that need to be archived

If you want to access such table you need to define it yourself in a model

dbdefine_table(mytable_archiveField(current_record dbmytable)dbmytable)

Notice such table includes all fields of dbmytable plus one current_record crudarchive does not times-tamp the stored record unless your original table has a fields like

dbdefine_table(Field(saved_on datetime

default=requestnow update=requestnow writable=False)Field(saved_by authuser

default=authuser_id update=authuser_id writable=False)

there is nothing special about these fields since they are filled before the record is archived

If you want to change the archive table name and the name of the reference field you can do for example

dbdefine_table(myhistoryField(parent_record dbmytable) dbmytable)

and use it as

form = crudupdate(dbmytable myrecordonaccept=lambda formcrudarchive(form

archive_table=dbrarr˓myhistory

current_record=parent_rarr˓record))

basic(basic_auth_realm=False)Performs basic login

Parameters basic_auth_realm ndash optional basic http authentication realm Can take str orunicode or function or callable or boolean

reads currentrequestenvhttp_authorization and returns basic_allowedbasic_accepteduser

122 Chapter 34 tools Module

web2py Documentation Release 2146-stable

if basic_auth_realm is defined is a callable itrsquos return value is used to set the basic authentication realm ifitrsquos a string its content is used instead Otherwise basic authentication realm is set to the application nameIf basic_auth_realm is None or False (the default) the behavior is to skip sending any challenge

bulk_register(max_emails=100)Creates a form for ther user to send invites to other users to join

cas_login(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt version=2)

cas_validate(version=2 proxy=False)

change_password(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form that lets the user change password

confirm_registration(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form to confirm user registration

default_messages = access_denied Insufficient privileges add_group_log Group (group_id)s created add_membership_log None add_permission_log None bulk_invite_body You have been invited to join (site)s click (link)s to complete the process bulk_invite_subject Invitation to join (site)s change_password_log User (id)s Password changed del_group_log Group (group_id)s deleted del_membership_log None del_permission_log None delete_label Check to delete email_sent Email sent email_taken This email already has an account email_verified Email verified function_disabled Function disabled group_description Group uniquely assigned to user (id)s has_membership_log None has_permission_log None impersonate_log User (id)s is impersonating (other_id)s invalid_email Invalid email invalid_login Invalid login invalid_password Invalid password invalid_reset_password Invalid reset password invalid_two_factor_code Incorrect code 0 more attempt(s) remaining invalid_user Invalid user invalid_username Invalid username is_empty Cannot be empty label_client_ip Client IP label_description Description label_email E-mail label_first_name First name label_group_id Group ID label_last_name Last name label_name Name label_origin Origin label_password Password label_record_id Record ID label_registration_id Registration identifier label_registration_key Registration key label_remember_me Remember me (for 30 days) label_reset_password_key Reset Password key label_role Role label_table_name Object or table name label_time_stamp Timestamp label_two_factor Authentication code label_user_id User ID label_username Username logged_in Logged in logged_out Logged out login_button Log In login_disabled Login disabled by administrator login_failed_log None login_log User (id)s Logged-in logout_log User (id)s Logged-out mismatched_password Password fields dont match new_password New password new_password_sent A new password was emailed to you old_password Old password password_change_button Change password password_changed Password changed password_reset_button Request reset password profile_log User (id)s Profile updated profile_save_button Apply changes profile_updated Profile updated register_button Sign Up register_log User (id)s Registered registration_pending Registration is pending approval registration_successful Registration successful registration_verifying Registration needs verification reset_password Click on the link (link)s to reset your password reset_password_log User (id)s Password reset reset_password_subject Password reset retrieve_password Your password is (password)s retrieve_password_log User (id)s Password retrieved retrieve_password_subject Password retrieve retrieve_two_factor_code Your temporary login code is 0 retrieve_two_factor_code_subject Two-step Login Authentication Code retrieve_username Your username is (username)s retrieve_username_log User (id)s Username retrieved retrieve_username_subject Username retrieve submit_button Submit two_factor_comment This code was emailed to you and is required for login unable_send_email Unable to send email unable_to_send_email Unable to send email username_sent Your username was emailed to you username_taken Username already taken verify_email Welcome (username)s Click on the link (link)s to verify your email verify_email_log User (id)s Verification email sent verify_email_subject Email verification verify_password Verify Password verify_password_comment please input your password againClass for authentication authorization role based access control

Includes

bull registration and profile

bull login and logout

bull username and password retrieval

bull event logging

bull role creation and assignment

bull user defined grouprole based permission

Parameters

bull environment ndash is there for legacy but unused (awful)

bull db ndash has to be the database where to create tables for authentication

bull mailer ndash Mail( ) or None (no mailer) or True (make a mailer)

bull hmac_key ndash can be a hmac_key or hmac_key=Authget_or_create_key()

bull controller ndash (where is the user action)

bull cas_provider ndash (delegate authentication to the URL CAS2)

Authentication Example

from gluoncontributils import mail=Mail()mailsettingsserver=smtpgmailcom587mailsettingssender=yousomewherecommailsettingslogin=usernamepasswordauth=Auth(db)authsettingsmailer=mail authsettings=authdefine_tables()def authentication()

return dict(form=auth())

341 Auth Mail PluginManager and various utilities 123

web2py Documentation Release 2146-stable

Exposes

bull http applicationcontrollerauthenticationlogin

bull http applicationcontrollerauthenticationlogout

bull http applicationcontrollerauthenticationregister

bull http applicationcontrollerauthenticationverify_email

bull http applicationcontrollerauthenticationretrieve_username

bull http applicationcontrollerauthenticationretrieve_password

bull http applicationcontrollerauthenticationreset_password

bull http applicationcontrollerauthenticationprofile

bull http applicationcontrollerauthenticationchange_password

On registration a group with role=new_userid is created and user is given membership of this group

You can create a group with

group_id=authadd_group(Manager can access the manage action)authadd_permission(group_id access to manage)

Here ldquoaccess to managerdquo is just a user defined string You can give access to a user

authadd_membership(group_id user_id)

If user id is omitted the logged in user is assumed

Then you can decorate any action

authrequires_permission(access to manage)def manage()

return dict()

You can restrict a permission to a specific table

authadd_permission(group_id edit dbsometable)authrequires_permission(edit dbsometable)

Or to a specific record

authadd_permission(group_id edit dbsometable 45)authrequires_permission(edit dbsometable 45)

If authorization is not granted calls

authsettingson_failed_authorization

Other options

authsettingsmailer=Noneauthsettingsexpiration=3600 seconds

these are messages that can be customized

124 Chapter 34 tools Module

web2py Documentation Release 2146-stable

default_settings = allow_basic_login False allow_basic_login_only False allow_delete_accounts False alternate_requires_registration False auth_manager_role None auth_two_factor_enabled False auth_two_factor_tries_left 3 bulk_register_enabled False captcha None cas_maps None client_side True create_user_groups user_(id)s email_case_sensitive True everybody_group_id None expiration 3600 formstyle None hideerror False keep_session_onlogin True keep_session_onlogout False label_separator None logging_enabled True login_after_password_change True login_after_registration False login_captcha None login_email_validate True login_userfield None logout_onlogout None long_expiration 2592000 manager_actions multi_login False on_failed_authentication ltfunction ltlambdagt at 0x7fcf0cf9f578gt ondelete CASCADE password_field password password_min_length 4 pre_registration_div None prevent_open_redirect_attacks True prevent_password_reset_attacks True profile_fields None register_captcha None register_fields None register_verify_password True registration_requires_approval False registration_requires_verification False remember_me_form True renew_session_onlogin True renew_session_onlogout True reset_password_requires_verification False retrieve_password_captcha None retrieve_username_captcha None showid False table_cas None table_cas_name auth_cas table_event None table_event_name auth_event table_group None table_group_name auth_group table_membership None table_membership_name auth_membership table_permission None table_permission_name auth_permission table_token_name auth_token table_user None table_user_name auth_user two_factor_authentication_group None update_fields [email] use_username False username_case_sensitive True wiki ltStorage gt

define_signature()

define_tables(username=None signature=None enable_tokens=False migrate=Nonefake_migrate=None)

To be called unless tables are defined manually

Examples

Use as

defines all needed tables and table files myprefix_auth_usertable authdefine_tables(migrate=myprefix_)

defines all needed tables without migrationtable filesauthdefine_tables(migrate=False)

del_group(group_id)Deletes a group

del_membership(group_id=None user_id=None role=None)Revokes membership from group_id to user_id if user_id is None than user_id is that of current logged inuser

del_permission(group_id name=rsquoanyrsquo table_name=rdquo record_id=0)Revokes group_id lsquonamersquo access to lsquotable_namersquo and lsquorecord_idrsquo

email_registration(subject body user)Sends and email invitation to a user informing they have been registered with the application

email_reset_password(user)

enable_record_versioning(tables archive_db=None archive_names=rsquo(tablename)s_archiversquocurrent_record=rsquocurrent_recordrsquo current_record_label=None)

Used to enable full record versioning (including auth tables)

auth = Auth(db)authdefine_tables(signature=True) define our own tablesdbdefine_table(mythingField(name)authsignature)authenable_record_versioning(tables=db)

tables can be the db (all table) or a list of tables only tables with modified_by and modified_on fiels (ascreated by authsignature) will have versioning Old record versions will be in table lsquomything_archiversquoautomatically defined

when you enable enable_record_versioning records are never deleted but marked with is_active=False

enable_record_versioning enables a common_filter for every table that filters out records with is_active =False

Note If you use authenable_record_versioning do not use autharchive or you will end up with dupli-cates autharchive does explicitly what enable_record_versioning does automatically

static get_or_create_key(filename=None alg=rsquosha512rsquo)

341 Auth Mail PluginManager and various utilities 125

web2py Documentation Release 2146-stable

get_or_create_user(keys update_fields=[rsquoemailrsquo] login=True get=True)Used for alternate login methods If the user exists already then password is updated If the user doesnrsquotyet exist then they are created

get_vars_next()

groups()Displays the groups and their roles for the logged in user

has_membership(group_id=None user_id=None role=None)Checks if user is member of group_id or role

has_permission(name=rsquoanyrsquo table_name=rdquo record_id=0 user_id=None group_id=None)Checks if user_id or current logged in user is member of a group that has lsquonamersquo permission on lsquota-ble_namersquo and lsquorecord_idrsquo if group_id is passed it checks whether the group has the permission

here()

id_group(role)Returns the group_id of the group specified by the role

impersonate(user_id=ltfunction ltlambdagtgt)To use this make a POST to http impersonate requestpost_varsuser_id=ltidgt

Set requestpost_varsuser_id to 0 to restore original user

requires impersonator is logged in and

has_permission(impersonate auth_user user_id)

is_impersonating()

is_logged_in()Checks if the user is logged in and returns TrueFalse If so user is in authuser as well as in ses-sionauthuser

jwt()To use JWT authentication 1) instantiate auth with

auth = Auth(db jwt = secret_keysecret)

where lsquosecretrsquo is your own secret string

2 Decorate functions that require login but should accept the JWT token credentials

authallows_jwt()authrequires_login()def myapi() return hello s authuseremail

Notice jwt is allowed but not required if user is logged in myapi is accessible

3 Use it

Now API users can obtain a token with

http appdefaultuserjwtusername= amppassword=

(returns json object with a token attribute) API users can refresh an existing token with

http appdefaultuserjwttoken=

they can authenticate themselves when calling http myapi by injecting a header

Authorization Bearer ltthe jwt tokengt

126 Chapter 34 tools Module

web2py Documentation Release 2146-stable

Any additional attributes in the jwt argument of Auth() below

auth = Auth(db jwt = )

are passed to the constructor of class AuthJWT Look there for documentation

log_event(description vars=None origin=rsquoauthrsquo)

Examples

Use as

authlog_event(description=this happened origin=auth)

login(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a login form

login_bare(username password)Logins user as specified by username (or email) and password

login_user(user)Logins the user = dbauth_user(id)

logout(next=ltfunction ltlambdagtgt onlogout=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)Logouts and redirects to login

logout_bare()

manage_tokens()

navbar(prefix=rsquoWelcomersquo action=None separators=(rsquo [ rsquo rsquo | rsquo rsquo ] rsquo) user_identifier=ltfunctionltlambdagtgt referrer_actions=ltfunction ltlambdagtgt mode=rsquodefaultrsquo)

Navbar with support for more templates This uses some code from the old navbar

Parameters mode ndash see options for list of

not_authorized()You can change the view for this page to make it look as you like

profile(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form that lets the user change hisher profile

random_password()

register(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a registration form

register_bare(fields)Registers a user as specified by username (or email) and a raw password

request_reset_password(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgtonaccept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form to reset the user password

requires(condition requires_login=True otherwise=None)Decorator that prevents access to action if not logged in

requires_login(otherwise=None)Decorator that prevents access to action if not logged in

341 Auth Mail PluginManager and various utilities 127

web2py Documentation Release 2146-stable

requires_login_or_token(otherwise=None)

requires_membership(role=None group_id=None otherwise=None)Decorator that prevents access to action if not logged in or if user logged in is not a member of group_idIf role is provided instead of group_id then the group_id is calculated

requires_permission(name table_name=rdquo record_id=0 otherwise=None)Decorator that prevents access to action if not logged in or if user logged in is not a member of any group(role) that has lsquonamersquo access to lsquotable_namersquo lsquorecord_idrsquo

requires_signature(otherwise=None hash_vars=True)Decorator that prevents access to action if not logged in or if user logged in is not a member of group_idIf role is provided instead of group_id then the group_id is calculated

reset_password(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form to reset the user password

reset_password_deprecated(next=ltfunction ltlambdagtgt onvalidation=ltfunctionltlambdagtgt onaccept=ltfunction ltlambdagtgt log=ltfunctionltlambdagtgt)

Returns a form to reset the user password (deprecated)

retrieve_password(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

retrieve_username(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form to retrieve the user username (only if there is a username field)

run_login_onaccept()

select_host(host host_names=None)checks that host is valid ie in the list of glob host_names if the host is missing then is it selects the firstentry from host_names read more here httpsgithubcomweb2pyweb2pyissues1196

table_cas()

table_event()

table_group()

table_membership()

table_permission()

table_token()

table_user()

update_groups()

url(f=None args=None vars=None scheme=False)

user_group(user_id=None)Returns the group_id of the group uniquely associated to this user ie role=user[user_id]

user_group_role(user_id=None)

user_iduserid or None

verify_email(next=ltfunction ltlambdagtgt onaccept=ltfunction ltlambdagtgt log=ltfunctionltlambdagtgt)

Action used to verify the registration email

128 Chapter 34 tools Module

web2py Documentation Release 2146-stable

when_is_logged_in_bypass_next_in_url(next session)This function should be use when someone want to avoid asking for user credentials when loaded pagecontains ldquouserlogin_next=NEXT_COMPONENTrdquo in the URL is refresh but user is already authenti-cated

wiki(slug=None env=None render=rsquomarkminrsquo manage_permissions=False force_prefix=rdquo re-strict_search=False resolve=True extra=None menu_groups=None templates=None mi-grate=True controller=None function=None force_render=False groups=None)

wikimenu()To be used in menupy for app wide wiki menus

class gluontoolsRecaptcha(request=None public_key=rdquo private_key=rdquo use_ssl=False er-ror=None error_message=rsquoinvalidrsquo label=rsquoVerifyrsquo options=rdquocomment=rdquo ajax=False)

Bases gluonhtmlDIV

Examples

Use as

form = FORM(Recaptcha(public_key= private_key=))

or

form = SQLFORM()formappend(Recaptcha(public_key= private_key=))

API_SERVER = httpwwwgooglecomrecaptchaapi

API_SSL_SERVER = httpswwwgooglecomrecaptchaapi

VERIFY_SERVER = httpwwwgooglecomrecaptchaapiverify

xml()generates the xml for this component

class gluontoolsRecaptcha2(request=None public_key=rdquo private_key=rdquo er-ror_message=rsquoinvalidrsquo label=rsquoVerifyrsquo options=None com-ment=rdquo)

Bases gluonhtmlDIV

Experimental Creates a DIV holding the newer Recaptcha from Google (v2)

Parameters

bull request ndash the request If not passed uses current request

bull public_key ndash the public key Google gave you

bull private_key ndash the private key Google gave you

bull error_message ndash the error message to show if verification fails

bull label ndash the label to use

bull options (dict) ndash takes these parameters

ndash hl

ndash theme

ndash type

341 Auth Mail PluginManager and various utilities 129

web2py Documentation Release 2146-stable

ndash tabindex

ndash callback

ndash expired-callback

see httpsdevelopersgooglecomrecaptchadocsdisplay for docs about those

bull comment ndash the comment

Examples

Use as

form = FORM(Recaptcha2(public_key= private_key=))

or

form = SQLFORM()formappend(Recaptcha2(public_key= private_key=))

to protect the login page instead use

from gluontools import Recaptcha2authsettingscaptcha = Recaptcha2(request public_key= private_key=)

API_URI = httpswwwgooglecomrecaptchaapijs

VERIFY_SERVER = httpswwwgooglecomrecaptchaapisiteverify

xml()generates the xml for this component

class gluontoolsCrud(environment db=None controller=rsquodefaultrsquo)Bases object

static archive(form archive_table=None current_record=rsquocurrent_recordrsquo)

create(table next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt message=ltfunction ltlambdagtgt form-name=ltfunction ltlambdagtgt attributes)

delete(table record_id next=ltfunction ltlambdagtgt message=ltfunction ltlambdagtgt)

get_format(field)

get_query(field op value refsearch=False)

has_permission(name table record=0)

log_event(message vars)

read(table record)

rows(table query=None fields=None orderby=None limitby=None)

search(tables args)Creates a search form and its results for a table rubric Examples

Use as

130 Chapter 34 tools Module

web2py Documentation Release 2146-stable

form results = crudsearch(dbtestqueries = [equals not equal contains]query_labels=equalsEquals

not equalNot equalfields = [idchildren]field_labels =

idIDchildrenChildrenzero=Please choosequery = (dbtestid gt 0)amp(dbtestid = 3) )

select(table query=None fields=None orderby=None limitby=None headers=None attr)

tables()

update(table record next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt ondelete=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgtmessage=ltfunction ltlambdagtgt deletable=ltfunction ltlambdagtgt formname=ltfunctionltlambdagtgt attributes)

url(f=None args=None vars=None)This should point to the controller that exposes download and crud

class gluontoolsService(environment=None)Bases object

exception JsonRpcException(code info)Bases exceptionsException

amfrpc(f)

Example

Use as

service = Service()serviceamfrpcdef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget httpappdefaultcallamfrpcmyfunctiona=helloampb=world

amfrpc3(domain=rsquodefaultrsquo)

Example

Use as

service = Service()serviceamfrpc3(domain)def myfunction(a b)

return a + bdef call()

return service()

341 Auth Mail PluginManager and various utilities 131

web2py Documentation Release 2146-stable

Then call it with

wget http appdefaultcallamfrpc3myfunctiona=helloampb=world

csv(f)

Example

Use as

service = Service()servicecsvdef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget httpappdefaultcallcsvmyfunctiona=3ampb=4

error()

json(f)

Example

Use as

service = Service()servicejsondef myfunction(a b)

return [a b]def call()

return service()

Then call it with

wget http appdefaultcalljsonmyfunctiona=helloampb=world

jsonrpc(f)

Example

Use as

service = Service()servicejsonrpcdef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget http appdefaultcalljsonrpcmyfunctiona=helloampb=world

132 Chapter 34 tools Module

web2py Documentation Release 2146-stable

jsonrpc2(f)

Example

Use as

service = Service()servicejsonrpc2def myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget ndashpost-data lsquoldquojsonrpcrdquo ldquo20rdquo ldquoidrdquo 1 ldquomethodrdquo ldquomyfunctionrdquo ldquoparamsrdquo ldquoardquo 1 ldquobrdquo2rsquo http appdefaultcalljsonrpc2

jsonrpc_errors = -32700 (Parse error Invalid JSON was received by the server An error occurred on the server while parsing the JSON text) -32603 (Internal error Internal JSON-RPC error) -32602 (Invalid params Invalid method parameter(s)) -32601 (Method not found The method does not exist is not available) -32600 (Invalid Request The JSON sent is not a valid Request object) -32099 (Server error Reserved for implementation-defined server-errors)

rss(f)

Example

Use as

service = Service()servicerssdef myfunction()

return dict(title= link= description=created_on= entries=[dict(title= link=

description= created_on=])def call()

return service()

Then call it with

wget http appdefaultcallrssmyfunction

run(f)

Example

Use as

service = Service()servicerundef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget httpappdefaultcallrunmyfunctiona=3ampb=4

341 Auth Mail PluginManager and various utilities 133

web2py Documentation Release 2146-stable

serve_amfrpc(version=0)

serve_csv(args=None)

serve_json(args=None)

serve_jsonrpc()

serve_jsonrpc2(data=None batch_element=False)

serve_rss(args=None)

serve_run(args=None)

serve_soap(version=rsquo11rsquo)

serve_xml(args=None)

serve_xmlrpc()

soap(name=None returns=None args=None doc=None)

Example

Use as

service = Service()servicesoap(MyFunctionreturns=resultintargs=aintbint)def myfunction(a b)

return a + bdef call()

return service()

Then call it with

from gluoncontribpysimplesoapclient import SoapClientclient = SoapClient(wsdl=httpappdefaultcallsoapWSDL)response = clientMyFunction(a=1b=2)return response[result]

It also exposes online generated documentation and xml example messages athttp appdefaultcallsoap

xml(f)

Example

Use as

service = Service()servicexmldef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget httpappdefaultcallxmlmyfunctiona=3ampb=4

134 Chapter 34 tools Module

web2py Documentation Release 2146-stable

xmlrpc(f)

Example

Use as

service = Service()servicexmlrpcdef myfunction(a b)

return a + bdef call()

return service()

The call it with

wget http appdefaultcallxmlrpcmyfunctiona=helloampb=world

class gluontoolsWiki(auth env=None render=rsquomarkminrsquo manage_permissions=Falseforce_prefix=rdquo restrict_search=False extra=None menu_groups=Nonetemplates=None migrate=True controller=None function=Nonegroups=None)

Bases object

automenu()adds the menu if not present

can_edit(page=None)

can_manage()

can_read(page)

can_search()

can_see_menu()

cloud()

static component(text)In wiki docs allows componentcontrollerfunctionargs which renders as a LOAD( ajax=True)

create()

edit(slug from_template=0)

editmedia(slug)

everybody = everybody

first_paragraph(page)

fix_hostname(body)

get_renderer()

html_render(page)

markmin_base(body)

markmin_render(page)

media(id)

menu(controller=rsquodefaultrsquo function=rsquoindexrsquo)

341 Auth Mail PluginManager and various utilities 135

web2py Documentation Release 2146-stable

not_authorized(page=None)

pages()

preview(render)

read(slug force_render=False)

render_tags(tags)

rows_page = 25

search(tags=None query=None cloud=True preview=True limitby=(0 100) orderby=None)

class gluontoolsPluginManager(plugin=None defaults)Bases object

Plugin Manager is similar to a storage object but it is a single level singleton This means that multiple instanceswithin the same thread share the same attributes Its constructor is also special The first argument is the nameof the plugin you are defining The named arguments are parameters needed by the plugin with default valuesIf the parameters were previous defined the old values are used

Example

in some general configuration file

plugins = PluginManager()pluginsmeparam1=3

within the plugin model

_ = PluginManager(meparam1=5param2=6param3=7)

where the plugin is used

gtgtgt print pluginsmeparam13gtgtgt print pluginsmeparam26gtgtgt pluginsmeparam3 = 8gtgtgt print pluginsmeparam38

Here are some tests

gtgtgt a=PluginManager()gtgtgt ax=6gtgtgt b=PluginManager(check)gtgtgt print bx6gtgtgt b=PluginManager() reset settingsgtgtgt print bxltStorage gtgtgtgt bx=7gtgtgt print ax7gtgtgt ayz=8gtgtgt print byz8

(continues on next page)

136 Chapter 34 tools Module

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt test_thread_separation()5gtgtgt plugins=PluginManager(medb=mydb)gtgtgt print pluginsmedbmydbgtgtgt print me in pluginsTruegtgtgt print pluginsmeinstalledTrue

instances =

keys()

gluontoolsfetch(url data=None headers=None cookie= user_agent=rsquoMozilla50rsquo)

gluontoolsgeocode(address)

gluontoolsreverse_geocode(lat lng lang=None)Try to get an approximate address for a given latitude longitude

gluontoolsprettydate(d T=ltfunction ltlambdagtgt utc=False)

341 Auth Mail PluginManager and various utilities 137

web2py Documentation Release 2146-stable

138 Chapter 34 tools Module

CHAPTER 35

utf8 Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)Created by Vladyslav Kozlovskyy (Ukraine) ltdbdevelopcopygmailcomgtfor Web2py project

351 Utilities and class for UTF8 strings managing

class gluonutf8Utf8Bases str

Class for utf8 string storing and manipulations

The base presupposition of this class usage is ldquoALL strings in the application are either of utf-8 or unicodetype even when simple str type is used UTF-8 is only a ldquopackedrdquo version of unicode so Utf-8 and unicodestrings are interchangeablerdquo

CAUTION This class is slower than strunicode Do NOT use it inside intensive loops Simply decode string(s)to unicode before loop and encode it back to utf-8 string(s) after intensive calculation

You can see the benefit of this class in doctests() below

capitalize()rarr stringReturn a copy of the string S with only its first character capitalized

center(width[ fillchar ])rarr stringReturn S centered in a string of length width Padding is done using the specified fill character (default isa space)

count(sub[ start[ end ]])rarr intReturn the number of non-overlapping occurrences of substring sub in string S[startend] Optional argu-ments start and end are interpreted as in slice notation

139

web2py Documentation Release 2146-stable

decode([encoding[ errors]])rarr objectDecodes S using the codec registered for encoding encoding defaults to the default encoding errors maybe given to set a different error handling scheme Default is lsquostrictrsquo meaning that encoding errors raise aUnicodeDecodeError Other possible values are lsquoignorersquo and lsquoreplacersquo as well as any other name registeredwith codecsregister_error that is able to handle UnicodeDecodeErrors

encode([encoding[ errors]])rarr objectEncodes S using the codec registered for encoding encoding defaults to the default encoding errors maybe given to set a different error handling scheme Default is lsquostrictrsquo meaning that encoding errors raise aUnicodeEncodeError Other possible values are lsquoignorersquo lsquoreplacersquo and lsquoxmlcharrefreplacersquo as well as anyother name registered with codecsregister_error that is able to handle UnicodeEncodeErrors

endswith(suffix[ start[ end ]])rarr boolReturn True if S ends with the specified suffix False otherwise With optional start test S beginning atthat position With optional end stop comparing S at that position suffix can also be a tuple of strings totry

expandtabs([tabsize])rarr stringReturn a copy of S where all tab characters are expanded using spaces If tabsize is not given a tab size of8 characters is assumed

find(sub[ start[ end ]])rarr intReturn the lowest index in S where substring sub is found such that sub is contained within S[startend]Optional arguments start and end are interpreted as in slice notation

Return -1 on failure

format(args kwargs)rarr stringReturn a formatted version of S using substitutions from args and kwargs The substitutions are identifiedby braces (lsquolsquo and lsquorsquo)

index(sub[ start[ end ]])rarr intLike Sfind() but raise ValueError when the substring is not found

isalnum()rarr boolReturn True if all characters in S are alphanumeric and there is at least one character in S False otherwise

isalpha()rarr boolReturn True if all characters in S are alphabetic and there is at least one character in S False otherwise

isdigit()rarr boolReturn True if all characters in S are digits and there is at least one character in S False otherwise

islower()rarr boolReturn True if all cased characters in S are lowercase and there is at least one cased character in S Falseotherwise

isspace()rarr boolReturn True if all characters in S are whitespace and there is at least one character in S False otherwise

istitle()rarr boolReturn True if S is a titlecased string and there is at least one character in S ie uppercase characters mayonly follow uncased characters and lowercase characters only cased ones Return False otherwise

isupper()rarr boolReturn True if all cased characters in S are uppercase and there is at least one cased character in S Falseotherwise

join(iterable)rarr stringReturn a string which is the concatenation of the strings in the iterable The separator between elements isS

140 Chapter 35 utf8 Module

web2py Documentation Release 2146-stable

ljust(width[ fillchar ])rarr stringReturn S left-justified in a string of length width Padding is done using the specified fill character (defaultis a space)

lower()rarr stringReturn a copy of the string S converted to lowercase

lstrip([chars])rarr string or unicodeReturn a copy of the string S with leading whitespace removed If chars is given and not None removecharacters in chars instead If chars is unicode S will be converted to unicode before stripping

partition(sep) -gt (head sep tail)Search for the separator sep in S and return the part before it the separator itself and the part after it Ifthe separator is not found return S and two empty strings

replace(old new[ count ])rarr stringReturn a copy of string S with all occurrences of substring old replaced by new If the optional argumentcount is given only the first count occurrences are replaced

rfind(sub[ start[ end ]])rarr intReturn the highest index in S where substring sub is found such that sub is contained within S[startend]Optional arguments start and end are interpreted as in slice notation

Return -1 on failure

rindex(sub[ start[ end ]])rarr intLike Srfind() but raise ValueError when the substring is not found

rjust(width[ fillchar ])rarr stringReturn S right-justified in a string of length width Padding is done using the specified fill character (defaultis a space)

rpartition(sep) -gt (head sep tail)Search for the separator sep in S starting at the end of S and return the part before it the separator itselfand the part after it If the separator is not found return two empty strings and S

rsplit([sep[ maxsplit ]])rarr list of stringsReturn a list of the words in the string S using sep as the delimiter string starting at the end of the stringand working to the front If maxsplit is given at most maxsplit splits are done If sep is not specified or isNone any whitespace string is a separator

rstrip([chars])rarr string or unicodeReturn a copy of the string S with trailing whitespace removed If chars is given and not None removecharacters in chars instead If chars is unicode S will be converted to unicode before stripping

split([sep[ maxsplit ]])rarr list of stringsReturn a list of the words in the string S using sep as the delimiter string If maxsplit is given at mostmaxsplit splits are done If sep is not specified or is None any whitespace string is a separator and emptystrings are removed from the result

splitlines(keepends=False)rarr list of stringsReturn a list of the lines in S breaking at line boundaries Line breaks are not included in the resulting listunless keepends is given and true

startswith(prefix[ start[ end ]])rarr boolReturn True if S starts with the specified prefix False otherwise With optional start test S beginning atthat position With optional end stop comparing S at that position prefix can also be a tuple of strings totry

strip([chars])rarr string or unicodeReturn a copy of the string S with leading and trailing whitespace removed If chars is given and not None

351 Utilities and class for UTF8 strings managing 141

web2py Documentation Release 2146-stable

remove characters in chars instead If chars is unicode S will be converted to unicode before stripping

swapcase()rarr stringReturn a copy of the string S with uppercase characters converted to lowercase and vice versa

title()rarr stringReturn a titlecased version of S ie words start with uppercase characters all remaining cased charactershave lowercase

translate(table[ deletechars])rarr stringReturn a copy of the string S where all characters occurring in the optional argument deletechars areremoved and the remaining characters have been mapped through the given translation table which mustbe a string of length 256 or None If the table argument is None no translation is applied and the operationsimply removes the characters in deletechars

upper()rarr stringReturn a copy of the string S converted to uppercase

zfill(width)rarr stringPad a numeric string S with zeros on the left to fill a field of the specified width The string S is nevertruncated

142 Chapter 35 utf8 Module

CHAPTER 36

utils Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

361 This file specifically includes utilities for security

gluonutilsAES_new(key IV=None)Returns an AES cipher object and random IV if None specified

gluonutilscompare(a b)Compares two strings and not vulnerable to timing attacks

gluonutilsfast_urandom16(urandom=[] locker=lt_RLock owner=None count=0gt)This is 4x faster than calling osurandom(16) and prevents the ldquotoo many files openrdquo issue with concurrent accessto osurandom()

gluonutilsget_callable_argspec(fn)

gluonutilsget_digest(value)Returns a hashlib digest algorithm from a string

gluonutilsgetipaddrinfo(host)Filter out non-IP and bad IP addresses from getaddrinfo

gluonutilsinitialize_urandom()This function and the web2py_uuid follow from the following discussionhttpgroupsgooglecomgroupweb2py-developersbrowse_threadthread7fd5789a7da3f09

At startup web2py compute a unique ID that identifies the machine by adding uuidgetnode() + int(timetime() 1e3)

This is a 48-bit number It converts the number into 16 8-bit tokens It uses this value to initialize the entropysource (lsquodevurandomrsquo) and to seed random

143

web2py Documentation Release 2146-stable

If osrandom() is not supported it falls back to using random and issues a warning

gluonutilsis_loopback_ip_address(ip=None addrinfo=None)Determines whether the address appears to be a loopback address This assumes that the IP is valid

gluonutilsis_valid_ip_address(address)

Examples

Better than a thousand words

gtgtgt is_valid_ip_address(1270)Falsegtgtgt is_valid_ip_address(127001)Truegtgtgt is_valid_ip_address(20016601)True

gluonutilsmd5_hash(text)Generates a md5 hash with the given text

gluonutilspad(s n=32 padchar=rsquo rsquo)

gluonutilspbkdf2_hex(data salt iterations=1000 keylen=24 hashfunc=None)

gluonutilssecure_dumps(data encryption_key hash_key=None compression_level=None)

gluonutilssecure_loads(data encryption_key hash_key=None compression_level=None)

gluonutilssimple_hash(text key=rdquo salt=rdquo digest_alg=rsquomd5rsquo)Generates hash with the given text using the specified digest hashing algorithm

gluonutilsweb2py_uuid(ctokens=(12807810588179607998L 787762416516532974))This function follows from the following discussion httpgroupsgooglecomgroupweb2py-developersbrowse_threadthread7fd5789a7da3f09

It works like uuiduuid4 except that tries to use osurandom() if possible and it XORs the output with the tokensuniquely associated with this machine

144 Chapter 36 utils Module

CHAPTER 37

validators Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)Thanks to ga2arch for help with IS_IN_DB and IS_NOT_IN_DB on GAE

371 Validators

class gluonvalidatorsANY_OF(subs)Bases gluonvalidatorsValidator

Tests if any of the validators in a list returns successfully

gtgtgt ANY_OF([IS_EMAIL()IS_ALPHANUMERIC()])(abco)(abco None)gtgtgt ANY_OF([IS_EMAIL()IS_ALPHANUMERIC()])(abco)(abco None)gtgtgt ANY_OF([IS_EMAIL()IS_ALPHANUMERIC()])(abco)(abco enter only letters numbers and underscore)gtgtgt ANY_OF([IS_ALPHANUMERIC()IS_EMAIL()])(abco)(abco enter a valid email address)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

class gluonvalidatorsCLEANUP(regex=None)Bases gluonvalidatorsValidator

Examples

Use as

145

web2py Documentation Release 2146-stable

INPUT(_type=text _name=name requires=CLEANUP())

removes special characters on validation

REGEX_CLEANUP = lt_sreSRE_Pattern objectgt

class gluonvalidatorsCRYPT(key=None digest_alg=rsquopbkdf2(1000 20 sha512)rsquo min_length=0error_message=rsquoToo shortrsquo salt=True max_length=1024)

Bases object

Examples

Use as

INPUT(_type=text _name=name requires=CRYPT())

encodes the value on validation with a digest

If no arguments are provided CRYPT uses the MD5 algorithm If the key argument is provided the HMAC+MD5algorithm is used If the digest_alg is specified this is used to replace the MD5 with for example SHA512 Thedigest_alg can be the name of a hashlib algorithm as a string or the algorithm itself

min_length is the minimal password length (default 4) - IS_STRONG for serious security error_message is themessage if password is too short

Notice that an empty password is accepted but invalid It will not allow login back Stores junk as hashedpassword

Specify an algorithm or by default we will use sha512

Typical available algorithms md5 sha1 sha224 sha256 sha384 sha512

If salt it hashes a password with a salt If salt is True this method will automatically generate one Either caseit returns an encrypted password string in the following format

ltalgorithmgt$ltsaltgt$lthashgt

Important hashed password is returned as a LazyCrypt object and computed only if needed The LasyCryptobject also knows how to compare itself with an existing salted password

Supports standard algorithms

gtgtgt for alg in (md5sha1sha256sha384sha512) print str(CRYPT(digest_alg=algsalt=True)(test)[0])md5$$sha1$$sha256$$sha384$$sha512$$

The syntax is always alg$salt$hash

Supports for pbkdf2

gtgtgt alg = pbkdf2(100020sha512)gtgtgt print str(CRYPT(digest_alg=algsalt=True)(test)[0])pbkdf2(100020sha512)$$

An optional hmac_key can be specified and it is used as salt prefix

146 Chapter 37 validators Module

web2py Documentation Release 2146-stable

gtgtgt a = str(CRYPT(digest_alg=md5key=mykeysalt=True)(test)[0])gtgtgt print amd5$$

Even if the algorithm changes the hash can still be validated

gtgtgt CRYPT(digest_alg=sha1key=mykeysalt=True)(test)[0] == aTrue

If no salt is specified CRYPT can guess the algorithms from length

gtgtgt a = str(CRYPT(digest_alg=sha1salt=False)(test)[0])gtgtgt asha1$$a94a8fe5ccb19ba61c4c0873d391e987982fbbd3gtgtgt CRYPT(digest_alg=sha1salt=False)(test)[0] == aTruegtgtgt CRYPT(digest_alg=sha1salt=False)(test)[0] == a[6]Truegtgtgt CRYPT(digest_alg=md5salt=False)(test)[0] == aTruegtgtgt CRYPT(digest_alg=md5salt=False)(test)[0] == a[6]True

class gluonvalidatorsIS_ALPHANUMERIC(error_message=rsquoEnter only letters numbers andunderscorersquo)

Bases gluonvalidatorsIS_MATCH

Example

Used as

INPUT(_type=text _name=name requires=IS_ALPHANUMERIC())

gtgtgt IS_ALPHANUMERIC()(1)(1 None)gtgtgt IS_ALPHANUMERIC()()( None)gtgtgt IS_ALPHANUMERIC()(A_a)(A_a None)gtgtgt IS_ALPHANUMERIC()()( enter only letters numbers and underscore)

class gluonvalidatorsIS_DATE_IN_RANGE(minimum=None maximum=None format=rsquoY-m-drsquo error_message=None)

Bases gluonvalidatorsIS_DATE

Examples

Use as

gtgtgt v = IS_DATE_IN_RANGE(minimum=datetimedate(200811)rarr˓ maximum=datetimedate(20091231)rarr˓ format=mdYerror_message=Oops)

(continues on next page)

371 Validators 147

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt v(03032008)(datetimedate(2008 3 3) None)

gtgtgt v(03032010)(03032010 oops)

gtgtgt v(datetimedate(200833))(datetimedate(2008 3 3) None)

gtgtgt v(datetimedate(201033))(datetimedate(2010 3 3) oops)

class gluonvalidatorsIS_DATE(format=rsquoY-m-drsquo error_message=rsquoEnter date as (for-mat)srsquo)

Bases gluonvalidatorsValidator

Examples

Use as

INPUT(_type=text _name=name requires=IS_DATE())

date has to be in the ISO8960 format YYYY-MM-DD

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

class gluonvalidatorsIS_DATETIME_IN_RANGE(minimum=None maximum=Noneformat=rsquoY-m-d HMSrsquo er-ror_message=None timezone=None)

Bases gluonvalidatorsIS_DATETIME

Examples

Use as

gtgtgt v = IS_DATETIME_IN_RANGE( minimum=datetimerarr˓datetime(2008111220) maximum=datetimerarr˓datetime(200912311220) format=mdY HMrarr˓error_message=Oops)gtgtgt v(03032008 1240)(datetimedatetime(2008 3 3 12 40) None)

gtgtgt v(03032010 1034)(03032010 1034 oops)

gtgtgt v(datetimedatetime(20083300))(datetimedatetime(2008 3 3 0 0) None)

gtgtgt v(datetimedatetime(20103300))(datetimedatetime(2010 3 3 0 0) oops)

148 Chapter 37 validators Module

web2py Documentation Release 2146-stable

class gluonvalidatorsIS_DATETIME(format=rsquoY-m-d HMSrsquo er-ror_message=rsquoEnter date and time as (format)srsquotimezone=None)

Bases gluonvalidatorsValidator

Examples

Use as

INPUT(_type=text _name=name requires=IS_DATETIME())

datetime has to be in the ISO8960 format YYYY-MM-DD hhmmss timezome must be None or apytztimezone(ldquoAmericaChicagordquo) object

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

isodatetime = Y-m-d HMS

static nice(format)

class gluonvalidatorsIS_DECIMAL_IN_RANGE(minimum=None maximum=None er-ror_message=None dot=rsquorsquo)

Bases gluonvalidatorsValidator

Determines that the argument is (or can be represented as) a Python Decimal and that it falls within the specifiedinclusive range The comparison is made with Python Decimal arithmetic

The minimum and maximum limits can be None meaning no lower or upper limit respectively

Example

Used as

INPUT(_type=text _name=name requires=IS_DECIMAL_IN_RANGE(0 10))

gtgtgt IS_DECIMAL_IN_RANGE(15)(4)(Decimal(4) None)gtgtgt IS_DECIMAL_IN_RANGE(15)(4)(Decimal(4) None)gtgtgt IS_DECIMAL_IN_RANGE(15)(1)(Decimal(1) None)gtgtgt IS_DECIMAL_IN_RANGE(15)(525)(525 enter a number between 1 and 5)gtgtgt IS_DECIMAL_IN_RANGE(5256)(525)(Decimal(525) None)gtgtgt IS_DECIMAL_IN_RANGE(5256)(525)(Decimal(525) None)gtgtgt IS_DECIMAL_IN_RANGE(15)(60)(60 enter a number between 1 and 5)gtgtgt IS_DECIMAL_IN_RANGE(15)(35)(Decimal(35) None)gtgtgt IS_DECIMAL_IN_RANGE(1555)(35)(Decimal(35) None)gtgtgt IS_DECIMAL_IN_RANGE(1555)(65)(65 enter a number between 15 and 55)

(continues on next page)

371 Validators 149

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_DECIMAL_IN_RANGE(15None)(65)(Decimal(65) None)gtgtgt IS_DECIMAL_IN_RANGE(15None)(05)(05 enter a number greater than or equal to 15)gtgtgt IS_DECIMAL_IN_RANGE(None55)(45)(Decimal(45) None)gtgtgt IS_DECIMAL_IN_RANGE(None55)(65)(65 enter a number less than or equal to 55)gtgtgt IS_DECIMAL_IN_RANGE()(65)(Decimal(65) None)gtgtgt IS_DECIMAL_IN_RANGE(099)(123123)(123123 enter a number between 0 and 99)gtgtgt IS_DECIMAL_IN_RANGE(099)(123123)(123123 enter a number between 0 and 99)gtgtgt IS_DECIMAL_IN_RANGE(099)(1234)(Decimal(1234) None)gtgtgt IS_DECIMAL_IN_RANGE()(abc)(abc enter a number)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

class gluonvalidatorsIS_EMAIL(banned=None forced=None error_message=rsquoEnter a validemail addressrsquo)

Bases gluonvalidatorsValidator

Checks if fieldrsquos value is a valid email address Can be set to disallow or force addresses from certain domain(s)

Email regex adapted from httphaackedcomarchive20070821i-knew-how-to-validate-an-email-address-until-iaspx generally following the RFCs except that we disallow quoted strings and permit underscores and leadingnumerics in subdomain labels

Parameters

bull banned ndash regex text for disallowed address domains

bull forced ndash regex text for required address domains

Both arguments can also be custom objects with a match(value) method

Example

Check for valid email address

INPUT(_type=text _name=namerequires=IS_EMAIL())

Check for valid email address that canrsquot be from a com domain

INPUT(_type=text _name=namerequires=IS_EMAIL(banned=^com(|)$))

Check for valid email address that must be from a edu domain

INPUT(_type=text _name=namerequires=IS_EMAIL(forced=^edu(|)$))

(continues on next page)

150 Chapter 37 validators Module

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_EMAIL()(abcom)(abcom None)gtgtgt IS_EMAIL()(abcdefcom)(abcdefcom None)gtgtgt IS_EMAIL()(abc3defcom)(abc3defcom None)gtgtgt IS_EMAIL()(abcdefus)(abcdefus None)gtgtgt IS_EMAIL()(abcd_-fus)(abcd_-fus None)gtgtgt IS_EMAIL()(defcom) missing name(defcom enter a valid email address)gtgtgt IS_EMAIL()(abcdefcom) quoted name(abcdefcom enter a valid email address)gtgtgt IS_EMAIL()(abc+defcom) no (abc+defcom enter a valid email address)gtgtgt IS_EMAIL()(abcdefx) one-char TLD(abcdefx enter a valid email address)gtgtgt IS_EMAIL()(abcdef12) numeric TLD(abcdef12 enter a valid email address)gtgtgt IS_EMAIL()(abcdefcom) double-dot in domain(abcdefcom enter a valid email address)gtgtgt IS_EMAIL()(abcdefcom) dot starts domain(abcdefcom enter a valid email address)gtgtgt IS_EMAIL()(abcdefc_m) underscore in TLD(abcdefc_m enter a valid email address)gtgtgt IS_EMAIL()(NotAnEmail) missing (NotAnEmail enter a valid email address)gtgtgt IS_EMAIL()(abcNotAnEmail) missing TLD(abcNotAnEmail enter a valid email address)gtgtgt IS_EMAIL()(customerdepartmentexamplecom)(customerdepartmentexamplecom None)gtgtgt IS_EMAIL()($A12345examplecom)($A12345examplecom None)gtgtgt IS_EMAIL()(defxyzabcexamplecom)(defxyzabcexamplecom None)gtgtgt IS_EMAIL()(_YosemiteSamexamplecom)(_YosemiteSamexamplecom None)gtgtgt IS_EMAIL()(~examplecom)(~examplecom None)gtgtgt IS_EMAIL()(woolyexamplecom) dot starts name(woolyexamplecom enter a valid email address)gtgtgt IS_EMAIL()(woolyexamplecom) adjacent dots in name(woolyexamplecom enter a valid email address)gtgtgt IS_EMAIL()(pootietangexamplecom) dot ends name(pootietangexamplecom enter a valid email address)gtgtgt IS_EMAIL()(examplecom) name is bare dot(examplecom enter a valid email address)gtgtgt IS_EMAIL()(ImaFoolexamplecom)(ImaFoolexamplecom None)gtgtgt IS_EMAIL()(Ima Foolexamplecom) space in name(Ima Foolexamplecom enter a valid email address)gtgtgt IS_EMAIL()(localguylocalhost) localhost as domain(localguylocalhost None)

regex = lt_sreSRE_Pattern object at 0x2e0e160gt

371 Validators 151

web2py Documentation Release 2146-stable

regex_proposed_but_failed = lt_sreSRE_Pattern object at 0x2e100d0gt

class gluonvalidatorsIS_LIST_OF_EMAILS(error_message=rsquoInvalid emails srsquo)Bases object

Example

Used as

Field(emailsliststringwidget=SQLFORMwidgetstextwidgetrequires=IS_LIST_OF_EMAILS()represent=lambda vr SPAN([A(x_href=mailto+x)

rarr˓for x in (v or [])]))

formatter(value row=None)

split_emails = lt_sreSRE_Pattern objectgt

class gluonvalidatorsIS_EMPTY_OR(other null=None empty_regex=None)Bases gluonvalidatorsValidator

Dummy class for testing IS_EMPTY_OR

gtgtgt IS_EMPTY_OR(IS_EMAIL())(abcdefcom)(abcdefcom None)gtgtgt IS_EMPTY_OR(IS_EMAIL())( )(None None)gtgtgt IS_EMPTY_OR(IS_EMAIL() null=abc)( )(abc None)gtgtgt IS_EMPTY_OR(IS_EMAIL() null=abc empty_regex=def)(def)(abc None)gtgtgt IS_EMPTY_OR(IS_EMAIL())(abc)(abc enter a valid email address)gtgtgt IS_EMPTY_OR(IS_EMAIL())( abc )(abc enter a valid email address)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

set_self_id(id)

class gluonvalidatorsIS_EXPR(expression error_message=rsquoInvalid expressionrsquo environ-ment=None)

Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=namerequires=IS_EXPR(5 lt int(value) lt 10))

The argument of IS_EXPR must be python condition

152 Chapter 37 validators Module

web2py Documentation Release 2146-stable

gtgtgt IS_EXPR(int(value) lt 2)(1)(1 None)

gtgtgt IS_EXPR(int(value) lt 2)(2)(2 invalid expression)

class gluonvalidatorsIS_FLOAT_IN_RANGE(minimum=None maximum=None er-ror_message=None dot=rsquorsquo)

Bases gluonvalidatorsValidator

Determines that the argument is (or can be represented as) a float and that it falls within the specified inclusiverange The comparison is made with native arithmetic

The minimum and maximum limits can be None meaning no lower or upper limit respectively

Example

Used as

INPUT(_type=text _name=name requires=IS_FLOAT_IN_RANGE(0 10))

gtgtgt IS_FLOAT_IN_RANGE(15)(4)(40 None)gtgtgt IS_FLOAT_IN_RANGE(15)(4)(40 None)gtgtgt IS_FLOAT_IN_RANGE(15)(1)(10 None)gtgtgt IS_FLOAT_IN_RANGE(15)(525)(525 enter a number between 1 and 5)gtgtgt IS_FLOAT_IN_RANGE(15)(60)(60 enter a number between 1 and 5)gtgtgt IS_FLOAT_IN_RANGE(15)(35)(35 None)gtgtgt IS_FLOAT_IN_RANGE(1None)(35)(35 None)gtgtgt IS_FLOAT_IN_RANGE(None5)(35)(35 None)gtgtgt IS_FLOAT_IN_RANGE(1None)(05)(05 enter a number greater than or equal to 1)gtgtgt IS_FLOAT_IN_RANGE(None5)(65)(65 enter a number less than or equal to 5)gtgtgt IS_FLOAT_IN_RANGE()(65)(65 None)gtgtgt IS_FLOAT_IN_RANGE()(abc)(abc enter a number)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

class gluonvalidatorsIS_IMAGE(extensions=(rsquobmprsquo rsquogifrsquo rsquojpegrsquo rsquopngrsquo) maxsize=(1000010000) minsize=(0 0) error_message=rsquoInvalid imagersquo)

Bases gluonvalidatorsValidator

Checks if file uploaded through file input was saved in one of selected image formats and has dimensions (widthand height) within given boundaries

371 Validators 153

web2py Documentation Release 2146-stable

Does not check for maximum file size (use IS_LENGTH for that) Returns validation failure if no data wasuploaded

Supported file formats BMP GIF JPEG PNG

Code parts taken from httpmailpythonorgpipermailpython-list2007-June617126html

Parameters

bull extensions ndash iterable containing allowed lowercase image file extensions

bull extension of uploaded file counts as jpeg) ((jpg) ndash

bull maxsize ndash iterable containing maximum width and height of the image

bull minsize ndash iterable containing minimum width and height of the image

Use (-1 -1) as minsize to pass image size check

Examples

Check if uploaded file is in any of supported image formats

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_IMAGE())

Check if uploaded file is either JPEG or PNG

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_IMAGE(extensions=(lsquojpegrsquo lsquopngrsquo)))

Check if uploaded file is PNG with maximum size of 200x200 pixels

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_IMAGE(extensions=(lsquopngrsquo) maxsize=(200200)))

class gluonvalidatorsIS_IN_DB(dbset field label=None error_message=rsquoValue not indatabasersquo orderby=None groupby=None distinct=Nonecache=None multiple=False zero=rdquo sort=False_and=None left=None delimiter=None auto_add=False)

Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=namerequires=IS_IN_DB(db dbmytablemyfield zero=))

used for reference fields rendered as a dropbox

build_set()

maybe_add(table fieldname value)

options(zero=True)

set_self_id(id)

class gluonvalidatorsIS_IN_SET(theset labels=None error_message=rsquoValue not allowedrsquomultiple=False zero=rdquo sort=False)

Bases gluonvalidatorsValidator

154 Chapter 37 validators Module

web2py Documentation Release 2146-stable

Example

Used as

INPUT(_type=text _name=namerequires=IS_IN_SET([max john]zero=))

The argument of IS_IN_SET must be a list or set

gtgtgt IS_IN_SET([max john])(max)(max None)gtgtgt IS_IN_SET([max john])(massimo)(massimo value not allowed)gtgtgt IS_IN_SET([max john] multiple=True)((max john))((max john) None)gtgtgt IS_IN_SET([max john] multiple=True)((bill john))((bill john) value not allowed)gtgtgt IS_IN_SET((id1id2) [first labelsecond label])(id1) Traditionalrarr˓way(id1 None)gtgtgt IS_IN_SET(id1first label id2second label)(id1)(id1 None)gtgtgt import itertoolsgtgtgt IS_IN_SET(itertoolschain([135][246]))(1)(1 None)gtgtgt IS_IN_SET([(id1first label) (id2second label)])(id1) Redundantrarr˓way(id1 None)

options(zero=True)

class gluonvalidatorsIS_INT_IN_RANGE(minimum=None maximum=None er-ror_message=None)

Bases gluonvalidatorsValidator

Determines that the argument is (or can be represented as) an int and that it falls within the specified range Therange is interpreted in the Pythonic way so the test is min lt= value lt max

The minimum and maximum limits can be None meaning no lower or upper limit respectively

Example

Used as

INPUT(_type=text _name=name requires=IS_INT_IN_RANGE(0 10))

gtgtgt IS_INT_IN_RANGE(15)(4)(4 None)gtgtgt IS_INT_IN_RANGE(15)(4)(4 None)gtgtgt IS_INT_IN_RANGE(15)(1)(1 None)gtgtgt IS_INT_IN_RANGE(15)(5)(5 enter an integer between 1 and 4)gtgtgt IS_INT_IN_RANGE(15)(5)(5 enter an integer between 1 and 4)gtgtgt IS_INT_IN_RANGE(15)(35)

(continues on next page)

371 Validators 155

web2py Documentation Release 2146-stable

(continued from previous page)

(35 enter an integer between 1 and 4)gtgtgt IS_INT_IN_RANGE(None5)(4)(4 None)gtgtgt IS_INT_IN_RANGE(None5)(6)(6 enter an integer less than or equal to 4)gtgtgt IS_INT_IN_RANGE(1None)(4)(4 None)gtgtgt IS_INT_IN_RANGE(1None)(0)(0 enter an integer greater than or equal to 1)gtgtgt IS_INT_IN_RANGE()(6)(6 None)gtgtgt IS_INT_IN_RANGE()(abc)(abc enter an integer)

class gluonvalidatorsIS_IPV4(minip=rsquo0000rsquo maxip=rsquo255255255255rsquo invert=Falseis_localhost=None is_private=None is_automatic=Noneerror_message=rsquoEnter valid IPv4 addressrsquo)

Bases gluonvalidatorsValidator

Checks if fieldrsquos value is an IP version 4 address in decimal form Can be set to force addresses from certainrange

IPv4 regex taken from httpregexlibcomREDetailsaspxregexp_id=1411

Parameters

bull minip ndash lowest allowed address accepts

ndash str eg 19216801

ndash list or tuple of octets eg [192 168 0 1]

bull maxip ndash highest allowed address same as above

bull invert ndash True to allow addresses only from outside of given range note that range bound-aries are not matched this way

bull is_localhost ndash localhost address treatment

ndash None (default) indifferent

ndash True (enforce) query address must match localhost address (127001)

ndash False (forbid) query address must not match localhost address

bull is_private ndash same as above except that query address is checked against two addressranges 1721600 - 17231255255 and 19216800 - 192168255255

bull is_automatic ndash same as above except that query address is checked against one addressrange 16925400 - 169254255255

Minip and maxip may also be lists or tuples of addresses in all above forms (str int list tuple) allowing setupof multiple address ranges

minip = (minip1 minip2 minipN)| | || | |

maxip = (maxip1 maxip2 maxipN)

Longer iterable will be truncated to match length of shorter one

156 Chapter 37 validators Module

web2py Documentation Release 2146-stable

Examples

Check for valid IPv4 address

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV4())

Check for valid IPv4 address belonging to specific range

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV4(minip=lsquo10020000rsquomaxip=lsquo100200255255rsquo))

Check for valid IPv4 address belonging to either 10011000 - 100110255255 or 2005000 - 200500255address range

INPUT(_type=rsquotextrsquo _name=rsquonamersquo

requires=IS_IPV4(minip=(lsquo10011000rsquo lsquo2005000rsquo) maxip=(lsquo100110255255rsquolsquo200500255rsquo)))

Check for valid IPv4 address belonging to private address space

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV4(is_private=True))

Check for valid IPv4 address that is not a localhost address

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV4(is_localhost=False))

gtgtgt IS_IPV4()(1234)(1234 None)gtgtgt IS_IPV4()(255255255255)(255255255255 None)gtgtgt IS_IPV4()(1234 )(1234 enter valid IPv4 address)gtgtgt IS_IPV4()(12345)(12345 enter valid IPv4 address)gtgtgt IS_IPV4()(123123)(123123 enter valid IPv4 address)gtgtgt IS_IPV4()(1111234)(1111234 enter valid IPv4 address)gtgtgt IS_IPV4()(0111234)(0111234 enter valid IPv4 address)gtgtgt IS_IPV4()(256234)(256234 enter valid IPv4 address)gtgtgt IS_IPV4()(300234)(300234 enter valid IPv4 address)gtgtgt IS_IPV4(minip=1234 maxip=1234)(1234)(1234 None)gtgtgt IS_IPV4(minip=1235 maxip=1239 error_message=Bad ip)(1rarr˓234)(1234 bad ip)gtgtgt IS_IPV4(maxip=1234 invert=True)(127001)(127001 None)gtgtgt IS_IPV4(maxip=1234 invert=True)(1234)(1234 enter valid IPv4 address)gtgtgt IS_IPV4(is_localhost=True)(127001)(127001 None)gtgtgt IS_IPV4(is_localhost=True)(1234)(1234 enter valid IPv4 address)gtgtgt IS_IPV4(is_localhost=False)(127001)(127001 enter valid IPv4 address)

(continues on next page)

371 Validators 157

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_IPV4(maxip=100000 is_localhost=True)(127001)(127001 enter valid IPv4 address)

automatic = (2851995648L 2852061183L)

localhost = 2130706433

numbers = (16777216 65536 256 1)

private = ((2886729728L 2886795263L) (3232235520L 3232301055L))

regex = lt_sreSRE_Pattern object at 0x2e26320gt

class gluonvalidatorsIS_IPV6(is_private=None is_link_local=None is_reserved=Noneis_multicast=None is_routeable=None is_6to4=Noneis_teredo=None subnets=None error_message=rsquoEnter validIPv6 addressrsquo)

Bases gluonvalidatorsValidator

Checks if fieldrsquos value is an IP version 6 address First attempts to use the ipaddress library and falls back tocontribipaddrpy from Google (httpscodegooglecompipaddr-py)

Parameters

bull is_private ndash None (default) indifferent True (enforce) address must be in fc007range False (forbid) address must NOT be in fc007 range

bull is_link_local ndash Same as above but uses fe8010 range

bull is_reserved ndash Same as above but uses IETF reserved range

bull is_mulicast ndash Same as above but uses ff008 range

bull is_routeable ndash Similar to above but enforces not private link_local reserved or multi-cast

bull is_6to4 ndash Same as above but uses 200216 range

bull is_teredo ndash Same as above but uses 200132 range

bull subnets ndash value must be a member of at least one from list of subnets

Examples

Check for valid IPv6 address

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV6())

Check for valid IPv6 address is a link_local address

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV6(is_link_local=True))

Check for valid IPv6 address that is Internet routeable

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV6(is_routeable=True))

Check for valid IPv6 address in specified subnet

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV6(subnets=[lsquo200132rsquo])

158 Chapter 37 validators Module

web2py Documentation Release 2146-stable

gtgtgt IS_IPV6()(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPV6()(19216811)(19216811 enter valid IPv6 address)gtgtgt IS_IPV6(error_message=Bad ip)(19216811)(19216811 bad ip)gtgtgt IS_IPV6(is_link_local=True)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPV6(is_link_local=False)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(is_link_local=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(is_multicast=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(is_multicast=True)(ff00126c8ffafe22b3af)(ff00126c8ffafe22b3af None)gtgtgt IS_IPV6(is_routeable=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af None)gtgtgt IS_IPV6(is_routeable=True)(ff00126c8ffafe22b3af)(ff00126c8ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(subnets=200132)(20018ffafe22b3af)(20018ffafe22b3af None)gtgtgt IS_IPV6(subnets=fb008)(20018ffafe22b3af)(20018ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(subnets=[fc008200132])(20018ffafe22b3af)(20018ffafe22b3af None)gtgtgt IS_IPV6(subnets=invalidsubnet)(20018ffafe22b3af)(20018ffafe22b3af invalid subnet provided)

class gluonvalidatorsIS_IPADDRESS(minip=rsquo0000rsquo maxip=rsquo255255255255rsquo in-vert=False is_localhost=None is_private=Noneis_automatic=None is_ipv4=None is_link_local=Noneis_reserved=None is_multicast=Noneis_routeable=None is_6to4=None is_teredo=Nonesubnets=None is_ipv6=None error_message=rsquoEntervalid IP addressrsquo)

Bases gluonvalidatorsValidator

Checks if fieldrsquos value is an IP Address (v4 or v6) Can be set to force addresses from within a specific rangeChecks are done with the correct IS_IPV4 and IS_IPV6 validators

Uses ipaddress library if found falls back to PEP-3144 ipaddrpy from Google (in contrib)

Parameters

bull minip ndash lowest allowed address accepts str eg 19216801 list or tuple of octets eg[192 168 0 1]

bull maxip ndash highest allowed address same as above

bull invert ndash True to allow addresses only from outside of given range note that range bound-aries are not matched this way

IPv4 specific arguments

bull is_localhost localhost address treatment

ndash None (default) indifferent

ndash True (enforce) query address must match localhost address (127001)

371 Validators 159

web2py Documentation Release 2146-stable

ndash False (forbid) query address must not match localhost address

bull is_private same as above except that query address is checked against two address ranges 1721600 -17231255255 and 19216800 - 192168255255

bull is_automatic same as above except that query address is checked against one address range 16925400- 169254255255

bull is_ipv4 either

ndash None (default) indifferent

ndash True (enforce) must be an IPv4 address

ndash False (forbid) must NOT be an IPv4 address

IPv6 specific arguments

bull is_link_local Same as above but uses fe8010 range

bull is_reserved Same as above but uses IETF reserved range

bull is_mulicast Same as above but uses ff008 range

bull is_routeable Similar to above but enforces not private link_local reserved or multicast

bull is_6to4 Same as above but uses 200216 range

bull is_teredo Same as above but uses 200132 range

bull subnets value must be a member of at least one from list of subnets

bull is_ipv6 either

ndash None (default) indifferent

ndash True (enforce) must be an IPv6 address

ndash False (forbid) must NOT be an IPv6 address

Minip and maxip may also be lists or tuples of addresses in all above forms (str int list tuple) allowing setupof multiple address ranges

minip = (minip1 minip2 minipN)| | || | |

maxip = (maxip1 maxip2 maxipN)

Longer iterable will be truncated to match length of shorter one

gtgtgt IS_IPADDRESS()(19216815)(19216815 None)gtgtgt IS_IPADDRESS(is_ipv6=False)(19216815)(19216815 None)gtgtgt IS_IPADDRESS()(255255255255)(255255255255 None)gtgtgt IS_IPADDRESS()(19216815 )(19216815 enter valid IP address)gtgtgt IS_IPADDRESS()(192168115)(192168115 enter valid IP address)gtgtgt IS_IPADDRESS()(123123)(123123 enter valid IP address)gtgtgt IS_IPADDRESS()(1111234)(1111234 enter valid IP address)gtgtgt IS_IPADDRESS()(0111234)

(continues on next page)

160 Chapter 37 validators Module

web2py Documentation Release 2146-stable

(continued from previous page)

(0111234 enter valid IP address)gtgtgt IS_IPADDRESS()(256234)(256234 enter valid IP address)gtgtgt IS_IPADDRESS()(300234)(300234 enter valid IP address)gtgtgt IS_IPADDRESS(minip=19216810 maxip=1921681255)(1921681100)(1921681100 None)gtgtgt IS_IPADDRESS(minip=1235 maxip=1239 error_message=Bad ip)(123rarr˓4)(1234 bad ip)gtgtgt IS_IPADDRESS(maxip=1234 invert=True)(127001)(127001 None)gtgtgt IS_IPADDRESS(maxip=19216814 invert=True)(19216814)(19216814 enter valid IP address)gtgtgt IS_IPADDRESS(is_localhost=True)(127001)(127001 None)gtgtgt IS_IPADDRESS(is_localhost=True)(192168110)(192168110 enter valid IP address)gtgtgt IS_IPADDRESS(is_localhost=False)(127001)(127001 enter valid IP address)gtgtgt IS_IPADDRESS(maxip=100000 is_localhost=True)(127001)(127001 enter valid IP address)

gtgtgt IS_IPADDRESS()(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPADDRESS(is_ipv4=False)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPADDRESS()(fe80126c8ffafe22b3af )(fe80126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_ipv4=True)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_ipv6=True)(19216811)(19216811 enter valid IP address)gtgtgt IS_IPADDRESS(is_ipv6=True error_message=Bad ip)(19216811)(19216811 bad ip)gtgtgt IS_IPADDRESS(is_link_local=True)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPADDRESS(is_link_local=False)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_link_local=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_multicast=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_multicast=True)(ff00126c8ffafe22b3af)(ff00126c8ffafe22b3af None)gtgtgt IS_IPADDRESS(is_routeable=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af None)gtgtgt IS_IPADDRESS(is_routeable=True)(ff00126c8ffafe22b3af)(ff00126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(subnets=200132)(20018ffafe22b3af)(20018ffafe22b3af None)gtgtgt IS_IPADDRESS(subnets=fb008)(20018ffafe22b3af)(20018ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(subnets=[fc008200132])(20018ffafe22b3af)(20018ffafe22b3af None)gtgtgt IS_IPADDRESS(subnets=invalidsubnet)(20018ffafe22b3af)(20018ffafe22b3af invalid subnet provided)

371 Validators 161

web2py Documentation Release 2146-stable

class gluonvalidatorsIS_LENGTH(maxsize=255 minsize=0 error_message=rsquoEnter from(min)g to (max)g charactersrsquo)

Bases gluonvalidatorsValidator

Checks if length of fieldrsquos value fits between given boundaries Works for both text and file inputs

Parameters

bull maxsize ndash maximum allowed length size

bull minsize ndash minimum allowed length size

Examples

Check if text string is shorter than 33 characters

INPUT(_type=text _name=name requires=IS_LENGTH(32))

Check if password string is longer than 5 characters

INPUT(_type=password _name=name requires=IS_LENGTH(minsize=6))

Check if uploaded file has size between 1KB and 1MB

INPUT(_type=file _name=name requires=IS_LENGTH(1048576 1024))

Other examples

gtgtgt IS_LENGTH()()( None)gtgtgt IS_LENGTH()(1234567890)(1234567890 None)gtgtgt IS_LENGTH(maxsize=5 minsize=0)(1234567890) too long(1234567890 enter from 0 to 5 characters)gtgtgt IS_LENGTH(maxsize=50 minsize=20)(1234567890) too short(1234567890 enter from 20 to 50 characters)

class gluonvalidatorsIS_LIST_OF(other=None minimum=0 maximum=100 er-ror_message=None)

Bases gluonvalidatorsValidator

class gluonvalidatorsIS_LOWERBases gluonvalidatorsValidator

Converts to lower case

gtgtgt IS_LOWER()(ABC)(abc None)gtgtgt IS_LOWER()(Ntilde)(xc3xb1 None)

class gluonvalidatorsIS_MATCH(expression error_message=rsquoInvalid expressionrsquo strict=Falsesearch=False extract=False is_unicode=False)

Bases gluonvalidatorsValidator

Example

Used as

162 Chapter 37 validators Module

web2py Documentation Release 2146-stable

INPUT(_type=text _name=name requires=IS_MATCH(+))

The argument of IS_MATCH is a regular expression

gtgtgt IS_MATCH(+)(hello)(hello None)

gtgtgt IS_MATCH(hell)(hello)(hello None)

gtgtgt IS_MATCH(hell strict=False)(hello)(hello None)

gtgtgt IS_MATCH(hello)(shello)(shello invalid expression)

gtgtgt IS_MATCH(hello search=True)(shello)(shello None)

gtgtgt IS_MATCH(hello search=True strict=False)(shellox)(shellox None)

gtgtgt IS_MATCH(hello search=True strict=False)(shellox)(shellox None)

gtgtgt IS_MATCH(+)()( invalid expression)

class gluonvalidatorsIS_EQUAL_TO(expression error_message=rsquoNo matchrsquo)Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=password)INPUT(_type=text _name=password2

requires=IS_EQUAL_TO(requestvarspassword))

The argument of IS_EQUAL_TO is a string

gtgtgt IS_EQUAL_TO(aaa)(aaa)(aaa None)

gtgtgt IS_EQUAL_TO(aaa)(aab)(aab no match)

class gluonvalidatorsIS_NOT_EMPTY(error_message=rsquoEnter a valuersquo empty_regex=None)Bases gluonvalidatorsValidator

Example

Used as

371 Validators 163

web2py Documentation Release 2146-stable

INPUT(_type=text _name=name requires=IS_NOT_EMPTY())

gtgtgt IS_NOT_EMPTY()(1)(1 None)gtgtgt IS_NOT_EMPTY()(0)(0 None)gtgtgt IS_NOT_EMPTY()(x)(x None)gtgtgt IS_NOT_EMPTY()( x )(x None)gtgtgt IS_NOT_EMPTY()(None)(None enter a value)gtgtgt IS_NOT_EMPTY()()( enter a value)gtgtgt IS_NOT_EMPTY()( )( enter a value)gtgtgt IS_NOT_EMPTY()( nt)( enter a value)gtgtgt IS_NOT_EMPTY()([])([] enter a value)gtgtgt IS_NOT_EMPTY(empty_regex=def)(def)( enter a value)gtgtgt IS_NOT_EMPTY(empty_regex=de[fg])(deg)( enter a value)gtgtgt IS_NOT_EMPTY(empty_regex=def)(abc)(abc None)

class gluonvalidatorsIS_NOT_IN_DB(dbset field error_message=rsquoValue already indatabase or emptyrsquo allowed_override=[] ig-nore_common_filters=False)

Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=name requires=IS_NOT_IN_DB(db dbtable))

makes the field unique

set_self_id(id)

gluonvalidatorsIS_NULL_ORalias of gluonvalidatorsIS_EMPTY_OR

class gluonvalidatorsIS_SLUG(maxlen=80 check=False error_message=rsquoMust be slugrsquokeep_underscores=False)

Bases gluonvalidatorsValidator

converts arbitrary text string to a slug

gtgtgt IS_SLUG()(abc123)(abc123 None)gtgtgt IS_SLUG()(ABC123)(abc123 None)gtgtgt IS_SLUG()(abc-123)(abc-123 None)

(continues on next page)

164 Chapter 37 validators Module

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_SLUG()(abc--123)(abc-123 None)gtgtgt IS_SLUG()(abc 123)(abc-123 None)gtgtgt IS_SLUG()(abc _123)(abc-123 None)gtgtgt IS_SLUG()(-abc-)(abc None)gtgtgt IS_SLUG()(--a--b--_ -c--)(a-b-c None)gtgtgt IS_SLUG()(abcampamp123)(abc123 None)gtgtgt IS_SLUG()(abcampamp123ampampdef)(abc123def None)gtgtgt IS_SLUG()(ntilde)(n None)gtgtgt IS_SLUG(maxlen=4)(abc123)(abc1 None)gtgtgt IS_SLUG()(abc_123)(abc-123 None)gtgtgt IS_SLUG(keep_underscores=False)(abc_123)(abc-123 None)gtgtgt IS_SLUG(keep_underscores=True)(abc_123)(abc_123 None)gtgtgt IS_SLUG(check=False)(abc)(abc None)gtgtgt IS_SLUG(check=True)(abc)(abc None)gtgtgt IS_SLUG(check=False)(a bc)(a-bc None)gtgtgt IS_SLUG(check=True)(a bc)(a bc must be slug)

static urlify(value maxlen=80 keep_underscores=False)

class gluonvalidatorsIS_STRONG(min=None max=None upper=None lower=Nonenumber=None entropy=None special=Nonespecials=rsquo~$^amp()_+-=ltgt []|rsquo invalid=rsquorsquo error_message=None es=False)

Bases object

Examples

Use as

INPUT(_type=password _name=passwdrequires=IS_STRONG(min=10 special=2 upper=2))

enforces complexity requirements on a field

gtgtgt IS_STRONG(es=True)(Abcd1234)(Abcd1234Must include at least 1 of the following ~$^amp()_+-=ltgt[]|)gtgtgt IS_STRONG(es=True)(Abcd1234)(Abcd1234 None)

(continues on next page)

371 Validators 165

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_STRONG(es=True entropy=1)(a)(a None)gtgtgt IS_STRONG(es=True entropy=1 min=2)(a)(a Minimum length is 2)gtgtgt IS_STRONG(es=True entropy=100)(abc123)(abc123 Entropy (3235) less than required (100))gtgtgt IS_STRONG(es=True entropy=100)(and)(and Entropy (1457) less than required (100))gtgtgt IS_STRONG(es=True entropy=100)(aaa)(aaa Entropy (1442) less than required (100))gtgtgt IS_STRONG(es=True entropy=100)(a1d)(a1d Entropy (1597) less than required (100))gtgtgt IS_STRONG(es=True entropy=100)(antilded)(axc3xb1d Entropy (1813) less than required (100))

class gluonvalidatorsIS_TIME(error_message=rsquoEnter time as hhmmss (seconds am pm op-tional)rsquo)

Bases gluonvalidatorsValidator

Example

Use as

INPUT(_type=text _name=name requires=IS_TIME())

understands the following formats hhmmss [ampm] hhmm [ampm] hh [ampm]

[ampm] is optional lsquorsquo can be replaced by any other non-space non-digit

gtgtgt IS_TIME()(2130)(datetimetime(21 30) None)gtgtgt IS_TIME()(21-30)(datetimetime(21 30) None)gtgtgt IS_TIME()(2130)(datetimetime(21 30) None)gtgtgt IS_TIME()(213059)(datetimetime(21 30 59) None)gtgtgt IS_TIME()(530)(datetimetime(5 30) None)gtgtgt IS_TIME()(530 am)(datetimetime(5 30) None)gtgtgt IS_TIME()(530 pm)(datetimetime(17 30) None)gtgtgt IS_TIME()(530 whatever)(530 whatever enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()(530 20)(530 20 enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()(2430)(2430 enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()(2160)(2160 enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()(2130)(2130 enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()()( enter time as hhmmss (seconds am pm optional))ugrave

166 Chapter 37 validators Module

web2py Documentation Release 2146-stable

class gluonvalidatorsIS_UPLOAD_FILENAME(filename=None extension=None lastdot=Truecase=1 error_message=rsquoEnter valid filenamersquo)

Bases gluonvalidatorsValidator

Checks if name and extension of file uploaded through file input matches given criteria

Does not ensure the file type in any way Returns validation failure if no data was uploaded

Parameters

bull filename ndash filename (before dot) regex

bull extension ndash extension (after dot) regex

bull lastdot ndash which dot should be used as a filename extension separator True means lastdot eg filepng -gt file png False means first dot eg filetargz -gt file targz

bull case ndash 0 - keep the case 1 - transform the string into lowercase (default) 2 - transform thestring into uppercase

If there is no dot present extension checks will be done against empty string and filename checks against wholevalue

Examples

Check if file has a pdf extension (case insensitive)

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_UPLOAD_FILENAME(extension=rsquopdfrsquo))

Check if file has a targz extension and name starting with backup

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_UPLOAD_FILENAME(filename=rsquobackuprsquo exten-sion=rsquotargzrsquo lastdot=False))

Check if file has no extension and name matching README (case sensitive)

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_UPLOAD_FILENAME(filename=rsquo^README$rsquoextension=rsquo^$rsquo case=0)

class gluonvalidatorsIS_UPPERBases gluonvalidatorsValidator

Converts to upper case

gtgtgt IS_UPPER()(abc)(ABC None)gtgtgt IS_UPPER()(ntilde)(xc3x91 None)

class gluonvalidatorsIS_URL(error_message=rsquoEnter a valid URLrsquo mode=rsquohttprsquo al-lowed_schemes=None prepend_scheme=rsquohttprsquo al-lowed_tlds=None)

Bases gluonvalidatorsValidator

Rejects a URL string if any of the following is true

bull The string is empty or None

bull The string uses characters that are not allowed in a URL

bull The string breaks any of the HTTP syntactic rules

bull The URL scheme specified (if one is specified) is not lsquohttprsquo or lsquohttpsrsquo

371 Validators 167

web2py Documentation Release 2146-stable

bull The top-level domain (if a host name is specified) does not exist

(These rules are based on RFC 2616 httpwwwfaqsorgrfcsrfc2616html)

This function only checks the URLrsquos syntax It does not check that the URL points to a real document forexample or that it otherwise makes sense semantically This function does automatically prepend lsquohttprsquo infront of a URL in the case of an abbreviated URL (eg lsquogooglecarsquo)

If the parameter mode=rsquogenericrsquo is used then this functionrsquos behavior changes It then rejects a URL string ifany of the following is true

bull The string is empty or None

bull The string uses characters that are not allowed in a URL

bull The URL scheme specified (if one is specified) is not valid

(These rules are based on RFC 2396 httpwwwfaqsorgrfcsrfc2396html)

The list of allowed schemes is customizable with the allowed_schemes parameter If you exclude None fromthe list then abbreviated URLs (lacking a scheme such as lsquohttprsquo) will be rejected

The default prepended scheme is customizable with the prepend_scheme parameter If you set prepend_schemeto None then prepending will be disabled URLs that require prepending to parse will still be accepted but thereturn value will not be modified

IS_URL is compatible with the Internationalized Domain Name (IDN) standard specified in RFC 3490 (httptoolsietforghtmlrfc3490) As a result URLs can be regular strings or unicode strings If the URLrsquos domaincomponent (eg googleca) contains non-US-ASCII letters then the domain will be converted into Punycode(defined in RFC 3492 httptoolsietforghtmlrfc3492) IS_URL goes a bit beyond the standards and allowsnon-US-ASCII characters to be present in the path and query components of the URL as well These non-US-ASCII characters will be escaped using the standard lsquo20rsquo type syntax eg the unicode character with hexcode 0x4e86 will become lsquo4e86rsquo

Parameters

bull error_message ndash a string the error message to give the end user if the URL does notvalidate

bull allowed_schemes ndash a list containing strings or None Each element is a scheme theinputed URL is allowed to use

bull prepend_scheme ndash a string this scheme is prepended if itrsquos necessary to make the URLvalid

Code Examples

INPUT(_type=text _name=name requires=IS_URL())gtgtgt IS_URL()(abccom)(httpabccom None)

INPUT(_type=text _name=name requires=IS_URL(mode=generic))gtgtgt IS_URL(mode=generic)(abccom)(abccom None)

INPUT(_type=text _name=namerequires=IS_URL(allowed_schemes=[https] prepend_scheme=https))

gtgtgt IS_URL(allowed_schemes=[https] prepend_scheme=https)(httpsabccom)(httpsabccom None)

INPUT(_type=text _name=namerequires=IS_URL(prepend_scheme=https))

(continues on next page)

168 Chapter 37 validators Module

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_URL(prepend_scheme=https)(abccom)(httpsabccom None)

INPUT(_type=text _name=namerequires=IS_URL(mode=generic allowed_schemes=[ftps https]

prepend_scheme=https))gtgtgt IS_URL(mode=generic allowed_schemes=[ftps https] prepend_scheme=rarr˓https)(httpsabccom)(httpsabccom None)gtgtgt IS_URL(mode=generic allowed_schemes=[ftps https None] prepend_rarr˓scheme=https)(abccom)(abccom None)

author Jonathan Benn

class gluonvalidatorsIS_JSON(error_message=rsquoInvalid jsonrsquo native_json=False)Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=namerequires=IS_JSON(error_message=This is not a valid json input)

gtgtgt IS_JSON()(a 100)(ua 100 None)

gtgtgt IS_JSON()(spam1234)(spam1234 invalid json)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

371 Validators 169

web2py Documentation Release 2146-stable

170 Chapter 37 validators Module

CHAPTER 38

widget Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

381 The widget is called from web2py

class gluonwidgetIOBases object

write(data)

gluonwidgetcheck_existent_app(options appname)

gluonwidgetconsole()Defines the behavior of the console web2py execution

gluonwidgetget_code_for_scheduler(app options)

gluonwidgetget_url(host path=rsquorsquo proto=rsquohttprsquo port=80)

gluonwidgetrun_system_tests(options)Runs unittests for gluontests

gluonwidgetstart(cron=True)Starts server

gluonwidgetstart_browser(url startup=False)

gluonwidgetstart_schedulers(options)

class gluonwidgetweb2pyDialog(root options)Bases object

Main window dialog

171

web2py Documentation Release 2146-stable

checkTaskBar()Checks taskbar status

connect_pages()Connects pages

error(message)Shows error message

quit(justHide=False)Finishes the program execution

server_ready()

start()Starts web2py server

start_schedulers(app)

stop()Stops web2py server

try_start_scheduler(app)

try_stop_scheduler(app)

update(text)Updates app text

update_canvas()Updates canvas

update_schedulers(start=False)

172 Chapter 38 widget Module

CHAPTER 39

xmlrpc Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

gluonxmlrpchandler(request response methods)

173

web2py Documentation Release 2146-stable

174 Chapter 39 xmlrpc Module

CHAPTER 40

Indices and tables

bull genindex

bull modindex

bull search

175

web2py Documentation Release 2146-stable

176 Chapter 40 Indices and tables

Python Module Index

ggluonadmin 3gluoncache 7gluoncfs 9gluoncompileapp 11gluoncontenttype 15gluoncustom_import 17gluondal 19gluondebug 21gluondecoder 23gluonfileutils 25gluonglobals 27gluonhighlight 33gluonhtml 35gluonhttp 51gluonlanguages 53gluonmain 57gluonmessageboxhandler 59gluonmyregex 61gluonnewcron 63gluonportalocker 65gluonrecfile 67gluonrestricted 69gluonrewrite 71gluonsanitizer 75gluonscheduler 77gluonserializers 83gluonsettings 85gluonshell 87gluonsql 89gluonsqlhtml 97gluonstorage 107gluonstreamer 111gluontemplate 113gluontools 117gluonutf8 139gluonutils 143gluonvalidators 145gluonwidget 171

gluonxmlrpc 173

177

web2py Documentation Release 2146-stable

178 Python Module Index

Index

AA (class in gluonhtml) 35absolute_path_link() (in module gluonnewcron) 63abspath() (in module gluonfileutils) 25accepts() (gluonhtmlFORM method) 41accepts() (gluonsqlhtmlSQLFORM method) 101accessible_query() (gluontoolsAuth method) 121acf() (gluonrewriteMapUrlOut method) 72acquire() (gluonnewcronToken method) 63action() (gluoncacheCache method) 7add_button() (gluonhtmlFORM method) 41add_class() (in module gluonsqlhtml) 104add_deps() (gluonschedulerJobGraph method) 77add_group() (gluontoolsAuth method) 121add_membership() (gluontoolsAuth method) 121add_path_first() (in module gluonadmin) 3add_permission() (gluontoolsAuth method) 122adj_hibernation() (gluonschedulerScheduler method)

79AES_new() (in module gluonutils) 143allows_jwt() (gluontoolsAuth method) 122amfrpc() (gluontoolsService method) 131amfrpc3() (gluontoolsService method) 131ANY_OF (class in gluonvalidators) 145apath() (in module gluonadmin) 3API_SERVER (gluontoolsRecaptcha attribute) 129API_SSL_SERVER (gluontoolsRecaptcha attribute)

129API_URI (gluontoolsRecaptcha2 attribute) 130app_cleanup() (in module gluonadmin) 3app_compile() (in module gluonadmin) 3app_create() (in module gluonadmin) 4app_install() (in module gluonadmin) 4app_pack() (in module gluonadmin) 4app_pack_compiled() (in module gluonadmin) 4app_uninstall() (in module gluonadmin) 4append() (gluonhtmlDIV method) 37append() (gluontemplateBlockNode method) 113append() (gluontemplateContent method) 114

appfactory() (in module gluonmain) 58apply_filter() (gluonlanguagestranslator method) 53archive() (gluontoolsAuth static method) 122archive() (gluontoolsCrud static method) 130arg0 (gluonrewriteMapUrlIn attribute) 71as_dict() (gluonhtmlFORM method) 41as_dict() (gluonsqlDAL method) 92as_dict() (gluonsqlDALField method) 91as_dict() (gluonsqlDALRow method) 91as_dict() (gluonsqlDALTable method) 92as_dict() (gluonsqlField method) 96as_json() (gluonhtmlFORM method) 41as_json() (gluonsqlDALRow method) 91as_xml() (gluonhtmlFORM method) 41as_xml() (gluonsqlDALRow method) 91as_yaml() (gluonhtmlFORM method) 41assert_status() (gluonhtmlFORM method) 41assert_status() (gluonsqlhtmlSQLFORM method) 101assign_tasks() (gluonschedulerScheduler method) 79ASSIGNJS() (in module gluonhtml) 35async() (gluonschedulerMetaScheduler method) 77Auth (class in gluontools) 121AutocompleteWidget (class in gluonsqlhtml) 97autoDetectXMLEncoding() (in module gluondecoder)

23autokey (gluoncacheCache attribute) 8automatic (gluonvalidatorsIS_IPV4 attribute) 158automenu() (gluontoolsWiki method) 135AUTOTYPES (gluonsqlhtmlSQLFORM attribute) 101

BB (class in gluonhtml) 36basic() (gluontoolsAuth method) 122BEAUTIFY (class in gluonhtml) 36being_a_ticker() (gluonschedulerScheduler method) 79BlockNode (class in gluontemplate) 113BODY (class in gluonhtml) 36body (gluonglobalsRequest attribute) 28BooleanWidget (class in gluonsqlhtml) 97BR (class in gluonhtml) 36

179

web2py Documentation Release 2146-stable

build_acf() (gluonrewriteMapUrlOut method) 72build_environment() (in module gluoncompileapp) 12build_query() (gluonsqlhtmlSQLFORM static method)

101build_set() (gluonvalidatorsIS_IN_DB method) 154bulk_insert() (gluonsqlDALTable method) 92bulk_register() (gluontoolsAuth method) 123BUTTON (class in gluonhtml) 36

CCache (class in gluoncache) 7CacheRepresenter (class in gluonsqlhtml) 97callback() (gluonsqlhtmlAutocompleteWidget method)

97can_edit() (gluontoolsWiki method) 135can_join() (gluonsqlDAL method) 92can_manage() (gluontoolsWiki method) 135can_read() (gluontoolsWiki method) 135can_search() (gluontoolsWiki method) 135can_see_menu() (gluontoolsWiki method) 135capitalize() (gluonutf8Utf8 method) 139cas_login() (gluontoolsAuth method) 123cas_validate() (gluontoolsAuth method) 123cast_keys() (in module gluonserializers) 83CAT (class in gluonhtml) 36CENTER (class in gluonhtml) 36center() (gluonutf8Utf8 method) 139change_password() (gluontoolsAuth method) 123check_credentials() (in module gluonfileutils) 26check_existent_app() (in module gluonwidget) 171check_interaction() (in module gluondebug) 22check_new_version() (in module gluonadmin) 4check_reserved_keyword() (gluonsqlDAL method) 92CheckboxesWidget (class in gluonsqlhtml) 97checkTaskBar() (gluonwidgetweb2pyDialog method)

171cleanpath() (in module gluonfileutils) 25CLEANUP (class in gluonvalidators) 145clear() (gluonglobalsSession method) 30clear_content() (gluontemplateContent method) 114clear_interaction() (gluondebugWebDebugger method)

21clear_session_cookies() (gluonglobalsSession method)

30clone() (gluonsqlDALField method) 91clone() (gluonsqlField method) 96close() (gluonportalockerLockedFile method) 65close() (gluonsqlDAL method) 92cloud() (gluontoolsWiki method) 135CODE (class in gluonhtml) 36COL (class in gluonhtml) 37COLGROUP (class in gluonhtml) 37commit() (gluonsqlDAL method) 92communicate() (in module gluondebug) 22

compare() (in module gluonutils) 143compile2() (in module gluonrestricted) 69compile_application() (in module gluoncompileapp) 12compile_controllers() (in module gluoncompileapp) 12compile_models() (in module gluoncompileapp) 12compile_regex() (in module gluonrewrite) 72compile_views() (in module gluoncompileapp) 12component() (gluontoolsWiki static method) 135compute_uuid() (gluonglobalsRequest method) 28confirm() (gluonhtmlFORM static method) 41confirm_registration() (gluontoolsAuth method) 123connect() (gluonglobalsSession method) 30connect_pages() (gluonwidgetweb2pyDialog method)

172console() (in module gluonwidget) 171Content (class in gluontemplate) 114content_type (gluonsqlhtmlExportClass attribute) 98content_type (gluonsqlhtmlExporterCSV attribute) 98content_type (gluonsqlhtmlExporterCSV_hidden

attribute) 98content_type (gluonsqlhtmlExporterHTML attribute)

98content_type (gluonsqlhtmlExporterJSON attribute) 98content_type (gluonsqlhtmlExporterTSV attribute) 99content_type (gluonsqlhtmlExporterXML attribute) 99contenttype() (in module gluoncontenttype) 15cookies2headers() (gluonhttpHTTP method) 51count() (gluonsqlDALField method) 91count() (gluonsqlField method) 96count() (gluonutf8Utf8 method) 139create() (gluontoolsCrud method) 130create() (gluontoolsWiki method) 135create_missing_app_folders() (in module gluonadmin) 5create_missing_folders() (in module gluonadmin) 5createform() (gluonsqlhtmlSQLFORM method) 102crondance() (in module gluonnewcron) 63cronlauncher (class in gluonnewcron) 63Crud (class in gluontools) 130CRYPT (class in gluonvalidators) 146csv() (gluontoolsService method) 132csv() (in module gluonserializers) 83custom_import_install() (in module

gluoncustom_import) 17custom_importer() (in module gluoncustom_import) 17custom_json() (in module gluonserializers) 83CustomImportException 17

DDAL (class in gluonsql) 89DALField (class in gluonsql) 91DALRow (class in gluonsql) 91DALTable (class in gluonsql) 92DatetimeWidget (class in gluonsqlhtml) 98DateWidget (class in gluonsqlhtml) 98

180 Index

web2py Documentation Release 2146-stable

DecimalWidget (class in gluonsqlhtml) 98decode() (gluonutf8Utf8 method) 139decoder() (in module gluondecoder) 23default_delimiters (gluontemplateTemplateParser

attribute) 115default_messages (gluontoolsAuth attribute) 123default_settings (gluontoolsAuth attribute) 124DEFAULT_WIDTH (gluonsqlhtmlUploadWidget

attribute) 104define_signature() (gluontoolsAuth method) 125define_table() (gluonsqlDAL method) 93define_tables() (gluonschedulerScheduler method) 79define_tables() (gluontoolsAuth method) 125del_group() (gluontoolsAuth method) 125del_membership() (gluontoolsAuth method) 125del_permission() (gluontoolsAuth method) 125delete() (gluontoolsCrud method) 130DELETE_FILE (gluonsqlhtmlUploadWidget attribute)

104dictform() (gluonsqlhtmlSQLFORM static method) 102die() (gluonschedulerMetaScheduler method) 78die() (in module gluonshell) 87disable() (gluonschedulerScheduler method) 79distributed_transaction_begin() (gluonsqlDAL static

method) 93distributed_transaction_commit() (gluonsqlDAL static

method) 93DIV (class in gluonhtml) 37do_continue() (gluondebugWebDebugger method) 21do_exec() (gluondebugWebDebugger method) 21do_next() (gluondebugWebDebugger method) 21do_quit() (gluondebugWebDebugger method) 21do_return() (gluondebugWebDebugger method) 21do_step() (gluondebugWebDebugger method) 21DoubleWidget (class in gluonsqlhtml) 98download() (gluonglobalsResponse method) 28drop() (gluonsqlDALTable method) 92DummyResponse (class in gluontemplate) 114

Eedit() (gluontoolsWiki method) 135editmedia() (gluontoolsWiki method) 135element() (gluonhtmlDIV method) 38elements() (gluonhtmlDIV method) 38elements() (gluonhtmlXML method) 49EM (class in gluonhtml) 40email_registration() (gluontoolsAuth method) 125email_reset_password() (gluontoolsAuth method) 125EMBED (class in gluonhtml) 40embed64() (in module gluonhtml) 50emit() (gluonmessageboxhandlerMessageBoxHandler

method) 59emit() (gluonmessageboxhandlerNotifySendHandler

method) 59

enable_autocomplete_and_history() (in modulegluonshell) 87

enable_record_versioning() (gluontoolsAuth method)125

encode() (gluonutf8Utf8 method) 140endswith() (gluonutf8Utf8 method) 140env() (in module gluonshell) 87error() (gluontoolsService method) 132error() (gluonwidgetweb2pyDialog method) 172everybody (gluontoolsWiki attribute) 135exception() (gluondebugWebDebugger method) 21exec_environment() (in module gluonshell) 87exec_pythonrc() (in module gluonshell) 87execute_from_command_line() (in module gluonshell)

87executesql() (gluonsqlDAL method) 93executor() (in module gluonscheduler) 82exists() (in module gluonrecfile) 67expandtabs() (gluonutf8Utf8 method) 140export() (gluonsqlhtmlExportClass method) 98export() (gluonsqlhtmlExporterCSV method) 98export() (gluonsqlhtmlExporterCSV_hidden method)

98export() (gluonsqlhtmlExporterHTML method) 98export() (gluonsqlhtmlExporterJSON method) 98export() (gluonsqlhtmlExporterTSV method) 99export() (gluonsqlhtmlExporterXML method) 99export_to_csv_file() (gluonsqlDAL method) 93ExportClass (class in gluonsqlhtml) 98ExporterCSV (class in gluonsqlhtml) 98ExporterCSV_hidden (class in gluonsqlhtml) 98ExporterHTML (class in gluonsqlhtml) 98ExporterJSON (class in gluonsqlhtml) 98ExporterTSV (class in gluonsqlhtml) 99ExporterXML (class in gluonsqlhtml) 99extcron (class in gluonnewcron) 63extend() (gluontemplateBlockNode method) 113extend() (gluontemplateContent method) 114extend() (gluontemplateTemplateParser method) 115

Ffactory() (gluonsqlhtmlSQLFORM static method) 102fast_urandom16() (in module gluonutils) 143fetch() (in module gluontools) 137Field (class in gluonsql) 95FIELDKEY_DELETE_RECORD

(gluonsqlhtmlSQLFORM attribute) 101FIELDNAME_REQUEST_DELETE

(gluonsqlhtmlSQLFORM attribute) 101fields (gluonsqlDALTable attribute) 92FIELDSET (class in gluonhtml) 40file_ext (gluonsqlhtmlExportClass attribute) 98file_ext (gluonsqlhtmlExporterCSV attribute) 98

Index 181

web2py Documentation Release 2146-stable

file_ext (gluonsqlhtmlExporterCSV_hidden attribute)98

file_ext (gluonsqlhtmlExporterHTML attribute) 98file_ext (gluonsqlhtmlExporterJSON attribute) 98file_ext (gluonsqlhtmlExporterTSV attribute) 99file_ext (gluonsqlhtmlExporterXML attribute) 99filter_err() (in module gluonrewrite) 72filter_url() (in module gluonrewrite) 72find() (gluonutf8Utf8 method) 140find_exposed_functions() (in module gluoncompileapp)

12findT() (in module gluonlanguages) 55first_paragraph() (gluontoolsWiki method) 135fix_hostname() (gluontoolsWiki method) 135fix_newlines() (in module gluonfileutils) 26fixup_missing_path_info() (in module gluonrewrite) 72flatten() (gluonhtmlDIV method) 39flatten() (gluonhtmlMARKMIN method) 44flatten() (gluonhtmlXML method) 49flush() (gluondebugPipe method) 21force() (gluonlanguagestranslator method) 53forget() (gluonglobalsSession method) 30FORM (class in gluonhtml) 40form_factory() (in module gluonsqlhtml) 104format() (gluonutf8Utf8 method) 140formatter() (gluonsqlDALField method) 91formatter() (gluonsqlField method) 96formatter() (gluonvalidatorsANY_OF method) 145formatter() (gluonvalidatorsIS_DATE method) 148formatter() (gluonvalidatorsIS_DATETIME method)

149formatter() (gluonvalidatorsIS_DECIMAL_IN_RANGE

method) 150formatter() (gluonvalidatorsIS_EMPTY_OR method)

152formatter() (gluonvalidatorsIS_FLOAT_IN_RANGE

method) 153formatter() (gluonvalidatorsIS_JSON method) 169formatter() (gluonvalidatorsIS_LIST_OF_EMAILS

method) 152formstyle_bootstrap() (in module gluonsqlhtml) 105formstyle_bootstrap3_inline_factory() (in module

gluonsqlhtml) 105formstyle_bootstrap3_stacked() (in module

gluonsqlhtml) 105formstyle_divs() (in module gluonsqlhtml) 105formstyle_inline() (in module gluonsqlhtml) 105formstyle_table2cols() (in module gluonsqlhtml) 105formstyle_table3cols() (in module gluonsqlhtml) 105formstyle_ul() (in module gluonsqlhtml) 105formstyles (gluonsqlhtmlSQLFORM attribute) 102FormWidget (class in gluonsqlhtml) 99frameset (gluonhtmlHTML attribute) 43frameset (gluonhtmlXHTML attribute) 49

Ggenerate() (in module gluonrecfile) 67GENERIC_DESCRIPTION

(gluonsqlhtmlUploadWidget attribute)104

geocode() (in module gluontools) 137get() (gluonhtmlDIV method) 39get() (gluonsqlDALRow method) 91get_callable_argspec() (in module gluonutils) 143get_code_for_scheduler() (in module gluonwidget) 171get_digest() (in module gluonutils) 143get_effective_router() (in module gluonrewrite) 72get_format() (gluontoolsCrud method) 130get_instances() (gluonsqlDAL static method) 93get_or_create_key() (gluontoolsAuth static method)

125get_or_create_user() (gluontoolsAuth method) 125get_parsed() (in module gluontemplate) 115get_possible_languages() (gluonlanguagestranslator

method) 54get_possible_languages_info()

(gluonlanguagestranslator method) 54get_query() (gluontoolsCrud method) 130get_renderer() (gluontoolsWiki method) 135get_session() (in module gluonfileutils) 26get_t() (gluonlanguagestranslator method) 54get_url() (in module gluonwidget) 171get_usage() (in module gluonshell) 87get_vars (gluonglobalsRequest attribute) 28get_vars_next() (gluontoolsAuth method) 126get_workers() (gluonschedulerScheduler method) 79getcfs() (in module gluoncfs) 9getfirst() (gluonstorageStorage method) 108getipaddrinfo() (in module gluonutils) 143getlast() (gluonstorageStorage method) 108getlist() (gluonstorageStorage method) 108give_up() (gluonschedulerMetaScheduler method) 78gluonadmin (module) 3gluoncache (module) 7gluoncfs (module) 9gluoncompileapp (module) 11gluoncontenttype (module) 15gluoncustom_import (module) 17gluondal (module) 19gluondebug (module) 21gluondecoder (module) 23gluonfileutils (module) 25gluonglobals (module) 27gluonhighlight (module) 33gluonhtml (module) 35gluonhttp (module) 51gluonlanguages (module) 53gluonmain (module) 57gluonmessageboxhandler (module) 59

182 Index

web2py Documentation Release 2146-stable

gluonmyregex (module) 61gluonnewcron (module) 63gluonportalocker (module) 65gluonrecfile (module) 67gluonrestricted (module) 69gluonrewrite (module) 71gluonsanitizer (module) 75gluonscheduler (module) 77gluonserializers (module) 83gluonsettings (module) 85gluonshell (module) 87gluonsql (module) 89gluonsqlhtml (module) 97gluonstorage (module) 107gluonstreamer (module) 111gluontemplate (module) 113gluontools (module) 117gluonutf8 (module) 139gluonutils (module) 143gluonvalidators (module) 145gluonwidget (module) 171gluonxmlrpc (module) 173grid() (gluonsqlhtmlSQLFORM static method) 102groups() (gluontoolsAuth method) 126

HH1 (class in gluonhtml) 42H2 (class in gluonhtml) 42H3 (class in gluonhtml) 42H4 (class in gluonhtml) 42H5 (class in gluonhtml) 42H6 (class in gluonhtml) 42handler() (in module gluonxmlrpc) 173hardcron (class in gluonnewcron) 64harg0 (gluonrewriteMapUrlIn attribute) 71has_membership() (gluontoolsAuth method) 126has_options() (gluonsqlhtmlOptionsWidget static

method) 100has_permission() (gluontoolsAuth method) 126has_permission() (gluontoolsCrud method) 130has_representer() (gluonsqlDAL method) 94HEAD (class in gluonhtml) 42here() (gluontoolsAuth method) 126hidden_fields() (gluonhtmlFORM method) 41highlight() (in module gluonhighlight) 33HR (class in gluonhtml) 42HTML (class in gluonhtml) 42html5 (gluonhtmlHTML attribute) 43html_render() (gluontoolsWiki method) 135HTTP 51HttpServer (class in gluonmain) 58

II (class in gluonhtml) 43

ics() (in module gluonserializers) 83ID_DELETE_SUFFIX (gluonsqlhtmlUploadWidget at-

tribute) 104id_group() (gluontoolsAuth method) 126ID_LABEL_SUFFIX (gluonsqlhtmlSQLFORM at-

tribute) 101ID_ROW_SUFFIX (gluonsqlhtmlSQLFORM attribute)

101IFRAME (class in gluonhtml) 43IMG (class in gluonhtml) 43impersonate() (gluontoolsAuth method) 126import_from_csv_file() (gluonsqlDAL method) 94import_from_csv_file() (gluonsqlDALTable method)

92import_table_definitions() (gluonsqlDAL method) 94include() (gluontemplateTemplateParser method) 115include_files() (gluonglobalsResponse method) 28include_meta() (gluonglobalsResponse method) 28index() (gluonutf8Utf8 method) 140initialize_urandom() (in module gluonutils) 143INPUT (class in gluonhtml) 43insert() (gluonhtmlDIV method) 40insert() (gluonsqlDALTable method) 92insert() (gluontemplateContent method) 114instances (gluontoolsPluginManager attribute) 137IntegerWidget (class in gluonsqlhtml) 99interaction() (gluondebugWebDebugger method) 22invalid_url() (in module gluonrewrite) 72IO (class in gluonwidget) 171IS_ALPHANUMERIC (class in gluonvalidators) 147IS_DATE (class in gluonvalidators) 148IS_DATE_IN_RANGE (class in gluonvalidators) 147IS_DATETIME (class in gluonvalidators) 148IS_DATETIME_IN_RANGE (class in gluonvalidators)

148IS_DECIMAL_IN_RANGE (class in gluonvalidators)

149IS_EMAIL (class in gluonvalidators) 150IS_EMPTY_OR (class in gluonvalidators) 152IS_EQUAL_TO (class in gluonvalidators) 163is_expired() (gluonglobalsSession method) 30IS_EXPR (class in gluonvalidators) 152IS_FLOAT_IN_RANGE (class in gluonvalidators) 153IS_IMAGE (class in gluonvalidators) 153is_image() (gluonsqlhtmlUploadWidget static method)

104is_impersonating() (gluontoolsAuth method) 126IS_IN_DB (class in gluonvalidators) 154IS_IN_SET (class in gluonvalidators) 154IS_INT_IN_RANGE (class in gluonvalidators) 155IS_IPADDRESS (class in gluonvalidators) 159IS_IPV4 (class in gluonvalidators) 156IS_IPV6 (class in gluonvalidators) 158IS_JSON (class in gluonvalidators) 169

Index 183

web2py Documentation Release 2146-stable

IS_LENGTH (class in gluonvalidators) 161IS_LIST_OF (class in gluonvalidators) 162IS_LIST_OF_EMAILS (class in gluonvalidators) 152is_logged_in() (gluontoolsAuth method) 126is_loopback_ip_address() (in module gluonutils) 144IS_LOWER (class in gluonvalidators) 162IS_MATCH (class in gluonvalidators) 162is_new() (gluonglobalsSession method) 30IS_NOT_EMPTY (class in gluonvalidators) 163IS_NOT_IN_DB (class in gluonvalidators) 164IS_NULL_OR (in module gluonvalidators) 164IS_SLUG (class in gluonvalidators) 164IS_STRONG (class in gluonvalidators) 165IS_TIME (class in gluonvalidators) 166is_tracking_changes() (in module gluoncustom_import)

17IS_UPLOAD_FILENAME (class in gluonvalidators)

166IS_UPPER (class in gluonvalidators) 167IS_URL (class in gluonvalidators) 167is_valid_ip_address() (in module gluonutils) 144isalnum() (gluonutf8Utf8 method) 140isalpha() (gluonutf8Utf8 method) 140isdigit() (gluonutf8Utf8 method) 140islower() (gluonutf8Utf8 method) 140isodatetime (gluonvalidatorsIS_DATETIME attribute)

149isspace() (gluonutf8Utf8 method) 140istitle() (gluonutf8Utf8 method) 140isupper() (gluonutf8Utf8 method) 140

JJobGraph (class in gluonscheduler) 77join() (gluonutf8Utf8 method) 140json() (gluonglobalsResponse method) 28json() (gluontoolsService method) 132json() (in module gluonserializers) 83jsonrpc() (gluontoolsService method) 132jsonrpc2() (gluontoolsService method) 132jsonrpc_errors (gluontoolsService attribute) 133JSONWidget (class in gluonsqlhtml) 99jwt() (gluontoolsAuth method) 126

Kkeys() (gluontoolsPluginManager method) 137kill() (gluonschedulerScheduler method) 79

LLABEL (class in gluonhtml) 44label (gluonsqlhtmlExportClass attribute) 98label (gluonsqlhtmlExporterCSV attribute) 98label (gluonsqlhtmlExporterCSV_hidden attribute) 98label (gluonsqlhtmlExporterHTML attribute) 98label (gluonsqlhtmlExporterJSON attribute) 98

label (gluonsqlhtmlExporterTSV attribute) 99label (gluonsqlhtmlExporterXML attribute) 99launch() (gluonnewcronhardcron method) 64Lazy (gluonsqlDALField attribute) 91Lazy (gluonsqlField attribute) 95lazy_cache() (in module gluoncache) 8lazy_define_table() (gluonsqlDAL method) 94LEGEND (class in gluonhtml) 44LI (class in gluonhtml) 44LINK (class in gluonhtml) 44List (class in gluonstorage) 107listdir() (in module gluonfileutils) 25ListWidget (class in gluonsqlhtml) 99ljust() (gluonutf8Utf8 method) 140load() (gluonrestrictedRestrictedError method) 69load() (gluonrestrictedTicketStorage method) 69LOAD() (in module gluoncompileapp) 11load() (in module gluonrewrite) 72load_routers() (in module gluonrewrite) 73load_storage() (in module gluonstorage) 109LoadFactory (class in gluoncompileapp) 12loads_json() (in module gluonserializers) 83loads_yaml() (in module gluonserializers) 83local_import_aux() (in module gluoncompileapp) 12localhost (gluonvalidatorsIS_IPV4 attribute) 158lock() (in module gluonportalocker) 66LockedFile (class in gluonportalocker) 65log() (gluonrestrictedRestrictedError method) 69log_event() (gluontoolsAuth method) 127log_event() (gluontoolsCrud method) 130log_rewrite() (in module gluonrewrite) 73logger (gluonsqlDAL attribute) 94login() (gluontoolsAuth method) 127login_bare() (gluontoolsAuth method) 127login_user() (gluontoolsAuth method) 127logout() (gluontoolsAuth method) 127logout_bare() (gluontoolsAuth method) 127loop() (gluonschedulerMetaScheduler method) 78loop() (gluonschedulerScheduler method) 79lower() (gluonutf8Utf8 method) 141lstrip() (gluonutf8Utf8 method) 141

MM() (gluonlanguagestranslator method) 53Mail (class in gluontools) 117MailAttachment (class in gluontools) 118main() (in module gluonscheduler) 82make_fake_file_like_object() (in module gluonfileutils)

26manage_tokens() (gluontoolsAuth method) 127map_app() (gluonrewriteMapUrlIn method) 71map_controller() (gluonrewriteMapUrlIn method) 71map_function() (gluonrewriteMapUrlIn method) 71map_language() (gluonrewriteMapUrlIn method) 71

184 Index

web2py Documentation Release 2146-stable

map_prefix() (gluonrewriteMapUrlIn method) 71map_root_static() (gluonrewriteMapUrlIn method) 72map_static() (gluonrewriteMapUrlIn method) 72map_url_in() (in module gluonrewrite) 73map_url_out() (in module gluonrewrite) 73MapUrlIn (class in gluonrewrite) 71MapUrlOut (class in gluonrewrite) 72MARKMIN (class in gluonhtml) 44markmin_base() (gluontoolsWiki method) 135markmin_render() (gluontoolsWiki method) 135maybe_add() (gluonvalidatorsIS_IN_DB method) 154md5_hash() (in module gluonutils) 144media() (gluontoolsWiki method) 135MENU (class in gluonhtml) 44menu() (gluontoolsWiki method) 135message (gluonhttpHTTP attribute) 51MessageBoxHandler (class in

gluonmessageboxhandler) 59Messages (class in gluonstorage) 108META (class in gluonhtml) 45MetaScheduler (class in gluonscheduler) 77Method (gluonsqlDALField attribute) 91Method (gluonsqlField attribute) 95mktree() (in module gluonfileutils) 25model_cmp() (in module gluoncompileapp) 12model_cmp_sep() (in module gluoncompileapp) 12MultipleOptionsWidget (class in gluonsqlhtml) 99mybuiltin (class in gluoncompileapp) 12

Nnavbar() (gluontoolsAuth method) 127nice() (gluonvalidatorsIS_DATETIME static method)

149no_underscore() (gluonhtmlBEAUTIFY static method)

36Node (class in gluontemplate) 114NOESCAPE (class in gluontemplate) 114not_authorized() (gluontoolsAuth method) 127not_authorized() (gluontoolsWiki method) 135NotifySendHandler (class in gluonmessageboxhandler)

59now() (gluonschedulerScheduler method) 79numbers (gluonvalidatorsIS_IPV4 attribute) 158

OOBJECT (class in gluonhtml) 45OL (class in gluonhtml) 44omit_acf() (gluonrewriteMapUrlOut method) 72omit_lang() (gluonrewriteMapUrlOut method) 72on() (gluonsqlDALTable method) 92open() (in module gluonrecfile) 67OPTGROUP (class in gluonhtml) 45OPTION (class in gluonhtml) 45options() (gluonvalidatorsIS_IN_DB method) 154

options() (gluonvalidatorsIS_IN_SET method) 155OptionsWidget (class in gluonsqlhtml) 100output() (gluontemplateBlockNode method) 113output_aux() (in module gluontemplate) 115

PP (class in gluonhtml) 45PACKAGE_PATH_SUFFIX

(gluoncustom_importTrackImporter at-tribute) 17

pad() (in module gluonutils) 144pages() (gluontoolsWiki method) 136params_substitution() (gluonlanguagestranslator

method) 54parse() (gluontemplateTemplateParser method) 115parse_all_vars() (gluonglobalsRequest method) 28parse_as_rest() (gluonsqlDAL method) 94parse_get_vars() (gluonglobalsRequest method) 28parse_path_info() (in module gluonshell) 87parse_post_vars() (gluonglobalsRequest method) 28parse_template() (in module gluontemplate) 115parse_version() (in module gluonfileutils) 25parsecronline() (in module gluonnewcron) 64partition() (gluonutf8Utf8 method) 141PasswordWidget (class in gluonsqlhtml) 100pbkdf2_hex() (in module gluonutils) 144Pipe (class in gluondebug) 21plugin_install() (in module gluonadmin) 5plugin_pack() (in module gluonadmin) 5PluginManager (class in gluontools) 136plural() (gluonlanguagestranslator method) 55pop_arg_if() (gluonrewriteMapUrlIn method) 72pop_task() (gluonschedulerMetaScheduler method) 78pop_task() (gluonschedulerScheduler method) 79post_vars (gluonglobalsRequest attribute) 28PRE (class in gluonhtml) 45prettydate() (in module gluontools) 137preview() (gluontoolsWiki method) 136private (gluonvalidatorsIS_IPV4 attribute) 158process() (gluonhtmlFORM method) 41profile() (gluontoolsAuth method) 127

Qqueue_task() (gluonschedulerScheduler method) 79quit() (gluonwidgetweb2pyDialog method) 172

Rr_multiline (gluontemplateTemplateParser attribute)

115r_tag (gluontemplateTemplateParser attribute) 115RadioWidget (class in gluonsqlhtml) 100random_password() (gluontoolsAuth method) 127rangetolist() (in module gluonnewcron) 64re_block (gluontemplateTemplateParser attribute) 115

Index 185

web2py Documentation Release 2146-stable

re_compile() (in module gluoncompileapp) 12re_pass (gluontemplateTemplateParser attribute) 115re_unblock (gluontemplateTemplateParser attribute)

115read() (gluondebugPipe method) 21read() (gluonportalockerLockedFile method) 66read() (gluontoolsCrud method) 130read() (gluontoolsWiki method) 136read_file() (in module gluonfileutils) 25read_locked() (in module gluonportalocker) 66read_pyc() (in module gluoncompileapp) 12readline() (gluondebugPipe method) 21readline() (gluonportalockerLockedFile method) 66readlines() (gluonportalockerLockedFile method) 66readlines_file() (in module gluonfileutils) 25Recaptcha (class in gluontools) 129Recaptcha2 (class in gluontools) 129recursive_unlink() (in module gluonfileutils) 25redirect() (in module gluonhttp) 51REDIRECT_JS (gluonhtmlFORM attribute) 41regex (gluonvalidatorsIS_EMAIL attribute) 151regex (gluonvalidatorsIS_IPV4 attribute) 158regex_attr (gluonhtmlDIV attribute) 40regex_class (gluonhtmlDIV attribute) 40REGEX_CLEANUP (gluonvalidatorsCLEANUP

attribute) 146regex_filter_in() (in module gluonrewrite) 73regex_filter_out() (in module gluonrewrite) 73regex_id (gluonhtmlDIV attribute) 40regex_proposed_but_failed (gluonvalidatorsIS_EMAIL

attribute) 151regex_select() (in module gluonrewrite) 73regex_tag (gluonhtmlDIV attribute) 40regex_uri() (in module gluonrewrite) 73regex_url_in() (in module gluonrewrite) 73register() (gluontoolsAuth method) 127register_bare() (gluontoolsAuth method) 127reindent() (gluontemplateTemplateParser method) 115release() (gluonnewcronToken method) 63remove() (in module gluonrecfile) 67remove_compiled_application() (in module

gluoncompileapp) 12render() (gluonglobalsResponse method) 28render() (in module gluontemplate) 115render_tags() (gluontoolsWiki method) 136renew() (gluonglobalsSession method) 30replace() (gluonutf8Utf8 method) 141report_task() (gluonschedulerMetaScheduler method)

78report_task() (gluonschedulerScheduler method) 80represent() (gluonsqlDAL method) 94represent() (gluonsqlhtmlUploadWidget class method)

104represent() (in module gluonsqlhtml) 105

represented() (gluonsqlhtmlExportClass method) 98representers (gluonsqlDAL attribute) 94Request (class in gluonglobals) 27request_reset_password() (gluontoolsAuth method) 127requires() (gluontoolsAuth method) 127requires_https() (gluonglobalsRequest method) 28requires_login() (gluontoolsAuth method) 127requires_login_or_token() (gluontoolsAuth method)

127requires_membership() (gluontoolsAuth method) 128requires_permission() (gluontoolsAuth method) 128requires_signature() (gluontoolsAuth method) 128reset_password() (gluontoolsAuth method) 128reset_password_deprecated() (gluontoolsAuth method)

128Response (class in gluonglobals) 28restful() (gluonglobalsRequest method) 28restricted() (in module gluonrestricted) 69RestrictedError 69resume() (gluonschedulerScheduler method) 80retrieve() (gluonsqlDALField method) 91retrieve() (gluonsqlField method) 96retrieve_file_properties() (gluonsqlDALField method)

91retrieve_file_properties() (gluonsqlField method) 96retrieve_password() (gluontoolsAuth method) 128retrieve_username() (gluontoolsAuth method) 128reverse_geocode() (in module gluontools) 137rfind() (gluonutf8Utf8 method) 141rindex() (gluonutf8Utf8 method) 141rjust() (gluonutf8Utf8 method) 141rollback() (gluonsqlDAL method) 94rows() (gluontoolsCrud method) 130rows_page (gluontoolsWiki attribute) 136rpartition() (gluonutf8Utf8 method) 141rsplit() (gluonutf8Utf8 method) 141rss() (gluontoolsService method) 133rss() (in module gluonserializers) 83rstrip() (gluonutf8Utf8 method) 141run() (gluondebugWebDebugger method) 22run() (gluonnewcroncronlauncher method) 63run() (gluonnewcronextcron method) 64run() (gluonnewcronhardcron method) 64run() (gluonnewcronsoftcron method) 64run() (gluonschedulerMetaScheduler method) 78run() (gluontoolsService method) 133run() (in module gluonshell) 88run_controller_in() (in module gluoncompileapp) 13run_login_onaccept() (gluontoolsAuth method) 128run_models_in() (in module gluoncompileapp) 13run_system_tests() (in module gluonwidget) 171run_view_in() (in module gluoncompileapp) 13

186 Index

web2py Documentation Release 2146-stable

Ssafe_encode() (in module gluonserializers) 83safe_float() (in module gluonsqlhtml) 105safe_int() (in module gluonsqlhtml) 105sanitize() (in module gluonsanitizer) 75save_password() (in module gluonmain) 58save_pyc() (in module gluoncompileapp) 13save_session_id_cookie() (gluonglobalsSession

method) 31save_storage() (in module gluonstorage) 109Scheduler (class in gluonscheduler) 78SCRIPT (class in gluonhtml) 45search() (gluontoolsCrud method) 130search() (gluontoolsWiki method) 136search_menu() (gluonsqlhtmlSQLFORM static

method) 102secure() (gluonglobalsSession method) 31secure_dumps() (in module gluonutils) 144secure_loads() (in module gluonutils) 144SELECT (class in gluonhtml) 45select() (gluontoolsCrud method) 131select_host() (gluontoolsAuth method) 128send() (gluontoolsMail method) 119send_heartbeat() (gluonschedulerMetaScheduler

method) 78send_heartbeat() (gluonschedulerScheduler method) 80serialize() (gluonhtmlMENU method) 45serialize_mobile() (gluonhtmlMENU method) 45serializers (gluonsqlDAL attribute) 95serve_amfrpc() (gluontoolsService method) 133serve_csv() (gluontoolsService method) 134serve_json() (gluontoolsService method) 134serve_jsonrpc() (gluontoolsService method) 134serve_jsonrpc2() (gluontoolsService method) 134serve_rss() (gluontoolsService method) 134serve_run() (gluontoolsService method) 134serve_soap() (gluontoolsService method) 134serve_xml() (gluontoolsService method) 134serve_xmlrpc() (gluontoolsService method) 134server_ready() (gluonwidgetweb2pyDialog method)

172Service (class in gluontools) 131ServiceJsonRpcException 131Session (class in gluonglobals) 29set_attributes() (gluonsqlDALField method) 91set_attributes() (gluonsqlField method) 96set_current_languages() (gluonlanguagestranslator

method) 55set_folder() (gluonsqlDAL static method) 95set_requirements() (gluonschedulerScheduler method)

80set_self_id() (gluonvalidatorsIS_EMPTY_OR method)

152set_self_id() (gluonvalidatorsIS_IN_DB method) 154

set_self_id() (gluonvalidatorsIS_NOT_IN_DB method)164

set_trace() (in module gluondebug) 22set_worker_status() (gluonschedulerScheduler method)

80Settings (class in gluonstorage) 108show_if() (in module gluonsqlhtml) 105sibling() (gluonhtmlDIV method) 40siblings() (gluonhtmlDIV method) 40simple_hash() (in module gluonutils) 144sleep() (gluonschedulerMetaScheduler method) 78sleep() (gluonschedulerScheduler method) 80sluggify() (gluonrewriteMapUrlIn method) 72sluggify() (in module gluonrewrite) 73smart_query() (gluonsqlDAL method) 95smartdictform() (gluonsqlhtmlSQLFORM static

method) 102smartgrid() (gluonsqlhtmlSQLFORM static method)

102soap() (gluontoolsService method) 134softcron (class in gluonnewcron) 64SPAN (class in gluonhtml) 46split() (gluonutf8Utf8 method) 141split_emails (gluonvalidatorsIS_LIST_OF_EMAILS at-

tribute) 152splitlines() (gluonutf8Utf8 method) 141SQLFORM (class in gluonsqlhtml) 100sqlsafe (gluonsqlDALField attribute) 91sqlsafe (gluonsqlDALTable attribute) 92sqlsafe (gluonsqlField attribute) 96sqlsafe_alias (gluonsqlDALTable attribute) 92sqlsafe_name (gluonsqlDALField attribute) 91sqlsafe_name (gluonsqlField attribute) 96SQLTABLE (class in gluonsqlhtml) 103start() (gluonmainHttpServer method) 58start() (gluonwidgetweb2pyDialog method) 172start() (in module gluonwidget) 171start_browser() (in module gluonwidget) 171start_heartbeats() (gluonschedulerMetaScheduler

method) 78start_schedulers() (gluonwidgetweb2pyDialog method)

172start_schedulers() (in module gluonwidget) 171startswith() (gluonutf8Utf8 method) 141stop() (gluonmainHttpServer method) 58stop() (gluonwidgetweb2pyDialog method) 172stop_task() (gluonschedulerScheduler method) 80stop_trace() (in module gluondebug) 22stopcron() (in module gluonnewcron) 64Storage (class in gluonstorage) 107StorageList (class in gluonstorage) 109store() (gluonrestrictedTicketStorage method) 69store() (gluonsqlDALField method) 91store() (gluonsqlField method) 96

Index 187

web2py Documentation Release 2146-stable

stream() (gluonglobalsResponse method) 28stream_file_or_304_or_206() (in module

gluonstreamer) 111streamer() (in module gluonstreamer) 111strict (gluonhtmlHTML attribute) 43strict (gluonhtmlXHTML attribute) 49StringWidget (class in gluonsqlhtml) 103strip() (gluonutf8Utf8 method) 141STRONG (class in gluonhtml) 46STYLE (class in gluonhtml) 46style() (gluonsqlhtmlSQLTABLE method) 103SuperNode (class in gluontemplate) 114swapcase() (gluonutf8Utf8 method) 142

TTABLE (class in gluonhtml) 46table_cas() (gluontoolsAuth method) 128table_event() (gluontoolsAuth method) 128table_group() (gluontoolsAuth method) 128table_membership() (gluontoolsAuth method) 128table_permission() (gluontoolsAuth method) 128table_token() (gluontoolsAuth method) 128table_user() (gluontoolsAuth method) 128tables (gluonsqlDAL attribute) 95tables() (gluontoolsCrud method) 131tag (gluonhtmlA attribute) 35tag (gluonhtmlB attribute) 36tag (gluonhtmlBEAUTIFY attribute) 36tag (gluonhtmlBODY attribute) 36tag (gluonhtmlBR attribute) 36tag (gluonhtmlBUTTON attribute) 36tag (gluonhtmlCAT attribute) 36tag (gluonhtmlCENTER attribute) 36tag (gluonhtmlCOL attribute) 37tag (gluonhtmlCOLGROUP attribute) 37tag (gluonhtmlDIV attribute) 40tag (gluonhtmlEM attribute) 40tag (gluonhtmlEMBED attribute) 40tag (gluonhtmlFIELDSET attribute) 40tag (gluonhtmlFORM attribute) 41tag (gluonhtmlH1 attribute) 42tag (gluonhtmlH2 attribute) 42tag (gluonhtmlH3 attribute) 42tag (gluonhtmlH4 attribute) 42tag (gluonhtmlH5 attribute) 42tag (gluonhtmlH6 attribute) 42tag (gluonhtmlHEAD attribute) 42tag (gluonhtmlHR attribute) 42tag (gluonhtmlHTML attribute) 43tag (gluonhtmlI attribute) 43tag (gluonhtmlIFRAME attribute) 43tag (gluonhtmlIMG attribute) 43tag (gluonhtmlINPUT attribute) 44tag (gluonhtmlLABEL attribute) 44

tag (gluonhtmlLEGEND attribute) 44tag (gluonhtmlLI attribute) 44tag (gluonhtmlLINK attribute) 44tag (gluonhtmlMENU attribute) 45tag (gluonhtmlMETA attribute) 45tag (gluonhtmlOBJECT attribute) 45tag (gluonhtmlOL attribute) 44tag (gluonhtmlOPTGROUP attribute) 45tag (gluonhtmlOPTION attribute) 45tag (gluonhtmlP attribute) 45tag (gluonhtmlPRE attribute) 45tag (gluonhtmlSCRIPT attribute) 45tag (gluonhtmlSELECT attribute) 46tag (gluonhtmlSPAN attribute) 46tag (gluonhtmlSTRONG attribute) 46tag (gluonhtmlSTYLE attribute) 46tag (gluonhtmlTABLE attribute) 46tag (gluonhtmlTBODY attribute) 47tag (gluonhtmlTD attribute) 46tag (gluonhtmlTEXTAREA attribute) 46tag (gluonhtmlTFOOT attribute) 47tag (gluonhtmlTH attribute) 47tag (gluonhtmlTHEAD attribute) 47tag (gluonhtmlTITLE attribute) 47tag (gluonhtmlTR attribute) 47tag (gluonhtmlTT attribute) 47tag (gluonhtmlUL attribute) 44tag (gluonhtmlXHTML attribute) 49TAG (in module gluonhtml) 46tar() (in module gluonfileutils) 26tar_compiled() (in module gluonfileutils) 26Task (class in gluonscheduler) 81task_status() (gluonschedulerScheduler method) 81TaskReport (class in gluonscheduler) 82TBODY (class in gluonhtml) 47TD (class in gluonhtml) 46TemplateParser (class in gluontemplate) 114terminate() (gluonschedulerScheduler method) 81terminate_process() (gluonschedulerMetaScheduler

method) 78test() (in module gluoncompileapp) 13test() (in module gluonshell) 88TEXTAREA (class in gluonhtml) 46TextWidget (class in gluonsqlhtml) 103TFOOT (class in gluonhtml) 47TH (class in gluonhtml) 46THEAD (class in gluonhtml) 47THREAD_LOCAL (gluoncustom_importTrackImporter

attribute) 17TicketStorage (class in gluonrestricted) 69TimeWidget (class in gluonsqlhtml) 104TITLE (class in gluonhtml) 47title() (gluonutf8Utf8 method) 142to() (gluonhttpHTTP method) 51

188 Index

web2py Documentation Release 2146-stable

to_string() (gluontemplateTemplateParser method) 115Token (class in gluonnewcron) 63toolbar() (gluonglobalsResponse method) 29total_seconds() (gluonschedulerScheduler static

method) 81TR (class in gluonhtml) 47track_changes() (in module gluoncustom_import) 17TrackImporter (class in gluoncustom_import) 17transitional (gluonhtmlHTML attribute) 43transitional (gluonhtmlXHTML attribute) 49translate() (gluonlanguagestranslator method) 55translate() (gluonutf8Utf8 method) 142translator (class in gluonlanguages) 53truncate() (gluonsqlDALTable method) 92try_redirect_on_error() (in module gluonrewrite) 73try_rewrite_on_error() (in module gluonrewrite) 73try_start_scheduler() (gluonwidgetweb2pyDialog

method) 172try_stop_scheduler() (gluonwidgetweb2pyDialog

method) 172TT (class in gluonhtml) 47TYPE (class in gluonscheduler) 81

UUL (class in gluonhtml) 44unlock() (in module gluonportalocker) 66untar() (in module gluonfileutils) 26unzip() (in module gluonadmin) 5up() (in module gluonfileutils) 25update() (gluonhtmlDIV method) 40update() (gluonsqlDALTable method) 92update() (gluontoolsCrud method) 131update() (gluonwidgetweb2pyDialog method) 172update_all_languages() (in module gluonlanguages) 55update_canvas() (gluonwidgetweb2pyDialog method)

172update_dependencies() (gluonschedulerScheduler

method) 81update_groups() (gluontoolsAuth method) 128update_or_insert() (gluonsqlDALTable method) 92update_request() (gluonrewriteMapUrlIn method) 72update_schedulers() (gluonwidgetweb2pyDialog

method) 172upgrade() (in module gluonadmin) 5UploadWidget (class in gluonsqlhtml) 104upper() (gluonutf8Utf8 method) 142url() (gluontoolsAuth method) 128url() (gluontoolsCrud method) 131URL() (in module gluonhtml) 47url_in() (in module gluonrewrite) 73url_out() (in module gluonrewrite) 73urlify() (gluonvalidatorsIS_SLUG static method) 165user_agent() (gluonglobalsRequest method) 28user_group() (gluontoolsAuth method) 128

user_group_role() (gluontoolsAuth method) 128user_id (gluontoolsAuth attribute) 128Utf8 (class in gluonutf8) 139uuid (gluonglobalsRequest attribute) 28uuid() (gluonsqlDAL method) 95

Vvalidate() (gluonhtmlFORM method) 41validate() (gluonschedulerJobGraph method) 77validate() (gluonsqlDALField method) 91validate() (gluonsqlField method) 96validate_and_insert() (gluonsqlDALTable method) 92validate_and_update() (gluonsqlDALTable method) 92validate_and_update_or_insert() (gluonsqlDALTable

method) 92validate_args() (gluonrewriteMapUrlIn method) 72validators (gluonsqlDAL attribute) 95validators_method() (gluonsqlDAL method) 95vars (gluonglobalsRequest attribute) 28verify_email() (gluontoolsAuth method) 128VERIFY_SERVER (gluontoolsRecaptcha attribute)

129VERIFY_SERVER (gluontoolsRecaptcha2 attribute)

130Virtual (gluonsqlDALField attribute) 91Virtual (gluonsqlField attribute) 96

Ww2p_pack() (in module gluonfileutils) 26w2p_pack_plugin() (in module gluonfileutils) 26w2p_unpack() (in module gluonfileutils) 26w2p_unpack_plugin() (in module gluonfileutils) 26web2py_uuid() (in module gluonutils) 144web2pyDialog (class in gluonwidget) 171WebDebugger (class in gluondebug) 21when_is_logged_in_bypass_next_in_url()

(gluontoolsAuth method) 128where() (gluonsqlDAL method) 95widget() (gluonsqlhtmlBooleanWidget class method)

97widget() (gluonsqlhtmlCheckboxesWidget class

method) 97widget() (gluonsqlhtmlFormWidget class method) 99widget() (gluonsqlhtmlJSONWidget class method) 99widget() (gluonsqlhtmlListWidget class method) 99widget() (gluonsqlhtmlMultipleOptionsWidget class

method) 100widget() (gluonsqlhtmlOptionsWidget class method)

100widget() (gluonsqlhtmlPasswordWidget class method)

100widget() (gluonsqlhtmlRadioWidget class method) 100widget() (gluonsqlhtmlStringWidget class method) 103widget() (gluonsqlhtmlTextWidget class method) 104

Index 189

web2py Documentation Release 2146-stable

widget() (gluonsqlhtmlUploadWidget class method)104

widgets (gluonsqlhtmlSQLFORM attribute) 103Wiki (class in gluontools) 135wiki() (gluontoolsAuth method) 129wikimenu() (gluontoolsAuth method) 129with_alias() (gluonsqlDALTable method) 92with_prefix() (gluoncacheCache static method) 8wrapped_assign_tasks() (gluonschedulerScheduler

method) 81wrapped_pop_task() (gluonschedulerScheduler

method) 81wrapped_report_task() (gluonschedulerScheduler

method) 81write() (gluondebugPipe method) 21write() (gluonglobalsResponse method) 29write() (gluonportalockerLockedFile method) 66write() (gluontemplateDummyResponse method) 114write() (gluonwidgetIO method) 171write_file() (in module gluonfileutils) 25write_locked() (in module gluonportalocker) 66wsgibase() (in module gluonmain) 57

XXHTML (class in gluonhtml) 49XML (class in gluonhtml) 49xml() (gluonhtmlA method) 35xml() (gluonhtmlCODE method) 37xml() (gluonhtmlDIV method) 40xml() (gluonhtmlFORM method) 42xml() (gluonhtmlHTML method) 43xml() (gluonhtmlINPUT method) 44xml() (gluonhtmlMARKMIN method) 44xml() (gluonhtmlMENU method) 45xml() (gluonhtmlP method) 45xml() (gluonhtmlSCRIPT method) 45xml() (gluonhtmlSTYLE method) 46xml() (gluonhtmlXHTML method) 49xml() (gluonhtmlXML method) 50xml() (gluontemplateNOESCAPE method) 114xml() (gluontoolsRecaptcha method) 129xml() (gluontoolsRecaptcha2 method) 130xml() (gluontoolsService method) 134xml() (in module gluonserializers) 83xml_rec() (in module gluonserializers) 83xmlescape() (in module gluonhtml) 50xmlns (gluonhtmlXHTML attribute) 49xmlrpc() (gluonglobalsResponse method) 29xmlrpc() (gluontoolsService method) 134

Yyaml() (in module gluonserializers) 83

Zzfill() (gluonutf8Utf8 method) 142

190 Index

  • admin Module
    • Utility functions for the Admin application
      • cache Module
        • Basic caching classes and methods
          • cfs Module
            • Functions required to execute app components
              • compileapp Module
                • Functions required to execute app components
                  • contenttype Module
                  • custom_import Module
                    • Support for smart import syntax for web2py applications
                      • dal Module
                        • Takes care of adapting pyDAL to web2pyrsquos needs
                          • debug Module
                            • Debugger support classes
                              • decoder Module
                              • fileutils Module
                                • File operations
                                  • globals Module
                                  • highlight Module
                                  • html Module
                                    • Template helpers
                                      • http Module
                                        • HTTP statuses helpers
                                          • languages Module
                                            • Translation system
                                              • main Module
                                                • The gluon wsgi application
                                                  • messageboxhandler Module
                                                  • myregex Module
                                                    • Useful regexes
                                                      • newcron Module
                                                      • portalocker Module
                                                      • recfile Module
                                                        • Generates names for cache and session files
                                                          • restricted Module
                                                            • Restricted environment to execute applicationrsquos code
                                                              • rewrite Module
                                                              • sanitizer Module
                                                                • Cross-site scripting (XSS) defense
                                                                  • scheduler Module
                                                                    • Background processes made simple
                                                                      • serializers Module
                                                                      • settings Module
                                                                      • shell Module
                                                                        • Web2py environment in the shell
                                                                          • sql Module
                                                                            • Just for backward compatibility
                                                                              • sqlhtml Module
                                                                              • storage Module
                                                                              • streamer Module
                                                                                • Facilities to handle file streaming
                                                                                  • template Module
                                                                                    • Templating syntax
                                                                                      • tools Module
                                                                                        • Auth Mail PluginManager and various utilities
                                                                                          • utf8 Module
                                                                                            • Utilities and class for UTF8 strings managing
                                                                                              • utils Module
                                                                                                • This file specifically includes utilities for security
                                                                                                  • validators Module
                                                                                                    • Validators
                                                                                                      • widget Module
                                                                                                        • The widget is called from web2py
                                                                                                          • xmlrpc Module
                                                                                                          • Indices and tables
                                                                                                          • Python Module Index
Page 4: web2py Documentation - Read the Docs

37 validators Module 145371 Validators 145

38 widget Module 171381 The widget is called from web2py 171

39 xmlrpc Module 173

40 Indices and tables 175

Python Module Index 177

iii

iv

web2py Documentation Release 2146-stable

Contents

Contents 1

web2py Documentation Release 2146-stable

2 Contents

CHAPTER 1

admin Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

11 Utility functions for the Admin application

gluonadminadd_path_first(path)

gluonadminapath(path=rdquo r=None)Builds a path inside an application folder

Parameters

bull path (str) ndash path within the application folder

bull r ndash the global request object

gluonadminapp_cleanup(app request)Removes session cache and error files

Parameters

bull app (str) ndash application name

bull request ndash the global request object

Returns True if everything went ok False otherwise

gluonadminapp_compile(app request skip_failed_views=False)Compiles the application

Parameters

bull app (str) ndash application name

bull request ndash the global request object

3

web2py Documentation Release 2146-stable

Returns None if everything went ok traceback text if errors are found

gluonadminapp_create(app request force=False key=None info=False)Create a copy of welcomew2p (scaffolding) app

Parameters

bull app (str) ndash application name

bull request ndash the global request object

gluonadminapp_install(app fobj request filename overwrite=None)Installs an application

bull Identifies file type by filename

bull Writes fobj contents to the deposit folder

bull Calls w2p_unpack() to do the job

Parameters

bull app (str) ndash new application name

bull fobj (obj) ndash file object containing the application to be installed

bull request ndash the global request object

bull filename (str) ndash original filename of the fobj required to determine extension

bull overwrite (bool) ndash force overwrite of existing application

Returns name of the file where app is temporarily stored or None on failure

gluonadminapp_pack(app request raise_ex=False filenames=None)Builds a w2p package for the application

Parameters

bull app (str) ndash application name

bull request ndash the global request object

Returns filename of the w2p file or None on error

gluonadminapp_pack_compiled(app request raise_ex=False)Builds a w2p bytecode-compiled package for the application

Parameters

bull app (str) ndash application name

bull request ndash the global request object

Returns filename of the w2p file or None on error

gluonadminapp_uninstall(app request)Uninstalls the application

Parameters

bull app (str) ndash application name

bull request ndash the global request object

Returns True on success False on failure

4 Chapter 1 admin Module

web2py Documentation Release 2146-stable

gluonadmincheck_new_version(myversion version_url)Compares current web2pyrsquos version with the latest stable web2py version

Parameters

bull myversion ndash the current version as stored in file web2pyVERSION

bull version_URL ndash the URL that contains the version of the latest stable release

Returns

state version

bull state True if upgrade available False if current version is up-to-date -1 on error

bull version the most up-to-version available

Return type tuple

gluonadmincreate_missing_app_folders(request)

gluonadmincreate_missing_folders()

gluonadminplugin_install(app fobj request filename)Installs a plugin

bull Identifies file type by filename

bull Writes fobj contents to the deposit folder

bull Calls w2p_unpack_plugin() to do the job

Parameters

bull app (str) ndash new application name

bull fobj ndash file object containing the application to be installed

bull request ndash the global request object

bull filename ndash original filename of the fobj required to determine extension

Returns name of the file where plugin is temporarily stored or False on failure

gluonadminplugin_pack(app plugin_name request)Builds a w2p package for the plugin

Parameters

bull app (str) ndash application name

bull plugin_name (str) ndash the name of the plugin without plugin_ prefix

bull request ndash the current request app

Returns filename of the w2p file or False on error

gluonadminunzip(filename dir subfolder=rdquo)Unzips filename into dir (zip only no gz etc)

Parameters

bull filename (str) ndash archive

bull dir (str) ndash destination

bull subfolder (str) ndash if = lsquorsquo unzips only files in subfolder

11 Utility functions for the Admin application 5

web2py Documentation Release 2146-stable

gluonadminupgrade(request url=rsquohttpweb2pycomrsquo)Upgrades web2py (src osx win) if a new version is posted It detects whether src osx or win is running anddownloads the right one

Parameters

bull request ndash the current request object (required to determine version and path)

bull url ndash the incomplete url where to locate the latest web2py (actual url isurl+rsquoexamplesstaticweb2py_(src|osx|win)ziprsquo)

Returns tuple completed traceback

bull completed True on success False on failure (network problem or old version)

bull traceback None on success raised exception details on failure

6 Chapter 1 admin Module

CHAPTER 2

cache Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

21 Basic caching classes and methods

bull Cache - The generic caching object interfacing with the others

bull CacheInRam - providing caching in ram

bull CacheOnDisk - provides caches on disk

Memcache is also available via a different module (see gluoncontribmemcache)

When web2py is running on Google App Engine caching will be provided by the GAE memcache (seegluoncontribgae_memcache)

class gluoncacheCache(request)Bases object

Sets up generic caching creating an instance of both CacheInRam and CacheOnDisk In case of GAE will makeuse of gluoncontribgae_memcache

bull selfram is an instance of CacheInRam

bull selfdisk is an instance of CacheOnDisk

action(time_expire=300 cache_model=None prefix=None session=False vars=True lang=Trueuser_agent=False public=True valid_statuses=None quick=None)

Better fit for caching an action

Warning Experimental

7

web2py Documentation Release 2146-stable

Currently only HTTP 11 compliant reference httpcodegooglecompdoctype-mirrorwikiArticleHttpCaching

Parameters

bull time_expire (int) ndash same as cache

bull cache_model (str) ndash same as cache

bull prefix (str) ndash add a prefix to the calculated key

bull session (bool) ndash adds responsesession_id to the key

bull vars (bool) ndash adds requestenvquery_string

bull lang (bool) ndash adds Taccepted_language

bull user_agent (bool or dict) ndash if True adds is_mobile and is_tablet tothe key Pass a dict to use all the needed values (uses str(items())) (eguser_agent=requestuser_agent()) Used only if session is not True

bull public (bool) ndash if False forces the Cache-Control to be lsquoprivatersquo

bull valid_statuses ndash by default only status codes starting with 123 will be cached passan explicit list of statuses on which turn the cache on

bull quick ndash SessionVarsLangUser-agentPublic fast overrides with initials eg lsquoSVLPrsquoor lsquoVLPrsquo or lsquoVLPrsquo

autokey = (name)s(args)s(vars)s

static with_prefix(cache_model prefix)allow replacing cacheram with cachewith_prefix(cacheramrsquoprefixrsquo) it will add prefix to all the cachekeys used

gluoncachelazy_cache(key=None time_expire=None cache_model=rsquoramrsquo)Can be used to cache any function including ones in modules as long as the cached function is only calledwithin a web2py request

If a key is not provided one is generated from the function name time_expire defaults to None (no cacheexpiration)

If cache_model is ldquoramrdquo then the model is currentcacheram etc

8 Chapter 2 cache Module

CHAPTER 3

cfs Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

31 Functions required to execute app components

Note FOR INTERNAL USE ONLY

gluoncfsgetcfs(key filename filter=None)Caches the filtered file filename with key until the file is modified

Parameters

bull key (str) ndash the cache key

bull filename ndash the file to cache

bull filter ndash is the function used for filtering Normally filename is a py file and filter is afunction that bytecode compiles the file In this way the bytecode compiled file is cached(Default = None)

This is used on Google App Engine since pyc files cannot be saved

9

web2py Documentation Release 2146-stable

10 Chapter 3 cfs Module

CHAPTER 4

compileapp Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

41 Functions required to execute app components

Note FOR INTERNAL USE ONLY

gluoncompileappLOAD(c=None f=rsquoindexrsquo args=None vars=None extension=None target=Noneajax=False ajax_trap=False url=None user_signature=False time-out=None times=1 content=rsquoloadingrsquo post_vars= attr)

LOADs a component into the actionrsquos document

Parameters

bull c (str) ndash controller

bull f (str) ndash function

bull args (tuple or list) ndash arguments

bull vars (dict) ndash vars

bull extension (str) ndash extension

bull target (str) ndash id of the target

bull ajax (bool) ndash True to enable AJAX bahaviour

bull ajax_trap (bool) ndash True if ajax is set to True traps both links and forms ldquoinsiderdquo thetarget

bull url (str) ndash overrides clsquoflsquolsquoargslsquo and vars

11

web2py Documentation Release 2146-stable

bull user_signature (bool) ndash adds hmac signature to all links with a key that is differentfor every user

bull timeout (int) ndash in milliseconds specifies the time to wait before starting the request orthe frequency if times is greater than 1 or ldquoinfinityrdquo

bull times (integer or str) ndash how many times the component will be requested ldquoinfin-ityrdquo or ldquocontinuousrdquo are accepted to reload indefinitely the component

class gluoncompileappLoadFactory(environment)Bases object

Attention this helper is new and experimental

gluoncompileappbuild_environment(request response session store_current=True)Build the environment dictionary into which web2py files are executed

gluoncompileappcompile_application(folder skip_failed_views=False)Compiles all models views controller for the application in folder

gluoncompileappcompile_controllers(folder)Compiles all the controllers in the application specified by folder

gluoncompileappcompile_models(folder)Compiles all the models in the application specified by folder

gluoncompileappcompile_views(folder skip_failed_views=False)Compiles all the views in the application specified by folder

gluoncompileappfind_exposed_functions(data)

gluoncompileapplocal_import_aux(name reload_force=False app=rsquowelcomersquo)In apps instead of importing a local module (in applicationsappmodules) with

import abc as d

you should do

d = local_import(abc)

or (to force a reload)

d = local_import(lsquoabcrsquo reload=True)

This prevents conflict between applications and un-necessary execs It can be used to import any moduleincluding regular Python modules

gluoncompileappmodel_cmp(a b sep=rsquorsquo)

gluoncompileappmodel_cmp_sep(a b sep=rsquorsquo)

class gluoncompileappmybuiltinBases object

NOTE could simple use a dict and populate it NOTE not sure if this changes things though if monkey patchingimport

gluoncompileappre_compile(regex)

gluoncompileappread_pyc(filename)Read the code inside a bytecode compiled file if the MAGIC number is compatible

Returns a code object

12 Chapter 4 compileapp Module

web2py Documentation Release 2146-stable

gluoncompileappremove_compiled_application(folder)Deletes the folder compiled containing the compiled application

gluoncompileapprun_controller_in(controller function environment)Runs the controllerfunction() (for the app specified by the current folder) It tries pre-compiled con-troller_functionpyc first before compiling it

gluoncompileapprun_models_in(environment)Runs all models (in the app specified by the current folder) It tries pre-compiled models first before compilingthem

gluoncompileapprun_view_in(environment)Executes the view for the requested action The view is the one specified in responseview or determined by theurl or viewgenericextension It tries the pre-compiled views_controller_functionpyc before compiling it

gluoncompileappsave_pyc(filename)Bytecode compiles the file filename

gluoncompileapptest()Example

gtgtgt import traceback typesgtgtgt environment=x1gtgtgt open(apy w)write(print 1x)gtgtgt save_pyc(apy)gtgtgt osunlink(apy)gtgtgt if type(read_pyc(apyc))==typesCodeType print codecodegtgtgt exec read_pyc(apyc) in environment1

41 Functions required to execute app components 13

web2py Documentation Release 2146-stable

14 Chapter 4 compileapp Module

CHAPTER 5

contenttype Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

CONTENT_TYPE dictionary created against freedesktoporgrsquos shared mime info database version 11

Deviations from official standards

bull md applicationx-genesis-rom ndashgt textx-markdown

bull png imagex-apple-ios-png ndashgt imagepng

Additions

bull load texthtml

bull json applicationjson

bull jsonp applicationjsonp

bull pickle applicationpython-pickle

bull w2prsquo applicationw2p

gluoncontenttypecontenttype(filename default=rsquotextplainrsquo)Returns the Content-Type string matching extension of the given filename

15

web2py Documentation Release 2146-stable

16 Chapter 5 contenttype Module

CHAPTER 6

custom_import Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

61 Support for smart import syntax for web2py applications

exception gluoncustom_importCustomImportExceptionBases exceptionsImportError

class gluoncustom_importTrackImporterBases object

An importer tracking the date of the module files and reloading them when they are changed

PACKAGE_PATH_SUFFIX = __init__py

THREAD_LOCAL = ltthread_local objectgt

gluoncustom_importcustom_import_install()

gluoncustom_importcustom_importer(name globals=None locals=None fromlist=Nonelevel=-1)

web2pyrsquos custom importer It behaves like the standard Python importer but it tries to transform importstatements as something like ldquoimport applicationsapp_namemodulesxrdquo If the import fails it falls back onnaive_importer

gluoncustom_importis_tracking_changes()

gluoncustom_importtrack_changes(track=True)

17

web2py Documentation Release 2146-stable

18 Chapter 6 custom_import Module

CHAPTER 7

dal Module

Go to httppydalreadthedocsorgenlatest for docs on pyDAL

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

71 Takes care of adapting pyDAL to web2pyrsquos needs

19

web2py Documentation Release 2146-stable

20 Chapter 7 dal Module

CHAPTER 8

debug Module

This file is part of the web2py Web FrameworkDeveloped by Massimo Di Pierro ltmdipierrocsdepauledugtlimodou ltlimodougmailcomgt and srackham ltsrackhamgmailcomgtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

81 Debugger support classes

class gluondebugPipe(name mode=rsquorrsquo args kwargs)Bases QueueQueue

flush()

read(count=None timeout=None)

readline()

write(data)

class gluondebugWebDebugger(pipe completekey=rsquotabrsquo stdin=None stdout=None)Bases gluoncontribqdbFrontend

Qdb web2py interface

clear_interaction()

do_continue(args kwargs)

do_exec(statement)

do_next(args kwargs)

do_quit(args kwargs)

do_return(args kwargs)

do_step(args kwargs)

21

web2py Documentation Release 2146-stable

exception(title extype exvalue trace request)Show a user_exception

interaction(filename lineno line context)

run()Main method dispatcher (infinite loop)

gluondebugcheck_interaction(fn)Decorator to clean and prevent interaction when not available

gluondebugcommunicate(command=None)send command to debbuger wait result

gluondebugset_trace()breakpoint shortcut (like pdb)

gluondebugstop_trace()stop waiting for the debugger (called atexit)

22 Chapter 8 debug Module

CHAPTER 9

decoder Module

Caller will hand this library a buffer and ask it to either convert it or auto-detect the type

Based on httpcodeactivestatecomrecipes52257

Licensed under the PSF License

gluondecoderautoDetectXMLEncoding(buffer)buffer -gt encoding_name The buffer should be at least 4 bytes long Returns None if encoding cannot bedetected Note that encoding_name might not have an installed decoder (eg EBCDIC)

gluondecoderdecoder(buffer)

23

web2py Documentation Release 2146-stable

24 Chapter 9 decoder Module

CHAPTER 10

fileutils Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

101 File operations

gluonfileutilsparse_version(version)Attempts to parse SemVer fallbacks on legacy

gluonfileutilsread_file(filename mode=rsquorrsquo)Returns content from filename making sure to close the file explicitly on exit

gluonfileutilswrite_file(filename value mode=rsquowrsquo)Writes ltvaluegt to filename making sure to close the file explicitly on exit

gluonfileutilsreadlines_file(filename mode=rsquorrsquo)Applies split(lsquo lsquo) to the output of read_file()

gluonfileutilsup(path)

gluonfileutilsabspath(relpath base)Converts relative path to absolute path based (by default) on applications_parent

gluonfileutilsmktree(path)

gluonfileutilslistdir(path expression=rsquo^+$rsquo drop=True add_dirs=False sort=Truemaxnum=None exclude_content_from=None)

Like oslistdir() but you can specify a regex pattern to filter files If add_dirs is True the returned items willhave the full path

gluonfileutilsrecursive_unlink(f)Deletes f If itrsquos a folder also its contents will be deleted

gluonfileutilscleanpath(path)Turns any expressionpath into a valid filename replaces with _ and removes special characters

25

web2py Documentation Release 2146-stable

gluonfileutilstar(file dir expression=rsquo^+$rsquo filenames=None exclude_content_from=None)Tars dir into file only tars file that match expression

gluonfileutilsuntar(file dir)Untar file into dir

gluonfileutilstar_compiled(file dir expression=rsquo^+$rsquo exclude_content_from=None)Used to tar a compiled application The content of models views controllers is not stored in the tar file

gluonfileutilsget_session(request other_application=rsquoadminrsquo)Checks that user is authorized to access other_application

gluonfileutilscheck_credentials(request other_application=rsquoadminrsquo expiration=3600gae_login=True)

Checks that user is authorized to access other_application

gluonfileutilsw2p_pack(filename path compiled=False filenames=None)Packs a web2py application

Parameters

bull filename (str) ndash path to the resulting archive

bull path (str) ndash path to the application

bull compiled (bool) ndash if True packs the compiled version

bull filenames (list) ndash adds filenames to the archive

gluonfileutilsw2p_unpack(filename path delete_tar=True)

gluonfileutilsw2p_pack_plugin(filename path plugin_name)Packs the given plugin into a w2p file Will match files at

ltpathgtplugin_[name]ltpathgtplugin_[name]

gluonfileutilsw2p_unpack_plugin(filename path delete_tar=True)

gluonfileutilsfix_newlines(path)

gluonfileutilsmake_fake_file_like_object()

26 Chapter 10 fileutils Module

CHAPTER 11

globals Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

Contains the classes for the global used variables

bull Request

bull Response

bull Session

class gluonglobalsRequest(env)Bases gluonstorageStorage

Defines the request object and the default values of its members

bull env environment variables by gluonmainwsgibase()

bull cookies

bull get_vars

bull post_vars

bull vars

bull folder

bull application

bull function

bull args

bull extension

bull now datetimedatetimenow()

27

web2py Documentation Release 2146-stable

bull utcnow datetimedatetimeutcnow()

bull is_local

bull is_https

bull restful()

body

compute_uuid()

get_varsLazily parses the query string into get_vars

parse_all_vars()Merges get_vars and post_vars to vars

parse_get_vars()Takes the QUERY_STRING and unpacks it to get_vars

parse_post_vars()Takes the body of the request and unpacks it into post_vars applicationjson is also automatically parsed

post_varsLazily parse the body into post_vars

requires_https()If request comes in over HTTP redirects it to HTTPS and secures the session

restful()

user_agent()

uuidLazily uuid

varsLazily parses all get_vars and post_vars to fill vars

class gluonglobalsResponseBases gluonstorageStorage

Defines the response object and the default values of its members responsewrite( ) can be used to write in theoutput html

download(request db chunk_size=65536 attachment=True download_filename=None)Example of usage in controller

def download()return responsedownload(request db)

Downloads from http downloadfilename

include_files(extensions=None)Includes files (usually in the head) Can minify and cache local files By default caches in ram for 5minutes To change responsecache_includes = (cache_method time_expire) Example (cachedisk 60) caches to disk for 1 minute

include_meta()

json(data default=None)

render(a b)

28 Chapter 11 globals Module

web2py Documentation Release 2146-stable

stream(stream chunk_size=65536 request=None attachment=False filename=None)If in a controller function

return responsestream(file 100)

the file content will be streamed at 100 bytes at the time

Parameters

bull stream ndash filename or read()able content

bull chunk_size (int) ndash Buffer size

bull request ndash the request object

bull attachment (bool) ndash prepares the correct headers to download the file as an attach-ment Usually creates a pop-up download window on browsers

bull filename (str) ndash the name for the attachment

Note for using the stream name (filename) with attachments the option must be explicitly set as functionparameter (will default to the last request argument otherwise)

toolbar()

write(data escape=True)

xmlrpc(request methods)assuming

def add(a b)return a+b

if a controller function ldquofuncrdquo

return responsexmlrpc(request [add])

the controller will be able to handle xmlrpc requests for the add function Example

import xmlrpclibconnection = xmlrpclibServerProxy(

httphostnameappcontrfunc)print connectionadd(3 4)

class gluonglobalsSessionBases gluonstorageStorage

Defines the session object and the default values of its members (None)

bull session_storage_type lsquofilersquo lsquodbrsquo or lsquocookiersquo

bull session_cookie_compression_level

bull session_cookie_expires cookie expiration

bull session_cookie_key for encrypted sessions in cookies

bull session_id a number or None if no session

bull session_id_name

bull session_locked

29

web2py Documentation Release 2146-stable

bull session_masterapp

bull session_new a new session obj is being created

bull session_hash hash of the pickled loaded session

bull session_pickled picked session

if session in cookie

bull session_data_name name of the cookie for session data

if session in db

bull session_db_record_id

bull session_db_table

bull session_db_unique_key

if session in file

bull session_file

bull session_filename

clear()rarr None Remove all items from D

clear_session_cookies()

connect(request=None response=None db=None tablename=rsquoweb2py_sessionrsquo master-app=None migrate=True separate=None check_client=False cookie_key=Nonecookie_expires=None compression_level=None)

Used in models allows to customize Session handling

Parameters

bull request ndash the request object

bull response ndash the response object

bull db ndash to storeretrieve sessions in db (a table is created)

bull tablename (str) ndash table name

bull masterapp (str) ndash points to anotherrsquos app sessions This enables a ldquoSSOrdquo environmentamong apps

bull migrate ndash passed to the underlying db

bull separate ndash with True creates a folder with the 2 initials of the session id Can also bea function eg

separate=lambda(session_name) session_name[-2]

bull check_client ndash if True sessions can only come from the same ip

bull cookie_key (str) ndash secret for cookie encryption

bull cookie_expires ndash sets the expiration of the cookie

bull compression_level (int) ndash 0-9 sets zlib compression on the data before the en-cryption

forget(response=None)

is_expired(seconds=3600)

is_new()

30 Chapter 11 globals Module

web2py Documentation Release 2146-stable

renew(clear_session=False)

save_session_id_cookie()

secure()

31

web2py Documentation Release 2146-stable

32 Chapter 11 globals Module

CHAPTER 12

highlight Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

gluonhighlighthighlight(code language link=rsquoexamplesglobalsvarsrsquo counter=1styles=None highlight_line=None context_lines=None at-tributes=None)

33

web2py Documentation Release 2146-stable

34 Chapter 12 highlight Module

CHAPTER 13

html Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

131 Template helpers

class gluonhtmlA(components attributes)Bases gluonhtmlDIV

Generates an A() link A() in web2py is really important and with the included web2pyjs allows lots of Ajaxinteractions in the page

On top of ldquousualrdquo _attributes it takes

Parameters

bull callback ndash an url to call but not redirect to

bull cid ndash if you want to load the _href into an element of the page (component) pass its id(without the ) here

bull delete ndash element to delete after calling callback

bull target ndash same thing as cid

bull confirm ndash text to display upon a callback with a delete

bull noconfirm ndash donrsquot display alert upon a callback with delete

tag = a

xml()generates the xml for this component

gluonhtmlASSIGNJS(kargs)

35

web2py Documentation Release 2146-stable

Example

ASSIGNJS(var1=lsquo1rsquo var2=lsquo2rsquo) will return the following javascript variables assignations

var var1 = ldquo1rdquo var var2 = ldquo2rdquo

Parameters kargs ndash Any keywords arguments and assigned values

Returns Javascript vars assignations for the keyvalue passed

class gluonhtmlB(components attributes)Bases gluonhtmlDIV

tag = b

class gluonhtmlBEAUTIFY(component attributes)Bases gluonhtmlDIV

Turns any list dictionary etc into decent looking html

Two special attributes are

bull sorted a function that takes the dict and returned sorted keys

bull keyfilter a function that takes a key and returns its representation or None if the key is to be skipped Bydefault key[1]==rsquo_rsquo is skipped

Examples

gtgtgt BEAUTIFY([a b hello world])xml()ltdivgtlttablegtlttrgtlttdgtltdivgtaltdivgtlttdgtlttrgtlttrgtlttdgtltdivgtbltdivgtlttdgtlttrgtlttrgtlttdgtrarr˓ltdivgtlttablegtlttrgtlttd style=font-weightboldvertical-aligntopgthellolttdgtlttdrarr˓style=vertical-aligntopgtlttdgtlttdgtltdivgtworldltdivgtlttdgtlttrgtlttablegtltdivgtltrarr˓tdgtlttrgtlttablegtltdivgt

static no_underscore(key)

tag = div

class gluonhtmlBODY(components attributes)Bases gluonhtmlDIV

tag = body

class gluonhtmlBR(components attributes)Bases gluonhtmlDIV

tag = br

class gluonhtmlBUTTON(components attributes)Bases gluonhtmlDIV

tag = button

class gluonhtmlCENTER(components attributes)Bases gluonhtmlDIV

tag = center

class gluonhtmlCAT(components attributes)Bases gluonhtmlDIV

tag =

36 Chapter 13 html Module

web2py Documentation Release 2146-stable

class gluonhtmlCODE(components attributes)Bases gluonhtmlDIV

Displays code in HTML with syntax highlighting

Parameters

bull language ndash indicates the language otherwise PYTHON is assumed

bull link ndash can provide a link

bull styles ndash for styles

Examples

=CODE(ldquoprint lsquohello worldrsquordquo language=rsquopythonrsquo link=None counter=1 styles= high-light_line=None)

supported languages are

ldquopythonrdquo ldquohtml_plainrdquo ldquocrdquo ldquocpprdquo ldquoweb2pyrdquo ldquohtmlrdquo

The ldquohtmlrdquo language interprets and tags as ldquoweb2pyrdquo code ldquohtml_plainrdquo doesnrsquot

if a link=rsquoexamplesglobalvarsrsquo is provided web2py keywords are linked to the online docs

the counter is used for line numbering counter can be None or a prompt string

xml()generates the xml for this component

class gluonhtmlCOL(components attributes)Bases gluonhtmlDIV

tag = col

class gluonhtmlCOLGROUP(components attributes)Bases gluonhtmlDIV

tag = colgroup

class gluonhtmlDIV(components attributes)Bases gluonhtmlXmlComponent

HTML helper for easy generating and manipulating a DOM structure Little or no validation is done

Behaves like a dictionary regarding updating of attributes Behaves like a list regarding insertingappendingcomponents

Examples

gtgtgt DIV(hello world _style=colorred)xml()ltdiv style=colorredgthelloworldltdivgt

All other HTML helpers are derived from DIV

_something=rdquovaluerdquo attributes are transparently translated into something=rdquovaluerdquo HTML attributes

append(value)list style appending of components

Examples

131 Template helpers 37

web2py Documentation Release 2146-stable

gtgtgt a=DIV()gtgtgt aappend(SPAN(x))gtgtgt print altdivgtltspangtxltspangtltdivgt

element(args kargs)Finds the first component that matches the supplied attribute dictionary or None if nothing could be found

Also the components of the components are searched

elements(args kargs)Find all components that match the supplied attribute dictionary or None if nothing could be found

All components of the components are searched

Examples

gtgtgt a = DIV(DIV(SPAN(x)3DIV(SPAN(y))))gtgtgt for c in aelements(span first_only=True) c[0]=zgtgtgt print altdivgtltdivgtltspangtzltspangt3ltdivgtltspangtyltspangtltdivgtltdivgtltdivgtgtgtgt for c in aelements(span) c[0]=zgtgtgt print altdivgtltdivgtltspangtzltspangt3ltdivgtltspangtzltspangtltdivgtltdivgtltdivgt

It also supports a syntax compatible with jQuery

Examples

gtgtgt a=TAG(ltdivgtltspangtlta id=1-1 uv=$gthelloltagtltspangtltp class=this is ararr˓testgtworldltpgtltdivgt)gtgtgt for e in aelements(div a1-1 pis) print eflatten()helloworldgtgtgt for e in aelements(1-1) print eflatten()hellogtgtgt aelements(a[uv=$])[0]xml()lta id=1-1 uv=$gthelloltagtgtgtgt a=FORM( INPUT(_type=text) SELECT(range(1)) TEXTAREA() )gtgtgt for c in aelements(input select textarea) c[_disabled] = disabledrarr˓gtgtgt axml()ltform action= enctype=multipartform-data method=postgtltinput disabled=rarr˓disabled type=text gtltselect disabled=disabledgtltoption value=0gt0ltrarr˓optiongtltselectgtlttextarea cols=40 disabled=disabled rows=10gtltrarr˓textareagtltformgt

Elements that are matched can also be replaced or removed by specifying a ldquoreplacerdquo argument (note alist of the original matching elements is still returned as usual)

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=abc) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(spanabc replace=P(x _class=xyz))gtgtgt print a We should xml() here instead of printltdivgtltdivgtltp class=xyzgtxltpgtltdivgtltp class=xyzgtxltpgtltp class=xyzgtxltpgtltrarr˓divgtltdivgtltdivgt

38 Chapter 13 html Module

web2py Documentation Release 2146-stable

ldquoreplacerdquo can be a callable which will be passed the original element and should return a new element toreplace it

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=abc) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(spanabc replace=lambda el P(el[0] _class=xyz))gtgtgt print altdivgtltdivgtltp class=xyzgtxltpgtltdivgtltp class=xyzgtyltpgtltp class=xyzgtzltpgtltrarr˓divgtltdivgtltdivgt

If replace=None matching elements will be removed completely

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=abc) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(span find=y replace=None)gtgtgt print altdivgtltdivgtltspan class=abcgtxltspangtltdivgtltspan class=abcgtzltspangtltdivgtltrarr˓divgtltdivgt

If a ldquofind_textrdquo argument is specified elements will be searched for text components that match find_textand any matching text components will be replaced (find_text is ignored if ldquoreplacerdquo is not also specified)Like the ldquofindrdquo argument ldquofind_textrdquo can be a string or a compiled regex

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=abc) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(find_text=recompile(x|y|z) replace=hello)gtgtgt print altdivgtltdivgtltspan class=abcgthelloltspangtltdivgtltspan class=abcgthelloltspangtrarr˓ltspan class=abcgthelloltspangtltdivgtltdivgtltdivgt

If other attributes are specified along with find_text then only components that match the specified at-tributes will be searched for find_text

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=efg) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(spanefg find_text=recompile(x|y|z) replace=hello)gtgtgt print altdivgtltdivgtltspan class=abcgtxltspangtltdivgtltspan class=efggthelloltspangtltspanrarr˓class=abcgtzltspangtltdivgtltdivgtltdivgt

flatten(render=None)Returns the text stored by the DIV object rendered by the render function the render function must taketext tagname and attributes render=None is equivalent to render=lambda text tag attr text

Examples

gtgtgt markdown = lambda text tag=None attributes=rarr˓None resub(s+ text) h1+text+nnrarr˓ ptext+nget(tagtext)gtgtgt a=TAG(lth1gtHeaderlth1gtltpgtthis is a testltpgt)gtgtgt aflatten(markdown)Headernnthis is a testn

131 Template helpers 39

web2py Documentation Release 2146-stable

get(i)

insert(i value)List-style inserting of components

Examples

gtgtgt a=DIV()gtgtgt ainsert(0 SPAN(x))gtgtgt print altdivgtltspangtxltspangtltdivgt

regex_attr = lt_sreSRE_Pattern objectgt

regex_class = lt_sreSRE_Pattern objectgt

regex_id = lt_sreSRE_Pattern objectgt

regex_tag = lt_sreSRE_Pattern objectgt

sibling(args kargs)Finds the first sibling component that match the supplied argument list and attribute dictionary or None ifnothing could be found

siblings(args kargs)Finds all sibling components that match the supplied argument list and attribute dictionary or None ifnothing could be found

tag = div

update(kargs)dictionary like updating of the tag attributes

xml()generates the xml for this component

class gluonhtmlEM(components attributes)Bases gluonhtmlDIV

tag = em

class gluonhtmlEMBED(components attributes)Bases gluonhtmlDIV

tag = embed

class gluonhtmlFIELDSET(components attributes)Bases gluonhtmlDIV

tag = fieldset

class gluonhtmlFORM(components attributes)Bases gluonhtmlDIV

Examples

gtgtgt from validators import IS_NOT_EMPTYgtgtgt form=FORM(INPUT(_name=test requires=IS_NOT_EMPTY()))gtgtgt formxml()ltform action= enctype=multipartform-data method=postgtltinput name=testrarr˓type=text gtltformgt

a FORM is container for INPUT TEXTAREA SELECT and other helpers

form has one important method

40 Chapter 13 html Module

web2py Documentation Release 2146-stable

formaccepts(requestvars session)

if form is accepted (and all validators pass) formvars contains the accepted vars otherwise formerrors containsthe errors in case of errors the form is modified to present the errors to the user

REDIRECT_JS = windowlocation=sreturn false

accepts(request_vars session=None formname=rsquodefaultrsquo keepvalues=False onvalidation=Nonehideerror=False kwargs)

kwargs is not used but allows to specify the same interface for FORM and SQLFORM

add_button(value url _class=None)

as_dict(flat=False sanitize=True)EXPERIMENTAL

Sanitize is naive It should catch any unsafe value for client retrieval

as_json(sanitize=True)

as_xml(sanitize=True)

as_yaml(sanitize=True)

assert_status(status request_vars)

static confirm(text=rsquoOKrsquo buttons=None hidden=None)

hidden_fields()

process(kwargs)Perform the validate() method but returns the form

Usage in controllers

directly on returndef action()

some code herereturn dict(form=FORM()process())

You can use it with FORM SQLFORM or FORM based plugins

responseflash messagesdef action()

form = SQLFORM(dbtable)process(message_onsuccess=Sucess)return dict(form=form)

callback function callback receives True or False as first arg and a list of argsdef my_callback(status msg)

responseflash = Success +msg if status else Errors occured

after argument can be flash to responseflash messages or a function name to use as callback or None to do nothingdef action()

return dict(form=SQLFORM(dbtable)process(onsuccess=my_callback)

tag = form

validate(kwargs)This function validates the form you can use it instead of directly formaccepts

Usage In controller

131 Template helpers 41

web2py Documentation Release 2146-stable

def action()form=FORM(INPUT(_name=test requires=IS_NOT_EMPTY()))formvalidate() you can pass some args here - see belowreturn dict(form=form)

This can receive a bunch of arguments

onsuccess = lsquoflashrsquo - will show message_onsuccess in responseflash None - will do nothing can be afunction (lambda form pass)

onfailure = lsquoflashrsquo - will show message_onfailure in responseflash None - will do nothing can be afunction (lambda form pass)

onchange = lsquoflashrsquo - will show message_onchange in responseflash None - will do nothing can be afunction (lambda form pass)

message_onsuccess message_onfailure message_onchange next = where to redirect in case of success anyother kwargs will be passed for formaccepts( )

xml()generates the xml for this component

class gluonhtmlH1(components attributes)Bases gluonhtmlDIV

tag = h1

class gluonhtmlH2(components attributes)Bases gluonhtmlDIV

tag = h2

class gluonhtmlH3(components attributes)Bases gluonhtmlDIV

tag = h3

class gluonhtmlH4(components attributes)Bases gluonhtmlDIV

tag = h4

class gluonhtmlH5(components attributes)Bases gluonhtmlDIV

tag = h5

class gluonhtmlH6(components attributes)Bases gluonhtmlDIV

tag = h6

class gluonhtmlHEAD(components attributes)Bases gluonhtmlDIV

tag = head

class gluonhtmlHR(components attributes)Bases gluonhtmlDIV

tag = hr

class gluonhtmlHTML(components attributes)Bases gluonhtmlDIV

42 Chapter 13 html Module

web2py Documentation Release 2146-stable

There are four predefined document type definitions They can be specified in the lsquodoctypersquo parameter

bull lsquostrictrsquo enables strict doctype

bull lsquotransitionalrsquo enables transitional doctype (default)

bull lsquoframesetrsquo enables frameset doctype

bull lsquohtml5rsquo enables HTML 5 doctype

bull any other string will be treated as userrsquos own doctype

lsquolangrsquo parameter specifies the language of the document Defaults to lsquoenrsquo

See also DIV

frameset = ltDOCTYPE HTML PUBLIC -W3CDTD HTML 401 FramesetEN httpwwww3orgTRhtml4framesetdtdgtn

html5 = ltDOCTYPE HTMLgtn

strict = ltDOCTYPE HTML PUBLIC -W3CDTD HTML 401EN httpwwww3orgTRhtml4strictdtdgtn

tag = html

transitional = ltDOCTYPE HTML PUBLIC -W3CDTD HTML 401 TransitionalEN httpwwww3orgTRhtml4loosedtdgtn

xml()generates the xml for this component

class gluonhtmlI(components attributes)Bases gluonhtmlDIV

tag = i

class gluonhtmlIFRAME(components attributes)Bases gluonhtmlDIV

tag = iframe

class gluonhtmlIMG(components attributes)Bases gluonhtmlDIV

tag = img

class gluonhtmlINPUT(components attributes)Bases gluonhtmlDIV

INPUT Component

Takes two special attributes value= and requires=

Parameters

bull value ndash used to pass the initial value for the input field value differs from _value becauseit works for checkboxes radio textarea and selectoption too For a checkbox value shouldbe lsquorsquo or lsquoonrsquo For a radio or selectoption value should be the _value of the checkedselecteditem

bull requires ndash should be None or a validator or a list of validators for the value of the field

Examples

gtgtgt INPUT(_type=text _name=name value=Max)xml()ltinput name=name type=text value=Max gt

gtgtgt INPUT(_type=checkbox _name=checkbox value=on)xml()ltinput checked=checked name=checkbox type=checkbox value=on gt

131 Template helpers 43

web2py Documentation Release 2146-stable

gtgtgt INPUT(_type=radio _name=radio _value=yes value=yes)xml()ltinput checked=checked name=radio type=radio value=yes gt

gtgtgt INPUT(_type=radio _name=radio _value=no value=yes)xml()ltinput name=radio type=radio value=no gt

tag = input

xml()generates the xml for this component

class gluonhtmlLABEL(components attributes)Bases gluonhtmlDIV

tag = label

class gluonhtmlLEGEND(components attributes)Bases gluonhtmlDIV

tag = legend

class gluonhtmlLI(components attributes)Bases gluonhtmlDIV

tag = li

class gluonhtmlLINK(components attributes)Bases gluonhtmlDIV

tag = link

class gluonhtmlOL(components attributes)Bases gluonhtmlUL

tag = ol

class gluonhtmlUL(components attributes)Bases gluonhtmlDIV

UL Component

If subcomponents are not LI-components they will be wrapped in a LI

tag = ul

class gluonhtmlMARKMIN(text extra=None allowed=None sep=rsquoprsquo url=None environ-ment=None latex=rsquogooglersquo autolinks=rsquodefaultrsquo protolinks=rsquodefaultrsquoclass_prefix=rdquo id_prefix=rsquomarkmin_rsquo kwargs)

Bases gluonhtmlXmlComponent

For documentation httpweb2pycomexamplesstaticmarkminhtml

flatten()

xml()

class gluonhtmlMENU(data args)Bases gluonhtmlDIV

Used to build menus

Parameters

bull _class ndash defaults to lsquoweb2py-menu web2py-menu-verticalrsquo

bull ul_class ndash defaults to lsquoweb2py-menu-verticalrsquo

44 Chapter 13 html Module

web2py Documentation Release 2146-stable

bull li_class ndash defaults to lsquoweb2py-menu-expandrsquo

bull li_first ndash defaults to lsquoweb2py-menu-firstrsquo

bull li_last ndash defaults to lsquoweb2py-menu-lastrsquo

Use like

menu = MENU([[name False URL() [submenu]] ])=menu

serialize(data level=0)

serialize_mobile(data select=None prefix=rdquo)

tag = ul

xml()generates the xml for this component

class gluonhtmlMETA(components attributes)Bases gluonhtmlDIV

tag = meta

class gluonhtmlOBJECT(components attributes)Bases gluonhtmlDIV

tag = object

class gluonhtmlOPTION(components attributes)Bases gluonhtmlDIV

tag = option

class gluonhtmlP(components attributes)Bases gluonhtmlDIV

Will replace n by ltbr gt if the cr2br attribute is provided

see also DIV

tag = p

xml()generates the xml for this component

class gluonhtmlPRE(components attributes)Bases gluonhtmlDIV

tag = pre

class gluonhtmlSCRIPT(components attributes)Bases gluonhtmlDIV

tag = script

xml()generates the xml for this component

class gluonhtmlOPTGROUP(components attributes)Bases gluonhtmlDIV

tag = optgroup

131 Template helpers 45

web2py Documentation Release 2146-stable

class gluonhtmlSELECT(components attributes)Bases gluonhtmlINPUT

Examples

gtgtgt from validators import IS_IN_SETgtgtgt SELECT(yes no _name=selector value=yes requires=IS_IN_SET([yes no]))xml()ltselect name=selectorgtltoption selected=selected value=yesgtyesltoptiongtrarr˓ltoption value=nogtnoltoptiongtltselectgt

tag = select

class gluonhtmlSPAN(components attributes)Bases gluonhtmlDIV

tag = span

class gluonhtmlSTRONG(components attributes)Bases gluonhtmlDIV

tag = strong

class gluonhtmlSTYLE(components attributes)Bases gluonhtmlDIV

tag = style

xml()generates the xml for this component

class gluonhtmlTABLE(components attributes)Bases gluonhtmlDIV

TABLE Component

If subcomponents are not TRTBODYTHEADTFOOT-components they will be wrapped in a TR

tag = table

gluonhtmlTAGTAG factory

Examples

gtgtgt print TAGfirst(TAGsecond(test) _key = 3)ltfirst key=3gtltsecondgttestltsecondgtltfirstgt

class gluonhtmlTD(components attributes)Bases gluonhtmlDIV

tag = td

class gluonhtmlTEXTAREA(components attributes)Bases gluonhtmlINPUT

Examples

TEXTAREA(_name=sometext value=blah 100 requires=IS_NOT_EMPTY())

lsquoblah blah blah rsquo will be the content of the textarea field

tag = textarea

46 Chapter 13 html Module

web2py Documentation Release 2146-stable

class gluonhtmlTH(components attributes)Bases gluonhtmlDIV

tag = th

class gluonhtmlTHEAD(components attributes)Bases gluonhtmlDIV

tag = thead

class gluonhtmlTBODY(components attributes)Bases gluonhtmlDIV

tag = tbody

class gluonhtmlTFOOT(components attributes)Bases gluonhtmlDIV

tag = tfoot

class gluonhtmlTITLE(components attributes)Bases gluonhtmlDIV

tag = title

class gluonhtmlTR(components attributes)Bases gluonhtmlDIV

TR Component

If subcomponents are not TDTH-components they will be wrapped in a TD

tag = tr

class gluonhtmlTT(components attributes)Bases gluonhtmlDIV

tag = tt

gluonhtmlURL(a=None c=None f=None r=None args=None vars=None an-chor=rdquo extension=None env=None hmac_key=None hash_vars=Truesalt=None user_signature=None scheme=None host=None port=None en-code_embedded_slash=False url_encode=True language=None)

generates a url lsquoacfrsquo corresponding to application a controller c and function f If r=request is passed a c fare set respectively to rapplication rcontroller rfunction

The more typical usage is

URL(lsquoindexrsquo)

that generates a url for the index function within the present application and controller

Parameters

bull a ndash application (default to current if r is given)

bull c ndash controller (default to current if r is given)

bull f ndash function (default to current if r is given)

bull r ndash request (optional)

bull args ndash any arguments (optional) Additional ldquopathrdquo elements

bull vars ndash any variables (optional) Querystring elements

bull anchor ndash anchorname without (optional)

131 Template helpers 47

web2py Documentation Release 2146-stable

bull extension ndash force an extension

bull hmac_key ndash key to use when generating hmac signature (optional)

bull hash_vars ndash which of the vars to include in our hmac signature True (default) - hash allvars False - hash none of the vars iterable - hash only the included vars [lsquokey1rsquorsquokey2rsquo]

bull salt ndash salt hashing with this string

bull user_signature ndash signs automatically the URL in such way that only the user canaccess the URL (use with URLverify or authrequires_signature())

bull scheme ndash URI scheme (True lsquohttprsquo or lsquohttpsrsquo etc) forces absolute URL (optional)

bull host ndash string to force absolute URL with host (True means http_host)

bull port ndash optional port number (forces absolute URL)

bull encode_embedded_slash ndash encode slash characters included in args

bull url_encode ndash encode characters included in vars

Raises SyntaxError ndash when no application controller or function is available or when a CRLFis found in the generated url

Examples

gtgtgt str(URL(a=a c=c f=f args=[x y z] vars=p1 q2 anchor=1))acfxyzp=1ampq=21

gtgtgt str(URL(a=a c=c f=f args=[x y z] vars=p(13) q2 anchor=1))acfxyzp=1ampp=3ampq=21

gtgtgt str(URL(a=a c=c f=f args=[x y z] vars=p(31) q2 anchor=1))acfxyzp=3ampp=1ampq=21

gtgtgt str(URL(a=a c=c f=f anchor=1+2))acf12B2

gtgtgt str(URL(a=a c=c f=f args=[x y z] vars=p(13) q2 anchor=1 hmac_key=key))acfxyzp=1ampp=3ampq=2amp_signature=a32530f0d0caa80964bb92aad2bedf8a4486a31f1

gtgtgt str(URL(a=a c=c f=f args=[wx yz]))acfwxyz

gtgtgt str(URL(a=a c=c f=f args=[wx yz] encode_embedded_slash=True))acfw2Fxy2Fz

gtgtgt str(URL(a=a c=c f=f args=[(id)d] url_encode=False))acf(id)d

gtgtgt str(URL(a=a c=c f=f args=[(id)d] url_encode=True))acf2528id29d

48 Chapter 13 html Module

web2py Documentation Release 2146-stable

gtgtgt str(URL(a=a c=c f=f vars=id (id)d url_encode=False))acfid=(id)d

gtgtgt str(URL(a=a c=c f=f vars=id (id)d url_encode=True))acfid=2528id29d

gtgtgt str(URL(a=a c=c f=f anchor=(id)d url_encode=False))acf(id)d

gtgtgt str(URL(a=a c=c f=f anchor=(id)d url_encode=True))acf2528id29d

class gluonhtmlXHTML(components attributes)Bases gluonhtmlDIV

This is XHTML version of the HTML helper

There are three predefined document type definitions They can be specified in the lsquodoctypersquo parameter

bull lsquostrictrsquo enables strict doctype

bull lsquotransitionalrsquo enables transitional doctype (default)

bull lsquoframesetrsquo enables frameset doctype

bull any other string will be treated as userrsquos own doctype

lsquolangrsquo parameter specifies the language of the document and the xml document Defaults to lsquoenrsquo

lsquoxmlnsrsquo parameter specifies the xml namespace Defaults to lsquohttpwwww3org1999xhtmlrsquo

See also DIV

frameset = ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 FramesetEN httpwwww3orgTRxhtml1DTDxhtml1-framesetdtdgtn

strict = ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgtn

tag = html

transitional = ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 TransitionalEN httpwwww3orgTRxhtml1DTDxhtml1-transitionaldtdgtn

xml()generates the xml for this component

xmlns = httpwwww3org1999xhtml

class gluonhtmlXML(text sanitize=False permitted_tags=[rsquoarsquo rsquobrsquo rsquoblockquotersquo rsquobrrsquo rsquoirsquo rsquolirsquo rsquoolrsquorsquoulrsquo rsquoprsquo rsquocitersquo rsquocodersquo rsquoprersquo rsquoimgrsquo rsquoh1rsquo rsquoh2rsquo rsquoh3rsquo rsquoh4rsquo rsquoh5rsquo rsquoh6rsquo rsquotablersquo rsquotrrsquorsquotdrsquo rsquodivrsquo rsquostrongrsquo rsquospanrsquo] allowed_attributes=rsquoarsquo [rsquohrefrsquo rsquotitlersquo rsquotargetrsquo]rsquoblockquotersquo [rsquotypersquo] rsquoimgrsquo [rsquosrcrsquo rsquoaltrsquo] rsquotdrsquo [rsquocolspanrsquo])

Bases gluonhtmlXmlComponent

use it to wrap a string that contains XMLHTML so that it will not be escaped by the template

Examples

gtgtgt XML(lth1gtHellolth1gt)xml()lth1gtHellolth1gt

elements(args kargs)to be considered experimental since the behavior of this method is questionable another option could beTAG(selftext)elements(args kwargs)

131 Template helpers 49

web2py Documentation Release 2146-stable

flatten(render=None)returns the text stored by the XML object rendered by the render function

xml()

gluonhtmlxmlescape(data quote=True)Returns an escaped string of the provided data

Parameters

bull data ndash the data to be escaped

bull quote ndash optional (default False)

gluonhtmlembed64(filename=None file=None data=None extension=rsquoimagegifrsquo)helper to encode the provided (binary) data into base64

Parameters

bull filename ndash if provided opens and reads this file in lsquorbrsquo mode

bull file ndash if provided reads this file

bull data ndash if provided uses the provided data

50 Chapter 13 html Module

CHAPTER 14

http Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

141 HTTP statuses helpers

exception gluonhttpHTTP(status body=rdquo cookies=None headers)Bases exceptionsException

Raises an HTTP response

Parameters

bull status ndash usually an integer If itrsquos a well known status code the ERROR message will beautomatically added A string can also be passed as 510 Foo Bar and in that case the statuscode and the error message will be parsed accordingly

bull body ndash what to return as body If left as is will return the error code and the status messagein the body itself

bull cookies ndash pass cookies along (usually not needed)

bull headers ndash pass headers as usual dict mapping

cookies2headers(cookies)

messagecompose a message describing this exception

ldquostatus defined_status [web2py_error]rdquo

message elements that are not defined are omitted

to(responder env=None)

51

web2py Documentation Release 2146-stable

gluonhttpredirect(location=rdquo how=303 client_side=False headers=None)Raises a redirect (303)

Parameters

bull location ndash the url where to redirect

bull how ndash what HTTP status code to use when redirecting

bull client_side ndash if set to True it triggers a reload of the entire page when the fragmenthas been loaded as a component

52 Chapter 14 http Module

CHAPTER 15

languages Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)Plural subsystem is created by Vladyslav Kozlovskyy (Ukraine) ltdbdevelopgmailcomgt

151 Translation system

class gluonlanguagestranslator(langpath http_accept_language)Bases object

This class is instantiated by gluoncompileappbuild_environment as the T object

Example

Tforce(None) turns off translation Tforce(lsquofr itrsquo) forces web2py to translate using frpy or itpy

T(ldquoHello Worldrdquo) translates ldquoHello Worldrdquo using the selected file

Note

bull there is no need to force since by default T uses http_accept_language to determine a translation file

bull en and en-en are considered different languages

bull if language xx-yy is not found force() probes other similar languages using such algorithm xx-yypy -gtxxpy -gt xx-yypy -gt xxpy

M(message symbols= language=None lazy=None filter=None ftag=None ns=None)Gets cached translated markmin-message with inserted parametes if lazy==True lazyT object is returned

apply_filter(message symbols= filter=None ftag=None)

53

web2py Documentation Release 2146-stable

force(languages)Selects language(s) for translation

if a list of languages is passed as a parameter the first language from this list that matches the ones fromthe possible_languages dictionary will be selected

default language will be selected if none of them matches possible_languages

get_possible_languages()Gets list of all possible languages for current application

get_possible_languages_info(lang=None)Returns info for selected language or dictionary with all possible languages info from APPlanguagespyIt Returns

bull a tuple containing

langcode langname langfile_mtimepluraldict_fname pluraldict_mtimeprules_langcode npluralsget_plural_id construct_plural_form

or None

bull if lang is NOT defined a dictionary with all possible languages

langcode(from filename)( langcode language code from langcodelangname

language name in national spelling from langnamelangfile_mtime m_time of language filepluraldict_fname name of plural dictionary file or None (when

rarr˓defaultpy is not exist)pluraldict_mtime m_time of plural dictionary file or 0 if file is

rarr˓not existprules_langcode code of plural rules language or defaultnplurals nplurals for current languageget_plural_id get_plural_id() for current languageconstruct_plural_form) construct_plural_form() for current

rarr˓language

Parameters lang (str) ndash language

get_t(message prefix=rdquo)Use to add a comment into a translation string the comment can be useful do discriminate differentpossible translations for the same string (for example different locations)

T( hello world ) -gt hello world T( hello world token) -gt hello world T(hello world token) -gt hello world

the notation is ignored in multiline strings and strings that start with This is needed to allow markminsyntax to be translated

params_substitution(message symbols)Substitutes parameters from symbols into message using also parse placeholders for plural-formsprocessing

Returns string with parameters

54 Chapter 15 languages Module

web2py Documentation Release 2146-stable

Note symbols MUST BE OR tuple OR dict of parameters

plural(word n)Gets plural form of word for number n invoked from T()TM() in tag

Note ldquowordrdquo MUST be defined in current language (Taccepted_language)

Parameters

bull word (str) ndash word in singular

bull n (numeric) ndash number plural form created for

Returns word in appropriate singularplural form

Return type word (str)

set_current_languages(languages)Sets current AKA ldquodefaultrdquo languages Setting one of this languages makes the force() function to turntranslation off

translate(message symbols)Gets cached translated message with inserted parameters(symbols)

gluonlanguagesfindT(path language=rsquoenrsquo)

Note Must be run by the admin app

gluonlanguagesupdate_all_languages(application_path)

Note Must be run by the admin app

151 Translation system 55

web2py Documentation Release 2146-stable

56 Chapter 15 languages Module

CHAPTER 16

main Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

161 The gluon wsgi application

gluonmainwsgibase(environ responder)The gluon wsgi application The first function called when a page is requested (static or dynamic) It can becalled by pastehttpserver or by apache mod_wsgi (or any WSGI-compatible server)

bull fills request with info

bull the environment variables replacing lsquorsquo with lsquo_rsquo

bull adds web2py path and version info

bull compensates for fcgi missing path_info and query_string

bull validates the path in url

The url path must be either

1 for static pages

bull ltapplicationgtstaticltfilegt

2 for dynamic pages

bull ltapplicationgt[ltcontrollergt[ltfunctiongt[ltsubgt]]][ltextensiongt]

The naming conventions are

bull application controller function and extension may only contain [a-zA-Z0-9_]

57

web2py Documentation Release 2146-stable

bull file and sub may also contain lsquo-lsquo lsquo=rsquo lsquorsquo and lsquorsquo

gluonmainsave_password(password port)Used by main() to save the password in the parameters_portpy file

gluonmainappfactory(wsgiapp=ltfunction wsgibasegt logfilename=rsquohttpserverlogrsquo pro-filer_dir=None profilerfilename=None)

generates a wsgi application that does logging and profiling and calls wsgibase

Parameters

bull wsgiapp ndash the base application

bull logfilename ndash where to store apache-compatible requests log

bull profiler_dir ndash where to store profile files

class gluonmainHttpServer(ip=rsquo127001rsquo port=8000 password=rdquopid_filename=rsquohttpserverpidrsquo log_filename=rsquohttpserverlogrsquoprofiler_dir=None ssl_certificate=None ssl_private_key=Nonessl_ca_certificate=None min_threads=None max_threads=Noneserver_name=None request_queue_size=5 timeout=10socket_timeout=1 shutdown_timeout=None path=None inter-faces=None)

Bases object

the web2py web server (Rocket)

start()start the web server

stop(stoplogging=False)stop cron and the web server

58 Chapter 16 main Module

CHAPTER 17

messageboxhandler Module

class gluonmessageboxhandlerMessageBoxHandlerBases loggingHandler

emit(record)Do whatever it takes to actually log the specified logging record

This version is intended to be implemented by subclasses and so raises a NotImplementedError

class gluonmessageboxhandlerNotifySendHandlerBases loggingHandler

emit(record)Do whatever it takes to actually log the specified logging record

This version is intended to be implemented by subclasses and so raises a NotImplementedError

59

web2py Documentation Release 2146-stable

60 Chapter 17 messageboxhandler Module

CHAPTER 18

myregex Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

181 Useful regexes

61

web2py Documentation Release 2146-stable

62 Chapter 18 myregex Module

CHAPTER 19

newcron Module

This file is part of the web2py Web FrameworkCreated by Attila Csipa ltweb2pycsipainrsgtModified by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

Cron-style interface

class gluonnewcronToken(path)Bases object

acquire(startup=False)Returns the time when the lock is acquired or None if cron already running

lock is implemented by writing a pickle (start stop) in cronmaster start is time when cron job starts andstop is time when cron completed stop == 0 if job started but did not yet complete if a cron job startedwithin less than 60 seconds acquire returns None if a cron job started before 60 seconds and did not stopa warning is issue ldquoStale cronmaster detectedrdquo

release()Writes into cronmaster the time when cron job was completed

gluonnewcronabsolute_path_link(path)Returns an absolute path for the destination of a symlink

gluonnewcroncrondance(applications_parent ctype=rsquosoftrsquo startup=False apps=None)

class gluonnewcroncronlauncher(cmd shell=True)Bases threadingThread

run()Method representing the threadrsquos activity

You may override this method in a subclass The standard run() method invokes the callable object passedto the objectrsquos constructor as the target argument if any with sequential and keyword arguments takenfrom the args and kwargs arguments respectively

63

web2py Documentation Release 2146-stable

class gluonnewcronextcron(applications_parent apps=None)Bases threadingThread

run()Method representing the threadrsquos activity

You may override this method in a subclass The standard run() method invokes the callable object passedto the objectrsquos constructor as the target argument if any with sequential and keyword arguments takenfrom the args and kwargs arguments respectively

class gluonnewcronhardcron(applications_parent)Bases threadingThread

launch()

run()Method representing the threadrsquos activity

You may override this method in a subclass The standard run() method invokes the callable object passedto the objectrsquos constructor as the target argument if any with sequential and keyword arguments takenfrom the args and kwargs arguments respectively

gluonnewcronparsecronline(line)

gluonnewcronrangetolist(s period=rsquominrsquo)

class gluonnewcronsoftcron(applications_parent)Bases threadingThread

run()Method representing the threadrsquos activity

You may override this method in a subclass The standard run() method invokes the callable object passedto the objectrsquos constructor as the target argument if any with sequential and keyword arguments takenfrom the args and kwargs arguments respectively

gluonnewcronstopcron()Graceful shutdown of cron

64 Chapter 19 newcron Module

CHAPTER 20

portalocker Module

Cross-platform (posixnt) API for flock-style file locking

Synopsis

import portalockerfile = open(somefile r+)portalockerlock(file portalockerLOCK_EX)fileseek(12)filewrite(foo)fileclose()

If you know what yoursquore doing you may choose to

portalockerunlock(file)

before closing the file but why

Methods

lock( file flags )unlock( file )

Constants

LOCK_EXLOCK_SHLOCK_NB

I learned the win32 technique for locking files from sample code provided by John Nielsen ltnielsenjfmy-dejacomgtin the documentation that accompanies the win32 modules

Author Jonathan Feinberg ltjdfpoboxcomgt Version $Id portalockerpyv 13 20010529 184755 AdministratorExp $

class gluonportalockerLockedFile(filename mode=rsquorbrsquo)Bases object

65

web2py Documentation Release 2146-stable

close()

read(size=None)

readline()

readlines()

write(data)

gluonportalockerlock(file flags)

gluonportalockerread_locked(filename)

gluonportalockerunlock(file)

gluonportalockerwrite_locked(filename data)

66 Chapter 20 portalocker Module

CHAPTER 21

recfile Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

211 Generates names for cache and session files

gluonrecfileexists(filename path=None)

gluonrecfilegenerate(filename depth=2 base=512)

gluonrecfileopen(filename mode=rsquorrsquo path=None)

gluonrecfileremove(filename path=None)

67

web2py Documentation Release 2146-stable

68 Chapter 21 recfile Module

CHAPTER 22

restricted Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

221 Restricted environment to execute applicationrsquos code

exception gluonrestrictedRestrictedError(layer=rdquo code=rdquo output=rdquo environ-ment=None)

Bases exceptionsException

Class used to wrap an exception that occurs in the restricted environment below The traceback is used to logthe exception and generate a ticket

load(request app ticket_id)Loads a logged exception

log(request)Logs the exception

gluonrestrictedrestricted(code environment=None layer=rsquoUnknownrsquo)Runs code in environment and returns the output If an exception occurs in code it raises a RestrictedErrorcontaining the traceback Layer is passed to RestrictedError to identify where the error occurred

class gluonrestrictedTicketStorage(db=None tablename=rsquoweb2py_ticketrsquo)Bases gluonstorageStorage

Defines the ticket object and the default values of its members (None)

load(request app ticket_id)

store(request ticket_id ticket_data)Stores the ticket It will figure out if this must be on disk or in db

gluonrestrictedcompile2(code layer)The +n is necessary else compile fails when code ends in a comment

69

web2py Documentation Release 2146-stable

70 Chapter 22 restricted Module

CHAPTER 23

rewrite Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

gluonrewrite parses incoming URLs and formats outgoing URLs for gluonhtmlURL

In addition it rewrites both incoming and outgoing URLs based on the (optional) user-supplied routespy which alsoallows for rewriting of certain error messages

routespy supports two styles of URL rewriting depending on whether lsquoroutersrsquo is defined Refer to routerexamplepyand routesexamplepy for additional documentation

class gluonrewriteMapUrlIn(request=None env=None)Bases object

Logic for mapping incoming URLs

arg0Returns first arg

harg0Returns first arg with optional hyphen mapping

map_app()Determines application name

map_controller()Identifies controller

map_function()Handles functionextension

map_language()Handles language (no hyphen mapping)

71

web2py Documentation Release 2146-stable

map_prefix()Strips path prefix if present in its entirety

map_root_static()Handles root-static files (no hyphen mapping)

a root-static file is one whose incoming URL expects it to be at the root typically robotstxt amp faviconico

map_static()Handles static files file_match but no hyphen mapping

pop_arg_if(dopop)Conditionally removes first arg and returns new first arg

sluggify()

update_request()Updates request from self Builds envrequest_uri Makes lower-case versions of http headers in env

validate_args()Checks args against validation pattern

class gluonrewriteMapUrlOut(request env application controller function args other schemehost port language)

Bases object

Logic for mapping outgoing URLs

acf()Converts components to applangcontrollerfunction

build_acf()Builds acf from components

omit_acf()Omits what we can of acf

omit_lang()Omits language if possible

gluonrewritecompile_regex(k v env=None)Preprocess and compile the regular expressions in routes_appinout The resulting regex will match a pattern ofthe form

[remote address][protocol][host][method] [path]

We allow abbreviated regexes on input here we try to complete them

gluonrewritefilter_err(status application=rsquoapprsquo ticket=rsquotktrsquo)doctestunittest interface to routes_onerror

gluonrewritefilter_url(url method=rsquogetrsquo remote=rsquo0000rsquo out=False app=False lang=Nonedomain=(None None) env=False scheme=None host=Noneport=None language=None)

doctestunittest interface to regex_filter_in() and regex_filter_out()

gluonrewritefixup_missing_path_info(environ)

gluonrewriteget_effective_router(appname)Returns a private copy of the effective router for the specified application

gluonrewriteinvalid_url(routes)

72 Chapter 23 rewrite Module

web2py Documentation Release 2146-stable

gluonrewriteload(routes=rsquoroutespyrsquo app=None data=None rdict=None)load read (if file) and parse routes store results in params (called from mainpy at web2py initialization time)If data is present itrsquos used instead of the routespy contents If rdict is present it must be a dict to be used forrouters (unit test)

gluonrewriteload_routers(all_apps)Load-time post-processing of routers

gluonrewritelog_rewrite(string)Log rewrite activity under control of routespy

gluonrewritemap_url_in(request env app=False)Routes incoming URL

gluonrewritemap_url_out(request env application controller function args other scheme hostport language=None)

Supply acf (or alangcf) portion of outgoing url

The basic rule is that we can only make transformations that map_url_in can reverse

Suppose that the incoming arguments are acfargslang and that the router defaults are da dc df dl

We can perform these transformations trivially if args=[] and lang=None or dl

dadcdf =gt adcdf =gt aacdf =gt ac

We would also like to be able to strip the default application or applicationcontroller from URLs with func-tionargs present thus

dacfargs =gt cfargsdadcfargs =gt fargs

We use [applications] and [controllers] and functions to suppress ambiguous omissions

We assume that language names do not collide with acf names

gluonrewriteregex_filter_in(e)Regex rewrite incoming URL

gluonrewriteregex_filter_out(url e=None)Regex rewrite outgoing URL

gluonrewriteregex_select(env=None app=None request=None)Selects a set of regex rewrite params for the current request

gluonrewriteregex_uri(e regexes tag default=None)Filters incoming URI against a list of regexes

gluonrewriteregex_url_in(request environ)Rewrites and parses incoming URL

gluonrewritesluggify(key)

gluonrewritetry_redirect_on_error(http_object request ticket=None)Called from mainwsgibase to rewrite the http response

gluonrewritetry_rewrite_on_error(http_response request environ ticket=None)Called from mainwsgibase to rewrite the http response

gluonrewriteurl_in(request environ)Parses and rewrites incoming URL

73

web2py Documentation Release 2146-stable

gluonrewriteurl_out(request environ application controller function args other scheme hostport language=None)

Assembles and rewrites outgoing URL

74 Chapter 23 rewrite Module

CHAPTER 24

sanitizer Module

From httpaspnactivestatecomASPNCookbookPythonRecipe496942Submitter Josh Goldfoot (other recipes)Last Updated 20060805Version 10

241 Cross-site scripting (XSS) defense

gluonsanitizersanitize(text permitted_tags=[rsquoarsquo rsquobrsquo rsquoblockquotersquo rsquobrrsquo rsquoirsquo rsquolirsquo rsquoolrsquo rsquoulrsquorsquoprsquo rsquocitersquo rsquocodersquo rsquoprersquo rsquoimgrsquo rsquoh1rsquo rsquoh2rsquo rsquoh3rsquo rsquoh4rsquo rsquoh5rsquo rsquoh6rsquo rsquota-blersquo rsquotbodyrsquo rsquotheadrsquo rsquotfootrsquo rsquotrrsquo rsquotdrsquo rsquodivrsquo rsquostrongrsquo rsquospanrsquo] al-lowed_attributes=rsquoarsquo [rsquohrefrsquo rsquotitlersquo] rsquoblockquotersquo [rsquotypersquo] rsquoimgrsquo[rsquosrcrsquo rsquoaltrsquo] rsquotdrsquo [rsquocolspanrsquo] escape=True)

75

web2py Documentation Release 2146-stable

76 Chapter 24 sanitizer Module

CHAPTER 25

scheduler Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

251 Background processes made simple

class gluonschedulerJobGraph(db job_name)Bases object

Experimental dependencies amongs tasks

add_deps(task_parent task_child)Create a dependency between task_parent and task_child

validate(job_name=None)Validate if all tasks job_name can be completed

Checks if there are no mutual dependencies among tasks Commits at the end if successfull or it rollbacksthe entire transaction Handle with care

class gluonschedulerMetaSchedulerBases threadingThread

Base class documenting schedulerrsquos base methods

async(task)Start the background process

Parameters task ndash a Task object

Returns

containing

77

web2py Documentation Release 2146-stable

(okresultoutput)(errorexceptionNone)(timeoutNoneNone)(terminatedNoneNone)

Return type tuple

die()Forces termination of the worker process along with any running task

give_up()Waits for any running task to be executed then exits the worker process

loop()Main loop fetching tasks and starting executorrsquos background processes

pop_task()Fetches a task ready to be executed

report_task(task task_report)Creates a task report

run()This is executed by the main thread to send heartbeats

send_heartbeat(counter)

sleep()

start_heartbeats()

terminate_process()Terminates any running tasks (internal use only)

class gluonschedulerScheduler(db tasks=None migrate=True worker_name=Nonegroup_names=None heartbeat=3 max_empty_runs=0discard_results=False utc_time=False)

Bases gluonschedulerMetaScheduler

Scheduler object

Parameters

bull db ndash DAL connection where Scheduler will create its tables

bull tasks (dict) ndash either a dict containing namendashgtfunc or None If None functions will besearched in the environment

bull migrate (bool) ndash turn migration onoff for the Schedulerrsquos tables

bull worker_name (str) ndash force worker_name to identify each process Leave it to None toautoassign a name (hostnamepid)

bull group_names (list) ndash process tasks belonging to this group defaults to [lsquomainrsquo] if noth-ing gets passed

bull heartbeat (int) ndash how many seconds the worker sleeps between one execution and thefollowing one Indirectly sets how many seconds will pass between checks for new tasks

bull max_empty_runs (int) ndash how many loops are allowed to pass without processing anytasks before exiting the process 0 to keep always the process alive

78 Chapter 25 scheduler Module

web2py Documentation Release 2146-stable

bull discard_results (bool) ndash Scheduler stores executionsrsquos details into the sched-uler_run table By default only if there is a result the details are kept Turning this toTrue means discarding results even for tasks that return something

bull utc_time (bool) ndash do all datetime calculations assuming UTC as the timezone Remem-ber to pass start_time and stop_time to tasks accordingly

adj_hibernation()Used to increase the ldquosleeprdquo interval for DISABLED workers

assign_tasks(db)Assign task to workers that can then pop them from the queue

Deals with group_name(s) logic in order to assign linearly tasks to available workers for those groups

being_a_ticker()Elect a TICKER process that assigns tasks to available workers

Does its best to elect a worker that is not busy processing other tasks to allow a proper distribution of tasksamong all active workers ASAP

define_tables(db migrate)Define Scheduler tables structure

disable(group_names=None limit=None worker_name=None)Set DISABLED on the workers processing group_names tasks

A DISABLED worker will be kept alive but it wonrsquot be able to process any waiting tasks essentiallyputting it to sleep By default all group_names of Schedulerrsquos instantation are selected

get_workers(only_ticker=False)Returns a dict holding worker_name columns representing all ldquoregisteredrdquo workers only_ticker re-turns only the workers running as a TICKER if there are any

kill(group_names=None limit=None worker_name=None)Sets KILL as worker status The worker will be killed even if itrsquos processing a task

loop(worker_name=None)Main loop

This works basically as a neverending loop that

bull checks if the worker is ready to process tasks (is not DISABLED)

bull pops a task from the queue

bull if there is a task

ndash spawns the executor background process

ndash waits for the process to be finished

ndash sleeps heartbeat seconds

bull if there is not a task

ndash checks for max_empty_runs

ndash sleeps heartbeat seconds

now()Shortcut that fetches current time based on UTC preferences

pop_task(db)Grab a task ready to be executed from the queue

251 Background processes made simple 79

web2py Documentation Release 2146-stable

queue_task(function pargs=[] pvars= kwargs)Queue tasks This takes care of handling the validation of all parameters

Parameters

bull function ndash the function (anything callable with a __name__)

bull pargs ndash ldquorawrdquo args to be passed to the function Automatically jsonified

bull pvars ndash ldquorawrdquo kwargs to be passed to the function Automatically jsonified

bull kwargs ndash all the parameters available (basically every scheduler_task column) If argsand vars are here they should be jsonified already and they will override pargs and pvars

Returns a dict just as a normal validate_and_insert() plus a uuid key holding the uuid of thequeued task If validation is not passed ( ie some parameters are invalid) both id and uuidwill be None and yoursquoll get an ldquoerrorrdquo dict holding the errors found

report_task(task task_report)Take care of storing the result according to preferences

Deals with logic for repeating tasks

resume(group_names=None limit=None worker_name=None)Wakes a worker up (it will be able to process queued tasks)

send_heartbeat(counter)Coordination among available workers

It - sends the heartbeat - elects a ticker among available workers (the only process that

effectively dispatch tasks to workers)

bull deals with workerrsquos statuses

bull does ldquohousecleaningrdquo for dead workers

bull triggers tasks assignment to workers

set_requirements(scheduler_task)Called to set defaults for lazy_tables connections

set_worker_status(group_names=None action=rsquoACTIVErsquo exclude=None limit=Noneworker_name=None)

Internal function to set workerrsquos status

sleep()Calculate the number of seconds to sleep

stop_task(ref)Shortcut for task termination

If the task is RUNNING it will terminate it meaning that status will be set as FAILED

If the task is QUEUED its stop_time will be set as to ldquonowrdquo the enabled flag will be set to False andthe status to STOPPED

Parameters ref ndash can be

bull an integer lookup will be done by scheduler_taskid

bull a string lookup will be done by scheduler_taskuuid

Returns

bull 1 if task was stopped (meaning an update has been done)

80 Chapter 25 scheduler Module

web2py Documentation Release 2146-stable

bull None if task was not found or if task was not RUNNING or QUEUED

Note Experimental

task_status(ref output=False)Retrieves task status and optionally the result of the task

Parameters

bull ref ndash can be

ndash an integer lookup will be done by scheduler_taskid

ndash a string lookup will be done by scheduler_taskuuid

ndash a Query lookup as you wish eg

dbscheduler_tasktask_name == test1

bull output (bool) ndash if True fetch also the scheduler_run record

Returns a single Row object for the last queued task If output == True returns also the lastscheduler_run record The scheduler_run record is fetched by a left join so it can have allfields == None

terminate(group_names=None limit=None worker_name=None)Sets TERMINATE as worker status The worker will wait for any currently running tasks to be executedand then it will exit gracefully

static total_seconds(td)Backport for py26

update_dependencies(db task_id)Unblock execution paths for Jobs

wrapped_assign_tasks(db)Commodity function to call assign_tasks and trap exceptions

If an exception is raised assume it happened because of database contention and retries assign_task after05 seconds

wrapped_pop_task()Commodity function to call pop_task and trap exceptions

If an exception is raised assume it happened because of database contention and retries pop_task after 05seconds

wrapped_report_task(task task_report)Commodity function to call report_task and trap exceptions

If an exception is raised assume it happened because of database contention and retries pop_task after 05seconds

class gluonschedulerTYPE(myclass=lttype rsquolistrsquogt parse=False)Bases object

Validator that checks whether field is valid json and validates its type Used for args and vars of the sched-uler_task table

class gluonschedulerTask(app function timeout args=rsquo[]rsquo vars=rsquorsquo kwargs)Bases object

251 Background processes made simple 81

web2py Documentation Release 2146-stable

Defines a ldquotaskrdquo object that gets passed from the main thread to the executorrsquos one

class gluonschedulerTaskReport(status result=None output=None tb=None)Bases object

Defines a ldquotask reportrdquo object that gets passed from the executorrsquos thread to the main one

gluonschedulerexecutor(queue task out)The function used to execute tasks in the background process

gluonschedulermain()allows to run worker without python web2pypy by simply

python gluonschedulerpy

82 Chapter 25 scheduler Module

CHAPTER 26

serializers Module

This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

gluonserializerscast_keys(o cast=lttype rsquostrrsquogt encoding=rsquoutf-8rsquo)Builds a new object with ltcastgt type keys Use this function if you are in Python lt 265 This avoids syntaxerrors when unpacking dictionary arguments

Parameters

bull o ndash is the object input

bull cast ndash (defaults to str) is an object type or function which supports conversion such as

converted = cast(o)

bull encoding ndash (defaults to utf-8) is the encoding for unicode keys This is not used forcustom cast functions

gluonserializerscsv(value)

gluonserializerscustom_json(o)

gluonserializersics(events title=None link=None timeshift=0 calname=True ignored)

gluonserializersjson(value default=ltfunction custom_jsongt)

gluonserializersloads_json(o unicode_keys=True kwargs)

gluonserializersloads_yaml(data)

gluonserializersrss(feed)

gluonserializerssafe_encode(text)

gluonserializersxml(value encoding=rsquoUTF-8rsquo key=rsquodocumentrsquo quote=True)

gluonserializersxml_rec(value key quote=True)

gluonserializersyaml(data)

83

web2py Documentation Release 2146-stable

84 Chapter 26 serializers Module

CHAPTER 27

settings Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

85

web2py Documentation Release 2146-stable

86 Chapter 27 settings Module

CHAPTER 28

shell Module

This file is part of the web2py Web FrameworkDeveloped by Massimo Di Pierro ltmdipierrocsdepauledugtlimodou ltlimodougmailcomgt and srackham ltsrackhamgmailcomgtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

281 Web2py environment in the shell

gluonshelldie(msg)

gluonshellenable_autocomplete_and_history(adir env)

gluonshellenv(a import_models=False c=None f=None dir=rdquo extra_request=)Returns web2py execution environment for application (a) controller (c) function (f) If import_models is Truethe exec all application models into the environment

extra_request allows you to pass along any extra variables to the request object before your models get executedThis was mainly done to support web2py_utilstest_runner however you can use it with any wrapper scripts thatneed access to the web2py environment

gluonshellexec_environment(pyfile=rdquo request=None response=None session=None)Environment builder and module loader

Builds a web2py environment and optionally executes a Python file into the environment

A Storage dictionary containing the resulting environment is returned The working directory must be web2pyroot ndash this is the web2py default

gluonshellexec_pythonrc()

gluonshellexecute_from_command_line(argv=None)

gluonshellget_usage()

87

web2py Documentation Release 2146-stable

gluonshellparse_path_info(path_info av=False)Parses path info formatted like acf where c and f are optional and a leading is accepted Return tuple (a c f)If invalid path_info a is set to None If c or f are omitted they are set to None If av=True parse args and vars

gluonshellrun(appname plain=False import_models=False startfile=None bpython=Falsepython_code=False cronjob=False)

Start interactive shell or run Python script (startfile) in web2py controller environment appname is formattedlike

bull a web2py application name

bull ac exec the controller c into the application environment

gluonshelltest(testpath import_models=True verbose=False)Run doctests in web2py environment testpath is formatted like

bull a tests all controllers in application a

bull ac tests controller c in application a

bull acf test function f in controller c application a

Where a c and f are application controller and function names respectively If the testpath is a file name the fileis tested If a controller is specified models are executed by default

88 Chapter 28 shell Module

CHAPTER 29

sql Module

This file is part of the web2py Web FrameworkDeveloped by Massimo Di Pierro ltmdipierrocsdepauledugtlimodou ltlimodougmailcomgt and srackham ltsrackhamgmailcomgtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

291 Just for backward compatibility

class gluonsqlDAL(uri=rsquosqlitedummydbrsquo pool_size=0 folder=None db_codec=rsquoUTF-8rsquo check_reserved=None migrate=True fake_migrate=False mi-grate_enabled=True fake_migrate_all=False decode_credentials=Falsedriver_args=None adapter_args=None attempts=5 auto_import=False big-int_id=False debug=False lazy_tables=False db_uid=None do_connect=Trueafter_connection=None tables=None ignore_field_case=True en-tity_quoting=False table_hash=None)

Bases pydalhelpersclassesSerializable pydalhelpersclassesBasicStorage

An instance of this class represents a database connection

Parameters

bull uri (str) ndash contains information for connecting to a database Defaults tolsquosqlitedummydbrsquo

Note experimental you can specify a dictionary as uri parameter ie with

db = DAL(uri sqlitestoragesqlitetables )

for an example of dict input you can check the output of the scaffolding db model with

dbas_dict()

89

web2py Documentation Release 2146-stable

Note that for compatibility with Python older than version 265 you should cast your dictinput keys to str due to a syntax limitation on kwarg names for proper DAL dictionary inputyou can use one of

obj = serializerscast_keys(dict [encoding=utf-8])or else (for parsing json input)obj = serializersloads_json(data unicode_keys=False)

bull pool_size ndash How many open connections to make to the database object

bull folder ndash where table files will be created Automatically set within web2py Use anexplicit path when using DAL outside web2py

bull db_codec ndash string encoding of the database (default lsquoUTF-8rsquo)

bull table_hash ndash database identifier with tables If your connection hash change you canstill using old tables if they have db_hash as prefix

bull check_reserved ndash list of adapters to check tablenames and column names againstsqlnosql reserved keywords Defaults to None

ndash rsquocommonrsquo List of sql keywords that are common to all database types such as ldquoSELECTINSERTrdquo (recommended)

ndash rsquoallrsquo Checks against all known SQL keywords

ndash rsquoltadapternamegtrdquo Checks against the specific adapters list of keywords

ndash rsquoltadapternamegt_nonreservedrsquo Checks against the specific adapters list of nonreservedkeywords (if available)

bull migrate ndash sets default migrate behavior for all tables

bull fake_migrate ndash sets default fake_migrate behavior for all tables

bull migrate_enabled ndash If set to False disables ALL migrations

bull fake_migrate_all ndash If set to True fake migrates ALL tables

bull attempts ndash Number of times to attempt connecting

bull auto_import ndash If set to True tries import automatically table definitions from thedatabases folder (works only for simple models)

bull bigint_id ndash If set turn on bigint instead of int for id and reference fields

bull lazy_tables ndash delays table definition until table access

bull after_connection ndash can a callable that will be executed after the connection

Example

Use as

db = DAL(sqlitetestdb)

or

90 Chapter 29 sql Module

web2py Documentation Release 2146-stable

db = DAL(uri tables []) experimental

dbdefine_table(tablename Field(fieldname1)Field(fieldname2))

class Field(fieldname type=rsquostringrsquo length=None default=ltfunction ltlambdagtgt re-quired=False requires=ltfunction ltlambdagtgt ondelete=rsquoCASCADErsquo not-null=False unique=False uploadfield=True widget=None label=None com-ment=None writable=True readable=True update=None authorize=Noneautodelete=False represent=None uploadfolder=None uploadseparate=Falseuploadfs=None compute=None custom_store=None custom_retrieve=Nonecustom_retrieve_file_properties=None custom_delete=None filter_in=None fil-ter_out=None custom_qualifier=None map_none=None rname=None)

Bases pydalobjectsExpression pydalhelpersclassesSerializable

Lazyalias of FieldMethod

Methodalias of FieldMethod

Virtualalias of FieldVirtual

as_dict(flat=False sanitize=True)

clone(point_self_references_to=False args)

count(distinct=None)

formatter(value)

retrieve(name path=None nameonly=False)If nameonly==True return (filename fullfilename) instead of (filename stream)

retrieve_file_properties(name path=None)

set_attributes(args attributes)

sqlsafe

sqlsafe_name

store(file filename=None path=None)

validate(value)

class Row(args kwargs)Bases pydalhelpersclassesBasicStorage

A dictionary that lets you do d[lsquoarsquo] as well as da this is only used to store a Row

as_dict(datetime_to_str=False custom_types=None)

as_json(mode=rsquoobjectrsquo default=None colnames=None serialize=True kwargs)serializes the row to a JSON object kwargs are passed to as_dict method only ldquoobjectrdquo mode sup-ported

serialize = False used by Rowsas_json

TODO return array mode with query column order

mode and colnames are not implemented

as_xml(row_name=rsquorowrsquo colnames=None indent=rsquo rsquo)

291 Just for backward compatibility 91

web2py Documentation Release 2146-stable

get(key default=None)

class Table(db tablename fields args)Bases pydalhelpersclassesSerializable pydalhelpersclassesBasicStorage

Represents a database table

Example

You can create a table as db = DAL( ) dbdefine_table(lsquousersrsquo Field(lsquonamersquo))

And then

dbusersinsert(name=me) print dbusers_insert() to see SQLdbusersdrop()

as_dict(flat=False sanitize=True)

bulk_insert(items)here items is a list of dictionaries

drop(mode=rdquo)

fields

import_from_csv_file(csvfile id_map=None null=rsquoltNULLgtrsquo unique=rsquouuidrsquoid_offset=None args kwargs)

Import records from csv file Column headers must have same names as table fields Field lsquoidrsquo isignored If column names read lsquotablefilersquo the lsquotablersquo prefix is ignored

bull lsquouniquersquo argument is a field which must be unique (typically a uuid field)bull lsquorestorersquo argument is default False if set True will remove old values in table firstbull lsquoid_maprsquo if set to None will not map ids

The import will keep the id numbers in the restored table This assumes that there is an field of typeid that is integer and in incrementing order Will keep the id numbers in restored table

insert(fields)

on(query)

sqlsafe

sqlsafe_alias

truncate(mode=None)

update(args kwargs)

update_or_insert(_key=ltfunction ltlambdagtgt values)

validate_and_insert(fields)

validate_and_update(_key=ltfunction ltlambdagtgt fields)

validate_and_update_or_insert(_key=ltfunction ltlambdagtgt fields)

with_alias(alias)

as_dict(flat=False sanitize=True)

can_join()

check_reserved_keyword(name)Validates name against SQL keywords Uses selfcheck_reserve which is a list of operators to use

close()

92 Chapter 29 sql Module

web2py Documentation Release 2146-stable

commit()

define_table(tablename fields args)

static distributed_transaction_begin(instances)

static distributed_transaction_commit(instances)

executesql(query placeholders=None as_dict=False fields=None colnames=Noneas_ordered_dict=False)

Executes an arbitrary query

Parameters

bull query (str) ndash the query to submit to the backend

bull placeholders ndash is optional and will always be None If using raw SQL with place-holders placeholders may be a sequence of values to be substituted in or (if supported bythe DB driver) a dictionary with keys matching named placeholders in your SQL

bull as_dict ndash will always be None when using DAL If using raw SQL can be set to Trueand the results cursor returned by the DB driver will be converted to a sequence of dic-tionaries keyed with the db field names Results returned with as_dict=True are the sameas those returned when applying to_list() to a DAL query If ldquoas_ordered_dictrdquo=True thebehaviour is the same as when ldquoas_dictrdquo=True with the keys (field names) guaranteed tobe in the same order as returned by the select name executed on the database

bull fields ndash list of DAL Fields that match the fields returned from the DB The Field objectsshould be part of one or more Table objects defined on the DAL object The ldquofieldsrdquo listcan include one or more DAL Table objects in addition to or instead of including Fieldobjects or it can be just a single table (not in a list) In that case the Field objects will beextracted from the table(s)

Note if either fields or colnames is provided the results will be converted to a DAL Rowsobject using the db_adapterparse() method

bull colnames ndash list of field names in tablenamefieldname format

Note It is also possible to specify both ldquofieldsrdquo and the associated ldquocolnamesrdquo In that case ldquofieldsrdquocan also include DAL Expression objects in addition to Field objects For Field objects in ldquofieldsrdquo theassociated ldquocolnamesrdquo must still be in tablenamefieldname format For Expression objects in ldquofieldsrdquo theassociated ldquocolnamesrdquo can be any arbitrary labels

DAL Table objects referred to by ldquofieldsrdquo or ldquocolnamesrdquo can be dummy tables and do not have to representany real tables in the database Also note that the ldquofieldsrdquo and ldquocolnamesrdquo must be in the same order asthe fields in the results cursor returned from the DB

export_to_csv_file(ofile args kwargs)

static get_instances()Returns a dictionary with uri as key with timings and defined tables

sqlitestoragesqlite dbstats [(select auth_useremail from auth_user 002009)]dbtables

defined [auth_cas auth_event auth_groupauth_membership auth_permission auth_user]

(continues on next page)

291 Just for backward compatibility 93

web2py Documentation Release 2146-stable

(continued from previous page)

lazy []

has_representer(name)

import_from_csv_file(ifile id_map=None null=rsquoltNULLgtrsquo unique=rsquouuidrsquomap_tablenames=None ignore_missing_tables=False args kwargs)

import_table_definitions(path migrate=False fake_migrate=False tables=None)

lazy_define_table(tablename fields args)

logger = ltloggingLogger objectgt

parse_as_rest(patterns args vars queries=None nested_select=True)

Example

Use as

dbdefine_table(personField(name)Field(info))dbdefine_table(pet

Field(ownedbydbperson)Field(name)Field(info)

)

requestrestful()def index()

def GET(argsvars)patterns = [

friends[person]personnamefieldpersonnamepets[petownedby]personnamepets[petownedby]petnamepersonnamepets[petownedby]petnamefield(dogs[pet] dbpetinfo==dog)(dogs[pet]petnamestartswith dbpetinfo==dog)]

parser = dbparse_as_rest(patternsargsvars)if parserstatus == 200

return dict(content=parserresponse)else

raise HTTP(parserstatusparsererror)

def POST(table_namevars)if table_name == person

return dbpersonvalidate_and_insert(vars)elif table_name == pet

return dbpetvalidate_and_insert(vars)else

raise HTTP(400)return locals()

represent(name args kwargs)

representers = rows_render ltfunction represent at 0x7fcf10dcdb18gt rows_xml ltclass gluonsqlhtmlSQLTABLEgt

94 Chapter 29 sql Module

web2py Documentation Release 2146-stable

rollback()

serializers = json ltfunction custom_json at 0x7fcf11069488gt xml ltfunction xml at 0x7fcf11069578gt

static set_folder(folder)

smart_query(fields text)

tables

uuid()

validators = None

validators_method(field)Field type validation using web2pyrsquos validators mechanism

makes sure the content of a field is in line with the declared fieldtype

where(query=None ignore_common_filters=None)

class gluonsqlField(fieldname type=rsquostringrsquo length=None default=ltfunction ltlambdagtgtrequired=False requires=ltfunction ltlambdagtgt ondelete=rsquoCASCADErsquonotnull=False unique=False uploadfield=True widget=None label=Nonecomment=None writable=True readable=True update=None autho-rize=None autodelete=False represent=None uploadfolder=None upload-separate=False uploadfs=None compute=None custom_store=Nonecustom_retrieve=None custom_retrieve_file_properties=None cus-tom_delete=None filter_in=None filter_out=None custom_qualifier=Nonemap_none=None rname=None)

Bases pydalobjectsExpression pydalhelpersclassesSerializable

LazyRepresents a database field

Example

Usage

a = Field(name string length=32 default=None required=Falserequires=IS_NOT_EMPTY() ondelete=CASCADEnotnull=False unique=Falseuploadfield=True widget=None label=None comment=Noneuploadfield=True True means store on disk

a_field_name means store in this field in db False means file content will be discarded

writable=True readable=True update=None authorize=Noneautodelete=False represent=None uploadfolder=Noneuploadseparate=False upload to separate directories by uuid_keys

first 2 character and tablenamefieldname False - old behavior True - put uploaded file in ltuploaddirgtlttablenamegtltfieldnamegtuuid_key[2] directory)

uploadfs=None a pyfilesystem where to store upload)

to be used as argument of DALdefine_table

alias of FieldMethod

291 Just for backward compatibility 95

web2py Documentation Release 2146-stable

Methodalias of FieldMethod

Virtualalias of FieldVirtual

as_dict(flat=False sanitize=True)

clone(point_self_references_to=False args)

count(distinct=None)

formatter(value)

retrieve(name path=None nameonly=False)If nameonly==True return (filename fullfilename) instead of (filename stream)

retrieve_file_properties(name path=None)

set_attributes(args attributes)

sqlsafe

sqlsafe_name

store(file filename=None path=None)

validate(value)

96 Chapter 29 sql Module

CHAPTER 30

sqlhtml Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

Holds

bull SQLFORM provide a form for a table (withwithout record)

bull SQLTABLE provides a table for a set of records

bull form_factory provides a SQLFORM for an non-db backed table

class gluonsqlhtmlAutocompleteWidget(request field id_field=None db=None or-derby=None limitby=(0 10) distinct=False key-word=rsquo_autocomplete_(tablename)s_(fieldname)srsquomin_length=2 help_fields=Nonehelp_string=None at_beginning=True)

Bases object

callback()

class gluonsqlhtmlBooleanWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates an INPUT checkbox tag

see also FormWidgetwidget

class gluonsqlhtmlCacheRepresenterBases object

class gluonsqlhtmlCheckboxesWidgetBases gluonsqlhtmlOptionsWidget

classmethod widget(field value attributes)Generates a TABLE tag including INPUT checkboxes (multiple allowed)

97

web2py Documentation Release 2146-stable

see also FormWidgetwidget

class gluonsqlhtmlDateWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlDatetimeWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlDecimalWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlDoubleWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlExportClass(rows)Bases object

content_type = None

export()

file_ext = None

label = None

represented()

class gluonsqlhtmlExporterCSV(rows)Bases gluonsqlhtmlExportClass

content_type = textcsv

export()

file_ext = csv

label = CSV

class gluonsqlhtmlExporterCSV_hidden(rows)Bases gluonsqlhtmlExportClass

content_type = textcsv

export()

file_ext = csv

label = CSV

class gluonsqlhtmlExporterHTML(rows)Bases gluonsqlhtmlExportClass

content_type = texthtml

export()

file_ext = html

label = HTML

class gluonsqlhtmlExporterJSON(rows)Bases gluonsqlhtmlExportClass

content_type = applicationjson

export()

file_ext = json

98 Chapter 30 sqlhtml Module

web2py Documentation Release 2146-stable

label = JSON

class gluonsqlhtmlExporterTSV(rows)Bases gluonsqlhtmlExportClass

content_type = texttab-separated-values

export()

file_ext = csv

label = TSV

class gluonsqlhtmlExporterXML(rows)Bases gluonsqlhtmlExportClass

content_type = textxml

export()

file_ext = xml

label = XML

class gluonsqlhtmlFormWidgetBases object

Helper for SQLFORM to generate form input fields (widget) related to the fieldtype

classmethod widget(field value attributes)Generates the widget for the field

When serialized will provide an INPUT tag

bull id = tablename_fieldname

bull class = fieldtype

bull name = fieldname

Parameters

bull field ndash the field needing the widget

bull value ndash value

bull attributes ndash any other attributes to be applied

class gluonsqlhtmlIntegerWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlJSONWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates a TEXTAREA for JSON notation

see also FormWidgetwidget

class gluonsqlhtmlListWidgetBases gluonsqlhtmlStringWidget

classmethod widget(field value attributes)Generates an INPUT text tag

see also FormWidgetwidget

99

web2py Documentation Release 2146-stable

class gluonsqlhtmlMultipleOptionsWidgetBases gluonsqlhtmlOptionsWidget

classmethod widget(field value size=5 attributes)Generates a SELECT tag including OPTIONs (multiple options allowed)

see also FormWidgetwidget

Parameters size ndash optional param (default=5) to indicate how many rows must be shown

class gluonsqlhtmlOptionsWidgetBases gluonsqlhtmlFormWidget

static has_options(field)Checks if the field has selectable options

Parameters field ndash the field needing checking

Returns True if the field has options

classmethod widget(field value attributes)Generates a SELECT tag including OPTIONs (only 1 option allowed)

see also FormWidgetwidget

class gluonsqlhtmlPasswordWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates a INPUT password tag If a value is present it will be shown as a number of lsquorsquo not related tothe length of the actual value

see also FormWidgetwidget

class gluonsqlhtmlRadioWidgetBases gluonsqlhtmlOptionsWidget

classmethod widget(field value attributes)Generates a TABLE tag including INPUT radios (only 1 option allowed)

see also FormWidgetwidget

class gluonsqlhtmlSQLFORM(table record=None deletable=False linkto=None upload=Nonefields=None labels=None col3= submit_button=rsquoSubmitrsquodelete_label=rsquoCheck to deletersquo showid=True readonly=False com-ments=True keepopts=[] ignore_rw=False record_id=Noneformstyle=None buttons=[rsquosubmitrsquo] separator=None ex-tra_fields=None attributes)

Bases gluonhtmlFORM

SQLFORM is used to map a table (and a current record) into an HTML form

Given a Table like dbtable

Generates an insert form

SQLFORM(dbtable)

Generates an update form

record=dbtable[some_id]SQLFORM(dbtable record)

Generates an update with a delete button

100 Chapter 30 sqlhtml Module

web2py Documentation Release 2146-stable

SQLFORM(dbtable record deletable=True)

Parameters

bull table ndash Table object

bull record ndash either an int if the id is an int or the record fetched from the table

bull deletable ndash adds the delete checkbox

bull linkto ndash the URL of a controllerfunction to access referencedby records

bull upload ndash the URL of a controllerfunction to download an uploaded file

bull fields ndash a list of fields that should be placed in the form default is all

bull labels ndash a dictionary with labels for each field keys are the field names

bull col3 ndash a dictionary with content for an optional third column (right of each field) keys arefield names

bull submit_button ndash text to show in the submit button

bull delete_label ndash text to show next to the delete checkbox

bull showid ndash shows the id of the record

bull readonly ndash doesnrsquot allow for any modification

bull comments ndash show comments (stored in col3 or in Field definition)

bull ignore_rw ndash overrides readablewritable attributes

bull record_id ndash used to create session key against CSRF

bull formstyle ndash what to use to generate the form layout

bull buttons ndash override buttons as you please (will be also stored in formcustomsubmit)

bull separator ndash character as separator between labels and inputs

any named optional attribute is passed to the ltformgt tag for example _class _id _style _action _method etc

AUTOTYPES = lttype intgt (integer ltgluonvalidatorsIS_INT_IN_RANGE object at 0x7fcf10deb210gt) lttype floatgt (double ltgluonvalidatorsIS_FLOAT_IN_RANGE object at 0x7fcf10deb250gt) lttype unicodegt (string None) lttype boolgt (boolean None) lttype strgt (string None) lttype listgt (liststring None) lttype datetimedatetimegt (datetime ltgluonvalidatorsIS_DATETIME object at 0x7fcf10deb310gt) lttype datetimedategt (date ltgluonvalidatorsIS_DATE object at 0x7fcf10deb2d0gt)

FIELDKEY_DELETE_RECORD = delete_record

FIELDNAME_REQUEST_DELETE = delete_this_record

ID_LABEL_SUFFIX = __label

ID_ROW_SUFFIX = __row

accepts(request_vars session=None formname=rsquo(tablename)s(record_id)srsquo keepvalues=Noneonvalidation=None dbio=True hideerror=False detect_record_change=False kwargs)

Similar to FORMaccepts but also does insert update or delete in DAL If detect_record_change is Truethan

bull formrecord_changed = False (record is properly validatedsubmitted)

bull formrecord_changed = True (record cannot be submitted because changed)

If detect_record_change == False than

bull formrecord_changed = None

assert_status(status request_vars)

101

web2py Documentation Release 2146-stable

static build_query(fields keywords)

createform(xfields)

static dictform(dictionary kwargs)

static factory(fields attributes)Generates a SQLFORM for the given fields

Internally will build a non-database based data model to hold the fields

formstyles = bootstrap ltfunction formstyle_bootstrap at 0x7fcf10de99b0gt bootstrap3_inline ltfunction _inner at 0x7fcf10de9b90gt bootstrap3_stacked ltfunction formstyle_bootstrap3_stacked at 0x7fcf10de9a28gt divs ltfunction formstyle_divs at 0x7fcf10de9848gt inline ltfunction formstyle_inline at 0x7fcf10de98c0gt table2cols ltfunction formstyle_table2cols at 0x7fcf10de97d0gt table3cols ltfunction formstyle_table3cols at 0x7fcf10dcdde8gt ul ltfunction formstyle_ul at 0x7fcf10de9938gt

static grid(query fields=None field_id=None left=None headers= or-derby=None groupby=None searchable=True sortable=True pagi-nate=20 deletable=True editable=True details=True selectable=None cre-ate=True csv=True links=None links_in_grid=True upload=rsquoltdefaultgtrsquoargs=[] user_signature=True maxtextlengths= maxtextlength=20 on-validation=None onfailure=None oncreate=None onupdate=None on-delete=None sorter_icons=(ltgluonhtmlXML objectgt ltgluonhtmlXMLobjectgt) ui=rsquoweb2pyrsquo showbuttontext=True _class=rsquoweb2py_gridrsquo form-name=rsquoweb2py_gridrsquo search_widget=rsquodefaultrsquo advanced_search=True ig-nore_rw=False formstyle=None exportclasses=None formargs= cre-ateargs= editargs= viewargs= selectable_submit_button=rsquoSubmitrsquobuttons_placement=rsquorightrsquo links_placement=rsquorightrsquo noconfirm=Falsecache_count=None client_side_delete=False ignore_common_filters=Noneauto_pagination=True use_cursor=False)

static search_menu(fields search_options=None prefix=rsquow2prsquo)

static smartdictform(session name filename=None query=None kwargs)

static smartgrid(table constraints=None linked_tables=None links=None links_in_grid=Trueargs=None user_signature=True divider=rsquogtrsquo breadcrumbs_class=rdquokwargs)

Builds a system of SQLFORMgrid(s) between any referenced tables

Parameters

bull table ndash main table

bull constraints (dict) ndash lsquotablersquoquery that limits which records can be accessible

bull links (dict) ndash like lsquotablenamersquo[lambda row A( ) ] that will add buttons whentable tablename is displayed

bull linked_tables (list) ndash list of tables to be linked

Example

given you defined a model as

dbdefine_table(person Field(name) format=(name)s)dbdefine_table(dog

Field(name) Field(owner dbperson) format=(name)s)dbdefine_table(comment Field(body) Field(dog dbdog))if db(dbperson)isempty()

from gluoncontribpopulate import populatepopulate(dbperson 300)populate(dbdog 300)populate(dbcomment 1000)

102 Chapter 30 sqlhtml Module

web2py Documentation Release 2146-stable

in a controller you can do

authrequires_login()def index()

form=SQLFORMsmartgrid(db[requestargs(0) or person])return dict(form=form)

widgets = autocomplete ltclass gluonsqlhtmlAutocompleteWidgetgt blob None boolean ltclass gluonsqlhtmlBooleanWidgetgt checkboxes ltclass gluonsqlhtmlCheckboxesWidgetgt date ltclass gluonsqlhtmlDateWidgetgt datetime ltclass gluonsqlhtmlDatetimeWidgetgt decimal ltclass gluonsqlhtmlDecimalWidgetgt double ltclass gluonsqlhtmlDoubleWidgetgt integer ltclass gluonsqlhtmlIntegerWidgetgt json ltclass gluonsqlhtmlJSONWidgetgt list ltclass gluonsqlhtmlListWidgetgt multiple ltclass gluonsqlhtmlMultipleOptionsWidgetgt options ltclass gluonsqlhtmlOptionsWidgetgt password ltclass gluonsqlhtmlPasswordWidgetgt radio ltclass gluonsqlhtmlRadioWidgetgt string ltclass gluonsqlhtmlStringWidgetgt text ltclass gluonsqlhtmlTextWidgetgt time ltclass gluonsqlhtmlTimeWidgetgt upload ltclass gluonsqlhtmlUploadWidgetgt

class gluonsqlhtmlSQLTABLE(sqlrows linkto=None upload=None orderby=None headers=truncate=16 columns=None th_link=rdquo extracolumns=None se-lectid=None renderstyle=False cid=None colgroup=False at-tributes)

Bases gluonhtmlTABLE

Given with a Rows object as returned by a db()select() generates an html table with the rows

Parameters

bull sqlrows ndash the Rows object

bull linkto ndash URL (or lambda to generate a URL) to edit individual records

bull upload ndash URL to download uploaded files

bull orderby ndash Add an orderby link to column headers

bull headers ndash dictionary of headers to headers redefinions headers can also be a string to gen-erate the headers from data for now only headers=rdquofieldnamecapitalizerdquo headers=rdquolabelsrdquoand headers=None are supported

bull truncate ndash length at which to truncate text in table cells Defaults to 16 characters

bull columns ndash a list or dict contaning the names of the columns to be shown Defaults to all

bull th_link ndash base link to support orderby headers

bull extracolumns ndash a list of dicts

bull selectid ndash The id you want to select

bull renderstyle ndash Boolean render the style with the table

bull cid ndash use this cid for all links

bull colgroup ndash FIXME

Extracolumns example

[labelA(Extra _href=)class class name of the headerwidth width in pixels or contentlambda row rc A(Edit _href=editsrowid)selected False agregate class selected to this column]

style()

class gluonsqlhtmlStringWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates an INPUT text tag

see also FormWidgetwidget

103

web2py Documentation Release 2146-stable

class gluonsqlhtmlTextWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates a TEXTAREA tag

see also FormWidgetwidget

class gluonsqlhtmlTimeWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlUploadWidgetBases gluonsqlhtmlFormWidget

DEFAULT_WIDTH = 150px

DELETE_FILE = delete

GENERIC_DESCRIPTION = file download

ID_DELETE_SUFFIX = __delete

static is_image(value)Tries to check if the filename provided references to an image

Checking is based on filename extension Currently recognized gif png jp(e)g bmp

Parameters value ndash filename

classmethod represent(field value download_url=None)How to represent the file

bull with download url and if it is an image ltA href= gtltIMG gtltAgt

bull otherwise with download url ltA href= gtfileltAgt

bull otherwise file

Parameters

bull field ndash the field

bull value ndash the field value

bull download_url ndash url for the file download (default = None)

classmethod widget(field value download_url=None attributes)generates a INPUT file tag

Optionally provides an A link to the file including a checkbox so the file can be deleted

All is wrapped in a DIV

see also FormWidgetwidget

Parameters

bull field ndash the field

bull value ndash the field value

bull download_url ndash url for the file download (default = None)

gluonsqlhtmladd_class(a b)

104 Chapter 30 sqlhtml Module

web2py Documentation Release 2146-stable

gluonsqlhtmlform_factory(fields attributes)Generates a SQLFORM for the given fields

Internally will build a non-database based data model to hold the fields

gluonsqlhtmlformstyle_bootstrap(form fields)bootstrap 23x format form layout

gluonsqlhtmlformstyle_bootstrap3_inline_factory(col_label_size=3)bootstrap 3 horizontal form layout

Note Experimental

gluonsqlhtmlformstyle_bootstrap3_stacked(form fields)bootstrap 3 format form layout

Note Experimental

gluonsqlhtmlformstyle_divs(form fields)divs only

gluonsqlhtmlformstyle_inline(form fields)divs only but inline

gluonsqlhtmlformstyle_table2cols(form fields)2 column table

gluonsqlhtmlformstyle_table3cols(form fields)3 column table - default

gluonsqlhtmlformstyle_ul(form fields)unordered list

gluonsqlhtmlrepresent(field value record)

gluonsqlhtmlsafe_float(x)

gluonsqlhtmlsafe_int(x)

gluonsqlhtmlshow_if(cond)

105

web2py Documentation Release 2146-stable

106 Chapter 30 sqlhtml Module

CHAPTER 31

storage Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

Provides

bull List like list but returns None instead of IndexOutOfBounds

bull Storage like dictionary allowing also for objfoo for obj[lsquofoorsquo]

class gluonstorageListBases list

Like a regular python list but callable When a(i) is called if i is out of bounds returns None instead of IndexError

class gluonstorageStorageBases dict

A Storage object is like a dictionary except objfoo can be used in addition to obj[lsquofoorsquo] and setting objfoo =None deletes item foo

Example

gtgtgt o = Storage(a=1)gtgtgt print oa1

gtgtgt o[a]1

gtgtgt oa = 2gtgtgt print o[a]2

gtgtgt del oa

(continues on next page)

107

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt print oaNone

getfirst(key default=None)Returns the first value of a list or the value itself when given a requestvars style key

If the value is a list its first item will be returned otherwise the value will be returned as-is

Example output for a query string of x=abcampy=abcampy=def

gtgtgt request = Storage()gtgtgt requestvars = Storage()gtgtgt requestvarsx = abcgtgtgt requestvarsy = [abc def]gtgtgt requestvarsgetfirst(x)abcgtgtgt requestvarsgetfirst(y)abcgtgtgt requestvarsgetfirst(z)

getlast(key default=None)Returns the last value of a list or value itself when given a requestvars style key

If the value is a list the last item will be returned otherwise the value will be returned as-is

Simulated output with a query string of x=abcampy=abcampy=def

gtgtgt request = Storage()gtgtgt requestvars = Storage()gtgtgt requestvarsx = abcgtgtgt requestvarsy = [abc def]gtgtgt requestvarsgetlast(x)abcgtgtgt requestvarsgetlast(y)defgtgtgt requestvarsgetlast(z)

getlist(key)Returns a Storage value as a list

If the value is a list it will be returned as-is If object is None an empty list will be returned Otherwise[value] will be returned

Example output for a query string of x=abcampy=abcampy=def

gtgtgt request = Storage()gtgtgt requestvars = Storage()gtgtgt requestvarsx = abcgtgtgt requestvarsy = [abc def]gtgtgt requestvarsgetlist(x)[abc]gtgtgt requestvarsgetlist(y)[abc def]gtgtgt requestvarsgetlist(z)[]

class gluonstorageSettingsBases gluonstorageStorage

108 Chapter 31 storage Module

web2py Documentation Release 2146-stable

class gluonstorageMessages(T)Bases gluonstorageSettings

class gluonstorageStorageListBases gluonstorageStorage

Behaves like Storage but missing elements defaults to [] instead of None

gluonstorageload_storage(filename)

gluonstoragesave_storage(storage filename)

109

web2py Documentation Release 2146-stable

110 Chapter 31 storage Module

CHAPTER 32

streamer Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

321 Facilities to handle file streaming

gluonstreamerstream_file_or_304_or_206(static_file chunk_size=65536 request=Noneheaders= status=200 error_message=None)

gluonstreamerstreamer(stream chunk_size=65536 bytes=None)

111

web2py Documentation Release 2146-stable

112 Chapter 32 streamer Module

CHAPTER 33

template Module

This file is part of the web2py Web FrameworkLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)Author Thadeus BurgessContributors- Massimo Di Pierro for creating the original gluontemplatepy- Jonathan Lundell for extensively testing the regex on Jython- Limodou (creater of uliweb) who inspired the block-element support for web2py

331 Templating syntax

class gluontemplateBlockNode(name=rdquo pre_extend=False delimiters=(rsquorsquo rsquorsquo))Bases gluontemplateNode

Block Container

This Node can contain other Nodes and will render in a hierarchical order of when nodes were added

ie

block test This is default block test

end

append(node)Adds an element to the nodes

Parameters node ndash Node object or string to append

extend(other)Extends the list of nodes with another BlockNode class

Parameters other ndash BlockNode or Content object to extend from

113

web2py Documentation Release 2146-stable

output(blocks)Merges all nodes into a single string

Parameters blocks ndash Dictionary of blocks that are extending from this template

class gluontemplateContent(name=rsquoContentBlockrsquo pre_extend=False)Bases gluontemplateBlockNode

Parent Container ndash Used as the root level BlockNode

Contains functions that operate as such

Parameters name ndash Unique name for this BlockNode

append(node)Adds a node to list If it is a BlockNode then we assign a block for it

clear_content()

extend(other)Extends the objects list of nodes with another objects nodes

insert(other index=0)Inserts object at index

You may pass a list of objects and have them inserted

class gluontemplateDummyResponse

write(data escape=True)

class gluontemplateNOESCAPE(text)A little helper to avoid escaping

xml()

class gluontemplateNode(value=None pre_extend=False)Bases object

Basic Container Object

class gluontemplateSuperNode(name=rdquo pre_extend=False)Bases gluontemplateNode

class gluontemplateTemplateParser(text name=rsquoParserContainerrsquo context=path=rsquoviewsrsquo writer=rsquoresponsewritersquo lexers=delimiters=(rsquorsquo rsquorsquo) _super_nodes=[])

Bases object

Parse all blocks

Parameters

bull text ndash text to parse

bull context ndash context to parse in

bull path ndash folder path to templates

bull writer ndash string of writer class to use

bull lexers ndash dict of custom lexers to use

bull delimiters ndash for example (lsquolsquorsquorsquo)

114 Chapter 33 template Module

web2py Documentation Release 2146-stable

bull _super_nodes ndash a list of nodes to check for inclusion this should only be set byldquoselfextendrdquo It contains a list of SuperNodes from a child template that need to be han-dled

default_delimiters = ( )

extend(filename)Extends filename Anything not declared in a block defined by the parent will be placed in the parenttemplates include block

include(content filename)Includes filename here

parse(text)

r_multiline = lt_sreSRE_Pattern objectgt

r_tag = lt_sreSRE_Pattern objectgt

re_block = lt_sreSRE_Pattern objectgt

re_pass = lt_sreSRE_Pattern objectgt

re_unblock = lt_sreSRE_Pattern objectgt

reindent(text)Reindents a string of unindented python code

to_string()Returns the parsed template with correct indentation

Used to make it easier to port to python3

gluontemplateget_parsed(text)Returns the indented python code of text Useful for unit testing

gluontemplateoutput_aux(node blocks)

gluontemplateparse_template(filename path=rsquoviewsrsquo context= lexers= delimiters=(rsquorsquorsquorsquo))

Parameters

bull filename ndash can be a view filename in the views folder or an input stream

bull path ndash is the path of a views folder

bull context ndash is a dictionary of symbols used to render the template

bull lexers ndash dict of custom lexers to use

bull delimiters ndash opening and closing tags

gluontemplaterender(content=rsquohello worldrsquo stream=None filename=None path=None con-text= lexers= delimiters=(rsquorsquo rsquorsquo) writer=rsquoresponsewritersquo)

Generic render function

Parameters

bull content ndash default content

bull stream ndash file-like obj to read template from

bull filename ndash where to find template

bull path ndash base path for templates

bull context ndash env

331 Templating syntax 115

web2py Documentation Release 2146-stable

bull lexers ndash custom lexers to use

bull delimiters ndash opening and closing tags

bull writer ndash where to inject the resulting stream

Example

gtgtgt render()hello worldgtgtgt render(content=abc)abcgtgtgt render(content=abc)abcgtgtgt render(content=abc)abcgtgtgt render(content=anbc)anbcgtgtgt render(content=abcde)abcdegtgtgt render(content=anc)ancgtgtgt render(content=ac)acgtgtgt render(content=for i in range(a)=iltbr gtpassrarr˓context=dict(a=5))0ltbr gt1ltbr gt2ltbr gt3ltbr gt4ltbr gtgtgtgt render(content=for i in range(a)=iltbr gtpassrarr˓context=dict(a=5)delimiters=())0ltbr gt1ltbr gt2ltbr gt3ltbr gt4ltbr gtgtgtgt render(content==hellonworld)hellonworldgtgtgt render(content=for i in range(3)n=inpass)012

116 Chapter 33 template Module

CHAPTER 34

tools Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

341 Auth Mail PluginManager and various utilities

class gluontoolsMail(server=None sender=None login=None tls=True)Bases object

Class for configuring and sending emails with alternative text html body multiple attachments and encryptionsupport

Works with SMTP and Google App Engine

Parameters

bull server ndash SMTP server address in addressport notation

bull sender ndash sender email address

bull login ndash sender login name and password in loginpassword notation or None if no authen-tication is required

bull tls ndash enablesdisables encryption (True by default)

In Google App Engine use

server=gae

For sake of backward compatibility all fields are optional and default to None however to be able to send emailsat least server and sender must be specified They are available under following fields

117

web2py Documentation Release 2146-stable

mailsettingsservermailsettingssendermailsettingsloginmailsettingstimeout = 60 seconds (default)

When server is lsquologgingrsquo email is logged but not sent (debug mode)

Optionally you can use PGP encryption or X509

mailsettingscipher_type = Nonemailsettingsgpg_home = Nonemailsettingssign = Truemailsettingssign_passphrase = Nonemailsettingsencrypt = Truemailsettingsx509_sign_keyfile = Nonemailsettingsx509_sign_certfile = Nonemailsettingsx509_sign_chainfile = Nonemailsettingsx509_nocerts = Falsemailsettingsx509_crypt_certfiles = None

cipher_type Nonegpg - need a python-pyme package and gpgme libx509 - smime

gpg_home you can set a GNUPGHOME environment variableto specify home of gnupg

sign sign the message (True or False)sign_passphrase passphrase for key signingencrypt encrypt the message (True or False) It defaults

to True x509 only

x509_sign_keyfile the signers private key filename orstring containing the key (PEM format)

x509_sign_certfile the signers certificate filename orstring containing the cert (PEM format)

x509_sign_chainfile sets the optional all-in-one file where youcan assemble the certificates of CertificationAuthorities (CA) which form the certificatechain of email certificate It can be astring containing the certs to (PEM format)

x509_nocerts if True then no attached certificate in mailx509_crypt_certfiles the certificates file or strings to encrypt

the messages with can be a file name string or a list of file names strings (PEM format)

Examples

Create Mail object with authentication data for remote server

mail = Mail(examplecom25 meexamplecom mepassword)

Notice for GAE users attachments have an automatic content_id=rsquoattachment-irsquo where i is progressive num-ber in this way the can be referenced from the HTML as ltimg src=rdquocidattachment-0rdquo gt etc

118 Chapter 34 tools Module

web2py Documentation Release 2146-stable

class Attachment(payload filename=None content_id=None content_type=Noneencoding=rsquoutf-8rsquo)

Bases emailmimebaseMIMEBase

Email attachment

Parameters

bull payload ndash path to file or file-like object with read() method

bull filename ndash name of the attachment stored in message if set to None it will be fetchedfrom payload path file-like object payload must have explicit filename specified

bull content_id ndash id of the attachment automatically contained within lt and gt

bull content_type ndash content type of the attachment if set to None it will be fetched fromfilename using gluoncontenttype module

bull encoding ndash encoding of all strings passed to this function (except attachment body)

Content ID is used to identify attachments within the html body in example attached image with contentID lsquophotorsquo may be used in html message as a source of img tag ltimg src=rdquocidphotordquo gt

Example Create attachment from text file

attachment = MailAttachment(pathtofiletxt)

Content-Type textplainMIME-Version 10Content-Disposition attachment filename=filetxtContent-Transfer-Encoding base64

SOMEBASE64CONTENT=

Create attachment from image file with custom filename and cid

attachment = MailAttachment(pathtofilepngfilename=photopngcontent_id=photo)

Content-Type imagepngMIME-Version 10Content-Disposition attachment filename=photopngContent-Id ltphotogtContent-Transfer-Encoding base64

SOMEOTHERBASE64CONTENT=

send(to subject=rsquo[no subject]rsquo message=rsquo[no message]rsquo attachments=None cc=None bcc=Nonereply_to=None sender=None encoding=rsquoutf-8rsquo raw=False headers= from_address=Nonecipher_type=None sign=None sign_passphrase=None encrypt=None x509_sign_keyfile=Nonex509_sign_chainfile=None x509_sign_certfile=None x509_crypt_certfiles=Nonex509_nocerts=None)

Sends an email using data specified in constructor

Parameters

bull to ndash list or tuple of receiver addresses will also accept single object

bull subject ndash subject of the email

bull message ndash email body text depends on type of passed object

341 Auth Mail PluginManager and various utilities 119

web2py Documentation Release 2146-stable

ndash if 2-list or 2-tuple is passed first element will be source of plain text while second ofhtml text

ndash otherwise object will be the only source of plain text and html source will be set toNone

If text or html source is

ndash None content part will be ignored

ndash string content part will be set to it

ndash file-like object content part will be fetched from it using itrsquos read() method

bull attachments ndash list or tuple of MailAttachment objects will also accept single object

bull cc ndash list or tuple of carbon copy receiver addresses will also accept single object

bull bcc ndash list or tuple of blind carbon copy receiver addresses will also accept single object

bull reply_to ndash address to which reply should be composed

bull encoding ndash encoding of all strings passed to this method (including message bodies)

bull headers ndash dictionary of headers to refine the headers just before sending mail eg lsquoX-Mailerrsquo lsquoweb2py mailerrsquo

bull from_address ndash address to appear in the lsquoFromrsquo header this is not the envelopesender If not specified the sender will be used

bull cipher_type ndash gpg - need a python-pyme package and gpgme lib x509 - smime

bull gpg_home ndash you can set a GNUPGHOME environment variable to specify home ofgnupg

bull sign ndash sign the message (True or False)

bull sign_passphrase ndash passphrase for key signing

bull encrypt ndash encrypt the message (True or False) It defaults to True x509 only

bull x509_sign_keyfile ndash the signers private key filename or string containing the key(PEM format)

bull x509_sign_certfile ndash the signers certificate filename or string containing the cert(PEM format)

bull x509_sign_chainfile ndash sets the optional all-in-one file where you can assemblethe certificates of Certification Authorities (CA) which form the certificate chain of emailcertificate It can be a string containing the certs to (PEM format)

bull x509_nocerts ndash if True then no attached certificate in mail

bull x509_crypt_certfiles ndash the certificates file or strings to encrypt the messages withcan be a file name string or a list of file names strings (PEM format)

Examples

Send plain text message to single address

mailsend(youexamplecomMessage subjectPlain text body of the message)

120 Chapter 34 tools Module

web2py Documentation Release 2146-stable

Send html message to single address

mailsend(youexamplecomMessage subjectlthtmlgtPlain text body of the messagelthtmlgt)

Send text and html message to three addresses (two in cc)

mailsend(youexamplecomMessage subject(Plain text body lthtmlgthtml bodylthtmlgt)cc=[other1examplecom other2examplecom])

Send html only message with image attachment available from the message by lsquophotorsquo content id

mailsend(youexamplecomMessage subject(None lthtmlgtltimg src=cidphoto gtlthtmlgt)MailAttachment(pathtophotojpg

content_id=photo))

Send email with two attachments and no body text

mailsend(youexamplecomMessage subjectNone[MailAttachment(pathtofistfile)MailAttachment(pathtosecondfile)])

Returns True on success False on failure

Before return method updates two objectrsquos fields

bull selfresult return value of smtplibSMTPsendmail() or GAErsquos mailsend_mail() method

bull selferror Exception message or None if above was successful

class gluontoolsAuth(environment=None db=None mailer=True hmac_key=None con-troller=rsquodefaultrsquo function=rsquouserrsquo cas_provider=None signature=Truesecure=False csrf_prevention=True propagate_extension=Noneurl_index=None jwt=None host_names=None)

Bases object

accessible_query(name table user_id=None)Returns a query with all accessible records for user_id or the current logged in user this method does notwork on GAE because uses JOIN and IN

Example

Use as

db(authaccessible_query(read dbmytable))select(dbmytableALL)

add_group(role description=rdquo)Creates a group associated to a role

add_membership(group_id=None user_id=None role=None)Gives user_id membership of group_id or role if user is None than user_id is that of current logged in user

341 Auth Mail PluginManager and various utilities 121

web2py Documentation Release 2146-stable

add_permission(group_id name=rsquoanyrsquo table_name=rdquo record_id=0)Gives group_id lsquonamersquo access to lsquotable_namersquo and lsquorecord_idrsquo

allows_jwt(otherwise=None)

static archive(form archive_table=None current_record=rsquocurrent_recordrsquoarchive_current=False fields=None)

If you have a table (dbmytable) that needs full revision history you can just do

form = crudupdate(dbmytable myrecord onaccept=autharchive)

or

form = SQLFORM(dbmytable myrecord)process(onaccept=autharchive)

crudarchive will define a new table ldquomytable_archiverdquo and store a copy of the current record (ifarchive_current=True) or a copy of the previous record (if archive_current=False) in the newly createdtable including a reference to the current record

fields allows to specify extra fields that need to be archived

If you want to access such table you need to define it yourself in a model

dbdefine_table(mytable_archiveField(current_record dbmytable)dbmytable)

Notice such table includes all fields of dbmytable plus one current_record crudarchive does not times-tamp the stored record unless your original table has a fields like

dbdefine_table(Field(saved_on datetime

default=requestnow update=requestnow writable=False)Field(saved_by authuser

default=authuser_id update=authuser_id writable=False)

there is nothing special about these fields since they are filled before the record is archived

If you want to change the archive table name and the name of the reference field you can do for example

dbdefine_table(myhistoryField(parent_record dbmytable) dbmytable)

and use it as

form = crudupdate(dbmytable myrecordonaccept=lambda formcrudarchive(form

archive_table=dbrarr˓myhistory

current_record=parent_rarr˓record))

basic(basic_auth_realm=False)Performs basic login

Parameters basic_auth_realm ndash optional basic http authentication realm Can take str orunicode or function or callable or boolean

reads currentrequestenvhttp_authorization and returns basic_allowedbasic_accepteduser

122 Chapter 34 tools Module

web2py Documentation Release 2146-stable

if basic_auth_realm is defined is a callable itrsquos return value is used to set the basic authentication realm ifitrsquos a string its content is used instead Otherwise basic authentication realm is set to the application nameIf basic_auth_realm is None or False (the default) the behavior is to skip sending any challenge

bulk_register(max_emails=100)Creates a form for ther user to send invites to other users to join

cas_login(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt version=2)

cas_validate(version=2 proxy=False)

change_password(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form that lets the user change password

confirm_registration(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form to confirm user registration

default_messages = access_denied Insufficient privileges add_group_log Group (group_id)s created add_membership_log None add_permission_log None bulk_invite_body You have been invited to join (site)s click (link)s to complete the process bulk_invite_subject Invitation to join (site)s change_password_log User (id)s Password changed del_group_log Group (group_id)s deleted del_membership_log None del_permission_log None delete_label Check to delete email_sent Email sent email_taken This email already has an account email_verified Email verified function_disabled Function disabled group_description Group uniquely assigned to user (id)s has_membership_log None has_permission_log None impersonate_log User (id)s is impersonating (other_id)s invalid_email Invalid email invalid_login Invalid login invalid_password Invalid password invalid_reset_password Invalid reset password invalid_two_factor_code Incorrect code 0 more attempt(s) remaining invalid_user Invalid user invalid_username Invalid username is_empty Cannot be empty label_client_ip Client IP label_description Description label_email E-mail label_first_name First name label_group_id Group ID label_last_name Last name label_name Name label_origin Origin label_password Password label_record_id Record ID label_registration_id Registration identifier label_registration_key Registration key label_remember_me Remember me (for 30 days) label_reset_password_key Reset Password key label_role Role label_table_name Object or table name label_time_stamp Timestamp label_two_factor Authentication code label_user_id User ID label_username Username logged_in Logged in logged_out Logged out login_button Log In login_disabled Login disabled by administrator login_failed_log None login_log User (id)s Logged-in logout_log User (id)s Logged-out mismatched_password Password fields dont match new_password New password new_password_sent A new password was emailed to you old_password Old password password_change_button Change password password_changed Password changed password_reset_button Request reset password profile_log User (id)s Profile updated profile_save_button Apply changes profile_updated Profile updated register_button Sign Up register_log User (id)s Registered registration_pending Registration is pending approval registration_successful Registration successful registration_verifying Registration needs verification reset_password Click on the link (link)s to reset your password reset_password_log User (id)s Password reset reset_password_subject Password reset retrieve_password Your password is (password)s retrieve_password_log User (id)s Password retrieved retrieve_password_subject Password retrieve retrieve_two_factor_code Your temporary login code is 0 retrieve_two_factor_code_subject Two-step Login Authentication Code retrieve_username Your username is (username)s retrieve_username_log User (id)s Username retrieved retrieve_username_subject Username retrieve submit_button Submit two_factor_comment This code was emailed to you and is required for login unable_send_email Unable to send email unable_to_send_email Unable to send email username_sent Your username was emailed to you username_taken Username already taken verify_email Welcome (username)s Click on the link (link)s to verify your email verify_email_log User (id)s Verification email sent verify_email_subject Email verification verify_password Verify Password verify_password_comment please input your password againClass for authentication authorization role based access control

Includes

bull registration and profile

bull login and logout

bull username and password retrieval

bull event logging

bull role creation and assignment

bull user defined grouprole based permission

Parameters

bull environment ndash is there for legacy but unused (awful)

bull db ndash has to be the database where to create tables for authentication

bull mailer ndash Mail( ) or None (no mailer) or True (make a mailer)

bull hmac_key ndash can be a hmac_key or hmac_key=Authget_or_create_key()

bull controller ndash (where is the user action)

bull cas_provider ndash (delegate authentication to the URL CAS2)

Authentication Example

from gluoncontributils import mail=Mail()mailsettingsserver=smtpgmailcom587mailsettingssender=yousomewherecommailsettingslogin=usernamepasswordauth=Auth(db)authsettingsmailer=mail authsettings=authdefine_tables()def authentication()

return dict(form=auth())

341 Auth Mail PluginManager and various utilities 123

web2py Documentation Release 2146-stable

Exposes

bull http applicationcontrollerauthenticationlogin

bull http applicationcontrollerauthenticationlogout

bull http applicationcontrollerauthenticationregister

bull http applicationcontrollerauthenticationverify_email

bull http applicationcontrollerauthenticationretrieve_username

bull http applicationcontrollerauthenticationretrieve_password

bull http applicationcontrollerauthenticationreset_password

bull http applicationcontrollerauthenticationprofile

bull http applicationcontrollerauthenticationchange_password

On registration a group with role=new_userid is created and user is given membership of this group

You can create a group with

group_id=authadd_group(Manager can access the manage action)authadd_permission(group_id access to manage)

Here ldquoaccess to managerdquo is just a user defined string You can give access to a user

authadd_membership(group_id user_id)

If user id is omitted the logged in user is assumed

Then you can decorate any action

authrequires_permission(access to manage)def manage()

return dict()

You can restrict a permission to a specific table

authadd_permission(group_id edit dbsometable)authrequires_permission(edit dbsometable)

Or to a specific record

authadd_permission(group_id edit dbsometable 45)authrequires_permission(edit dbsometable 45)

If authorization is not granted calls

authsettingson_failed_authorization

Other options

authsettingsmailer=Noneauthsettingsexpiration=3600 seconds

these are messages that can be customized

124 Chapter 34 tools Module

web2py Documentation Release 2146-stable

default_settings = allow_basic_login False allow_basic_login_only False allow_delete_accounts False alternate_requires_registration False auth_manager_role None auth_two_factor_enabled False auth_two_factor_tries_left 3 bulk_register_enabled False captcha None cas_maps None client_side True create_user_groups user_(id)s email_case_sensitive True everybody_group_id None expiration 3600 formstyle None hideerror False keep_session_onlogin True keep_session_onlogout False label_separator None logging_enabled True login_after_password_change True login_after_registration False login_captcha None login_email_validate True login_userfield None logout_onlogout None long_expiration 2592000 manager_actions multi_login False on_failed_authentication ltfunction ltlambdagt at 0x7fcf0cf9f578gt ondelete CASCADE password_field password password_min_length 4 pre_registration_div None prevent_open_redirect_attacks True prevent_password_reset_attacks True profile_fields None register_captcha None register_fields None register_verify_password True registration_requires_approval False registration_requires_verification False remember_me_form True renew_session_onlogin True renew_session_onlogout True reset_password_requires_verification False retrieve_password_captcha None retrieve_username_captcha None showid False table_cas None table_cas_name auth_cas table_event None table_event_name auth_event table_group None table_group_name auth_group table_membership None table_membership_name auth_membership table_permission None table_permission_name auth_permission table_token_name auth_token table_user None table_user_name auth_user two_factor_authentication_group None update_fields [email] use_username False username_case_sensitive True wiki ltStorage gt

define_signature()

define_tables(username=None signature=None enable_tokens=False migrate=Nonefake_migrate=None)

To be called unless tables are defined manually

Examples

Use as

defines all needed tables and table files myprefix_auth_usertable authdefine_tables(migrate=myprefix_)

defines all needed tables without migrationtable filesauthdefine_tables(migrate=False)

del_group(group_id)Deletes a group

del_membership(group_id=None user_id=None role=None)Revokes membership from group_id to user_id if user_id is None than user_id is that of current logged inuser

del_permission(group_id name=rsquoanyrsquo table_name=rdquo record_id=0)Revokes group_id lsquonamersquo access to lsquotable_namersquo and lsquorecord_idrsquo

email_registration(subject body user)Sends and email invitation to a user informing they have been registered with the application

email_reset_password(user)

enable_record_versioning(tables archive_db=None archive_names=rsquo(tablename)s_archiversquocurrent_record=rsquocurrent_recordrsquo current_record_label=None)

Used to enable full record versioning (including auth tables)

auth = Auth(db)authdefine_tables(signature=True) define our own tablesdbdefine_table(mythingField(name)authsignature)authenable_record_versioning(tables=db)

tables can be the db (all table) or a list of tables only tables with modified_by and modified_on fiels (ascreated by authsignature) will have versioning Old record versions will be in table lsquomything_archiversquoautomatically defined

when you enable enable_record_versioning records are never deleted but marked with is_active=False

enable_record_versioning enables a common_filter for every table that filters out records with is_active =False

Note If you use authenable_record_versioning do not use autharchive or you will end up with dupli-cates autharchive does explicitly what enable_record_versioning does automatically

static get_or_create_key(filename=None alg=rsquosha512rsquo)

341 Auth Mail PluginManager and various utilities 125

web2py Documentation Release 2146-stable

get_or_create_user(keys update_fields=[rsquoemailrsquo] login=True get=True)Used for alternate login methods If the user exists already then password is updated If the user doesnrsquotyet exist then they are created

get_vars_next()

groups()Displays the groups and their roles for the logged in user

has_membership(group_id=None user_id=None role=None)Checks if user is member of group_id or role

has_permission(name=rsquoanyrsquo table_name=rdquo record_id=0 user_id=None group_id=None)Checks if user_id or current logged in user is member of a group that has lsquonamersquo permission on lsquota-ble_namersquo and lsquorecord_idrsquo if group_id is passed it checks whether the group has the permission

here()

id_group(role)Returns the group_id of the group specified by the role

impersonate(user_id=ltfunction ltlambdagtgt)To use this make a POST to http impersonate requestpost_varsuser_id=ltidgt

Set requestpost_varsuser_id to 0 to restore original user

requires impersonator is logged in and

has_permission(impersonate auth_user user_id)

is_impersonating()

is_logged_in()Checks if the user is logged in and returns TrueFalse If so user is in authuser as well as in ses-sionauthuser

jwt()To use JWT authentication 1) instantiate auth with

auth = Auth(db jwt = secret_keysecret)

where lsquosecretrsquo is your own secret string

2 Decorate functions that require login but should accept the JWT token credentials

authallows_jwt()authrequires_login()def myapi() return hello s authuseremail

Notice jwt is allowed but not required if user is logged in myapi is accessible

3 Use it

Now API users can obtain a token with

http appdefaultuserjwtusername= amppassword=

(returns json object with a token attribute) API users can refresh an existing token with

http appdefaultuserjwttoken=

they can authenticate themselves when calling http myapi by injecting a header

Authorization Bearer ltthe jwt tokengt

126 Chapter 34 tools Module

web2py Documentation Release 2146-stable

Any additional attributes in the jwt argument of Auth() below

auth = Auth(db jwt = )

are passed to the constructor of class AuthJWT Look there for documentation

log_event(description vars=None origin=rsquoauthrsquo)

Examples

Use as

authlog_event(description=this happened origin=auth)

login(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a login form

login_bare(username password)Logins user as specified by username (or email) and password

login_user(user)Logins the user = dbauth_user(id)

logout(next=ltfunction ltlambdagtgt onlogout=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)Logouts and redirects to login

logout_bare()

manage_tokens()

navbar(prefix=rsquoWelcomersquo action=None separators=(rsquo [ rsquo rsquo | rsquo rsquo ] rsquo) user_identifier=ltfunctionltlambdagtgt referrer_actions=ltfunction ltlambdagtgt mode=rsquodefaultrsquo)

Navbar with support for more templates This uses some code from the old navbar

Parameters mode ndash see options for list of

not_authorized()You can change the view for this page to make it look as you like

profile(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form that lets the user change hisher profile

random_password()

register(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a registration form

register_bare(fields)Registers a user as specified by username (or email) and a raw password

request_reset_password(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgtonaccept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form to reset the user password

requires(condition requires_login=True otherwise=None)Decorator that prevents access to action if not logged in

requires_login(otherwise=None)Decorator that prevents access to action if not logged in

341 Auth Mail PluginManager and various utilities 127

web2py Documentation Release 2146-stable

requires_login_or_token(otherwise=None)

requires_membership(role=None group_id=None otherwise=None)Decorator that prevents access to action if not logged in or if user logged in is not a member of group_idIf role is provided instead of group_id then the group_id is calculated

requires_permission(name table_name=rdquo record_id=0 otherwise=None)Decorator that prevents access to action if not logged in or if user logged in is not a member of any group(role) that has lsquonamersquo access to lsquotable_namersquo lsquorecord_idrsquo

requires_signature(otherwise=None hash_vars=True)Decorator that prevents access to action if not logged in or if user logged in is not a member of group_idIf role is provided instead of group_id then the group_id is calculated

reset_password(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form to reset the user password

reset_password_deprecated(next=ltfunction ltlambdagtgt onvalidation=ltfunctionltlambdagtgt onaccept=ltfunction ltlambdagtgt log=ltfunctionltlambdagtgt)

Returns a form to reset the user password (deprecated)

retrieve_password(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

retrieve_username(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form to retrieve the user username (only if there is a username field)

run_login_onaccept()

select_host(host host_names=None)checks that host is valid ie in the list of glob host_names if the host is missing then is it selects the firstentry from host_names read more here httpsgithubcomweb2pyweb2pyissues1196

table_cas()

table_event()

table_group()

table_membership()

table_permission()

table_token()

table_user()

update_groups()

url(f=None args=None vars=None scheme=False)

user_group(user_id=None)Returns the group_id of the group uniquely associated to this user ie role=user[user_id]

user_group_role(user_id=None)

user_iduserid or None

verify_email(next=ltfunction ltlambdagtgt onaccept=ltfunction ltlambdagtgt log=ltfunctionltlambdagtgt)

Action used to verify the registration email

128 Chapter 34 tools Module

web2py Documentation Release 2146-stable

when_is_logged_in_bypass_next_in_url(next session)This function should be use when someone want to avoid asking for user credentials when loaded pagecontains ldquouserlogin_next=NEXT_COMPONENTrdquo in the URL is refresh but user is already authenti-cated

wiki(slug=None env=None render=rsquomarkminrsquo manage_permissions=False force_prefix=rdquo re-strict_search=False resolve=True extra=None menu_groups=None templates=None mi-grate=True controller=None function=None force_render=False groups=None)

wikimenu()To be used in menupy for app wide wiki menus

class gluontoolsRecaptcha(request=None public_key=rdquo private_key=rdquo use_ssl=False er-ror=None error_message=rsquoinvalidrsquo label=rsquoVerifyrsquo options=rdquocomment=rdquo ajax=False)

Bases gluonhtmlDIV

Examples

Use as

form = FORM(Recaptcha(public_key= private_key=))

or

form = SQLFORM()formappend(Recaptcha(public_key= private_key=))

API_SERVER = httpwwwgooglecomrecaptchaapi

API_SSL_SERVER = httpswwwgooglecomrecaptchaapi

VERIFY_SERVER = httpwwwgooglecomrecaptchaapiverify

xml()generates the xml for this component

class gluontoolsRecaptcha2(request=None public_key=rdquo private_key=rdquo er-ror_message=rsquoinvalidrsquo label=rsquoVerifyrsquo options=None com-ment=rdquo)

Bases gluonhtmlDIV

Experimental Creates a DIV holding the newer Recaptcha from Google (v2)

Parameters

bull request ndash the request If not passed uses current request

bull public_key ndash the public key Google gave you

bull private_key ndash the private key Google gave you

bull error_message ndash the error message to show if verification fails

bull label ndash the label to use

bull options (dict) ndash takes these parameters

ndash hl

ndash theme

ndash type

341 Auth Mail PluginManager and various utilities 129

web2py Documentation Release 2146-stable

ndash tabindex

ndash callback

ndash expired-callback

see httpsdevelopersgooglecomrecaptchadocsdisplay for docs about those

bull comment ndash the comment

Examples

Use as

form = FORM(Recaptcha2(public_key= private_key=))

or

form = SQLFORM()formappend(Recaptcha2(public_key= private_key=))

to protect the login page instead use

from gluontools import Recaptcha2authsettingscaptcha = Recaptcha2(request public_key= private_key=)

API_URI = httpswwwgooglecomrecaptchaapijs

VERIFY_SERVER = httpswwwgooglecomrecaptchaapisiteverify

xml()generates the xml for this component

class gluontoolsCrud(environment db=None controller=rsquodefaultrsquo)Bases object

static archive(form archive_table=None current_record=rsquocurrent_recordrsquo)

create(table next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt message=ltfunction ltlambdagtgt form-name=ltfunction ltlambdagtgt attributes)

delete(table record_id next=ltfunction ltlambdagtgt message=ltfunction ltlambdagtgt)

get_format(field)

get_query(field op value refsearch=False)

has_permission(name table record=0)

log_event(message vars)

read(table record)

rows(table query=None fields=None orderby=None limitby=None)

search(tables args)Creates a search form and its results for a table rubric Examples

Use as

130 Chapter 34 tools Module

web2py Documentation Release 2146-stable

form results = crudsearch(dbtestqueries = [equals not equal contains]query_labels=equalsEquals

not equalNot equalfields = [idchildren]field_labels =

idIDchildrenChildrenzero=Please choosequery = (dbtestid gt 0)amp(dbtestid = 3) )

select(table query=None fields=None orderby=None limitby=None headers=None attr)

tables()

update(table record next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt ondelete=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgtmessage=ltfunction ltlambdagtgt deletable=ltfunction ltlambdagtgt formname=ltfunctionltlambdagtgt attributes)

url(f=None args=None vars=None)This should point to the controller that exposes download and crud

class gluontoolsService(environment=None)Bases object

exception JsonRpcException(code info)Bases exceptionsException

amfrpc(f)

Example

Use as

service = Service()serviceamfrpcdef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget httpappdefaultcallamfrpcmyfunctiona=helloampb=world

amfrpc3(domain=rsquodefaultrsquo)

Example

Use as

service = Service()serviceamfrpc3(domain)def myfunction(a b)

return a + bdef call()

return service()

341 Auth Mail PluginManager and various utilities 131

web2py Documentation Release 2146-stable

Then call it with

wget http appdefaultcallamfrpc3myfunctiona=helloampb=world

csv(f)

Example

Use as

service = Service()servicecsvdef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget httpappdefaultcallcsvmyfunctiona=3ampb=4

error()

json(f)

Example

Use as

service = Service()servicejsondef myfunction(a b)

return [a b]def call()

return service()

Then call it with

wget http appdefaultcalljsonmyfunctiona=helloampb=world

jsonrpc(f)

Example

Use as

service = Service()servicejsonrpcdef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget http appdefaultcalljsonrpcmyfunctiona=helloampb=world

132 Chapter 34 tools Module

web2py Documentation Release 2146-stable

jsonrpc2(f)

Example

Use as

service = Service()servicejsonrpc2def myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget ndashpost-data lsquoldquojsonrpcrdquo ldquo20rdquo ldquoidrdquo 1 ldquomethodrdquo ldquomyfunctionrdquo ldquoparamsrdquo ldquoardquo 1 ldquobrdquo2rsquo http appdefaultcalljsonrpc2

jsonrpc_errors = -32700 (Parse error Invalid JSON was received by the server An error occurred on the server while parsing the JSON text) -32603 (Internal error Internal JSON-RPC error) -32602 (Invalid params Invalid method parameter(s)) -32601 (Method not found The method does not exist is not available) -32600 (Invalid Request The JSON sent is not a valid Request object) -32099 (Server error Reserved for implementation-defined server-errors)

rss(f)

Example

Use as

service = Service()servicerssdef myfunction()

return dict(title= link= description=created_on= entries=[dict(title= link=

description= created_on=])def call()

return service()

Then call it with

wget http appdefaultcallrssmyfunction

run(f)

Example

Use as

service = Service()servicerundef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget httpappdefaultcallrunmyfunctiona=3ampb=4

341 Auth Mail PluginManager and various utilities 133

web2py Documentation Release 2146-stable

serve_amfrpc(version=0)

serve_csv(args=None)

serve_json(args=None)

serve_jsonrpc()

serve_jsonrpc2(data=None batch_element=False)

serve_rss(args=None)

serve_run(args=None)

serve_soap(version=rsquo11rsquo)

serve_xml(args=None)

serve_xmlrpc()

soap(name=None returns=None args=None doc=None)

Example

Use as

service = Service()servicesoap(MyFunctionreturns=resultintargs=aintbint)def myfunction(a b)

return a + bdef call()

return service()

Then call it with

from gluoncontribpysimplesoapclient import SoapClientclient = SoapClient(wsdl=httpappdefaultcallsoapWSDL)response = clientMyFunction(a=1b=2)return response[result]

It also exposes online generated documentation and xml example messages athttp appdefaultcallsoap

xml(f)

Example

Use as

service = Service()servicexmldef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget httpappdefaultcallxmlmyfunctiona=3ampb=4

134 Chapter 34 tools Module

web2py Documentation Release 2146-stable

xmlrpc(f)

Example

Use as

service = Service()servicexmlrpcdef myfunction(a b)

return a + bdef call()

return service()

The call it with

wget http appdefaultcallxmlrpcmyfunctiona=helloampb=world

class gluontoolsWiki(auth env=None render=rsquomarkminrsquo manage_permissions=Falseforce_prefix=rdquo restrict_search=False extra=None menu_groups=Nonetemplates=None migrate=True controller=None function=Nonegroups=None)

Bases object

automenu()adds the menu if not present

can_edit(page=None)

can_manage()

can_read(page)

can_search()

can_see_menu()

cloud()

static component(text)In wiki docs allows componentcontrollerfunctionargs which renders as a LOAD( ajax=True)

create()

edit(slug from_template=0)

editmedia(slug)

everybody = everybody

first_paragraph(page)

fix_hostname(body)

get_renderer()

html_render(page)

markmin_base(body)

markmin_render(page)

media(id)

menu(controller=rsquodefaultrsquo function=rsquoindexrsquo)

341 Auth Mail PluginManager and various utilities 135

web2py Documentation Release 2146-stable

not_authorized(page=None)

pages()

preview(render)

read(slug force_render=False)

render_tags(tags)

rows_page = 25

search(tags=None query=None cloud=True preview=True limitby=(0 100) orderby=None)

class gluontoolsPluginManager(plugin=None defaults)Bases object

Plugin Manager is similar to a storage object but it is a single level singleton This means that multiple instanceswithin the same thread share the same attributes Its constructor is also special The first argument is the nameof the plugin you are defining The named arguments are parameters needed by the plugin with default valuesIf the parameters were previous defined the old values are used

Example

in some general configuration file

plugins = PluginManager()pluginsmeparam1=3

within the plugin model

_ = PluginManager(meparam1=5param2=6param3=7)

where the plugin is used

gtgtgt print pluginsmeparam13gtgtgt print pluginsmeparam26gtgtgt pluginsmeparam3 = 8gtgtgt print pluginsmeparam38

Here are some tests

gtgtgt a=PluginManager()gtgtgt ax=6gtgtgt b=PluginManager(check)gtgtgt print bx6gtgtgt b=PluginManager() reset settingsgtgtgt print bxltStorage gtgtgtgt bx=7gtgtgt print ax7gtgtgt ayz=8gtgtgt print byz8

(continues on next page)

136 Chapter 34 tools Module

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt test_thread_separation()5gtgtgt plugins=PluginManager(medb=mydb)gtgtgt print pluginsmedbmydbgtgtgt print me in pluginsTruegtgtgt print pluginsmeinstalledTrue

instances =

keys()

gluontoolsfetch(url data=None headers=None cookie= user_agent=rsquoMozilla50rsquo)

gluontoolsgeocode(address)

gluontoolsreverse_geocode(lat lng lang=None)Try to get an approximate address for a given latitude longitude

gluontoolsprettydate(d T=ltfunction ltlambdagtgt utc=False)

341 Auth Mail PluginManager and various utilities 137

web2py Documentation Release 2146-stable

138 Chapter 34 tools Module

CHAPTER 35

utf8 Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)Created by Vladyslav Kozlovskyy (Ukraine) ltdbdevelopcopygmailcomgtfor Web2py project

351 Utilities and class for UTF8 strings managing

class gluonutf8Utf8Bases str

Class for utf8 string storing and manipulations

The base presupposition of this class usage is ldquoALL strings in the application are either of utf-8 or unicodetype even when simple str type is used UTF-8 is only a ldquopackedrdquo version of unicode so Utf-8 and unicodestrings are interchangeablerdquo

CAUTION This class is slower than strunicode Do NOT use it inside intensive loops Simply decode string(s)to unicode before loop and encode it back to utf-8 string(s) after intensive calculation

You can see the benefit of this class in doctests() below

capitalize()rarr stringReturn a copy of the string S with only its first character capitalized

center(width[ fillchar ])rarr stringReturn S centered in a string of length width Padding is done using the specified fill character (default isa space)

count(sub[ start[ end ]])rarr intReturn the number of non-overlapping occurrences of substring sub in string S[startend] Optional argu-ments start and end are interpreted as in slice notation

139

web2py Documentation Release 2146-stable

decode([encoding[ errors]])rarr objectDecodes S using the codec registered for encoding encoding defaults to the default encoding errors maybe given to set a different error handling scheme Default is lsquostrictrsquo meaning that encoding errors raise aUnicodeDecodeError Other possible values are lsquoignorersquo and lsquoreplacersquo as well as any other name registeredwith codecsregister_error that is able to handle UnicodeDecodeErrors

encode([encoding[ errors]])rarr objectEncodes S using the codec registered for encoding encoding defaults to the default encoding errors maybe given to set a different error handling scheme Default is lsquostrictrsquo meaning that encoding errors raise aUnicodeEncodeError Other possible values are lsquoignorersquo lsquoreplacersquo and lsquoxmlcharrefreplacersquo as well as anyother name registered with codecsregister_error that is able to handle UnicodeEncodeErrors

endswith(suffix[ start[ end ]])rarr boolReturn True if S ends with the specified suffix False otherwise With optional start test S beginning atthat position With optional end stop comparing S at that position suffix can also be a tuple of strings totry

expandtabs([tabsize])rarr stringReturn a copy of S where all tab characters are expanded using spaces If tabsize is not given a tab size of8 characters is assumed

find(sub[ start[ end ]])rarr intReturn the lowest index in S where substring sub is found such that sub is contained within S[startend]Optional arguments start and end are interpreted as in slice notation

Return -1 on failure

format(args kwargs)rarr stringReturn a formatted version of S using substitutions from args and kwargs The substitutions are identifiedby braces (lsquolsquo and lsquorsquo)

index(sub[ start[ end ]])rarr intLike Sfind() but raise ValueError when the substring is not found

isalnum()rarr boolReturn True if all characters in S are alphanumeric and there is at least one character in S False otherwise

isalpha()rarr boolReturn True if all characters in S are alphabetic and there is at least one character in S False otherwise

isdigit()rarr boolReturn True if all characters in S are digits and there is at least one character in S False otherwise

islower()rarr boolReturn True if all cased characters in S are lowercase and there is at least one cased character in S Falseotherwise

isspace()rarr boolReturn True if all characters in S are whitespace and there is at least one character in S False otherwise

istitle()rarr boolReturn True if S is a titlecased string and there is at least one character in S ie uppercase characters mayonly follow uncased characters and lowercase characters only cased ones Return False otherwise

isupper()rarr boolReturn True if all cased characters in S are uppercase and there is at least one cased character in S Falseotherwise

join(iterable)rarr stringReturn a string which is the concatenation of the strings in the iterable The separator between elements isS

140 Chapter 35 utf8 Module

web2py Documentation Release 2146-stable

ljust(width[ fillchar ])rarr stringReturn S left-justified in a string of length width Padding is done using the specified fill character (defaultis a space)

lower()rarr stringReturn a copy of the string S converted to lowercase

lstrip([chars])rarr string or unicodeReturn a copy of the string S with leading whitespace removed If chars is given and not None removecharacters in chars instead If chars is unicode S will be converted to unicode before stripping

partition(sep) -gt (head sep tail)Search for the separator sep in S and return the part before it the separator itself and the part after it Ifthe separator is not found return S and two empty strings

replace(old new[ count ])rarr stringReturn a copy of string S with all occurrences of substring old replaced by new If the optional argumentcount is given only the first count occurrences are replaced

rfind(sub[ start[ end ]])rarr intReturn the highest index in S where substring sub is found such that sub is contained within S[startend]Optional arguments start and end are interpreted as in slice notation

Return -1 on failure

rindex(sub[ start[ end ]])rarr intLike Srfind() but raise ValueError when the substring is not found

rjust(width[ fillchar ])rarr stringReturn S right-justified in a string of length width Padding is done using the specified fill character (defaultis a space)

rpartition(sep) -gt (head sep tail)Search for the separator sep in S starting at the end of S and return the part before it the separator itselfand the part after it If the separator is not found return two empty strings and S

rsplit([sep[ maxsplit ]])rarr list of stringsReturn a list of the words in the string S using sep as the delimiter string starting at the end of the stringand working to the front If maxsplit is given at most maxsplit splits are done If sep is not specified or isNone any whitespace string is a separator

rstrip([chars])rarr string or unicodeReturn a copy of the string S with trailing whitespace removed If chars is given and not None removecharacters in chars instead If chars is unicode S will be converted to unicode before stripping

split([sep[ maxsplit ]])rarr list of stringsReturn a list of the words in the string S using sep as the delimiter string If maxsplit is given at mostmaxsplit splits are done If sep is not specified or is None any whitespace string is a separator and emptystrings are removed from the result

splitlines(keepends=False)rarr list of stringsReturn a list of the lines in S breaking at line boundaries Line breaks are not included in the resulting listunless keepends is given and true

startswith(prefix[ start[ end ]])rarr boolReturn True if S starts with the specified prefix False otherwise With optional start test S beginning atthat position With optional end stop comparing S at that position prefix can also be a tuple of strings totry

strip([chars])rarr string or unicodeReturn a copy of the string S with leading and trailing whitespace removed If chars is given and not None

351 Utilities and class for UTF8 strings managing 141

web2py Documentation Release 2146-stable

remove characters in chars instead If chars is unicode S will be converted to unicode before stripping

swapcase()rarr stringReturn a copy of the string S with uppercase characters converted to lowercase and vice versa

title()rarr stringReturn a titlecased version of S ie words start with uppercase characters all remaining cased charactershave lowercase

translate(table[ deletechars])rarr stringReturn a copy of the string S where all characters occurring in the optional argument deletechars areremoved and the remaining characters have been mapped through the given translation table which mustbe a string of length 256 or None If the table argument is None no translation is applied and the operationsimply removes the characters in deletechars

upper()rarr stringReturn a copy of the string S converted to uppercase

zfill(width)rarr stringPad a numeric string S with zeros on the left to fill a field of the specified width The string S is nevertruncated

142 Chapter 35 utf8 Module

CHAPTER 36

utils Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

361 This file specifically includes utilities for security

gluonutilsAES_new(key IV=None)Returns an AES cipher object and random IV if None specified

gluonutilscompare(a b)Compares two strings and not vulnerable to timing attacks

gluonutilsfast_urandom16(urandom=[] locker=lt_RLock owner=None count=0gt)This is 4x faster than calling osurandom(16) and prevents the ldquotoo many files openrdquo issue with concurrent accessto osurandom()

gluonutilsget_callable_argspec(fn)

gluonutilsget_digest(value)Returns a hashlib digest algorithm from a string

gluonutilsgetipaddrinfo(host)Filter out non-IP and bad IP addresses from getaddrinfo

gluonutilsinitialize_urandom()This function and the web2py_uuid follow from the following discussionhttpgroupsgooglecomgroupweb2py-developersbrowse_threadthread7fd5789a7da3f09

At startup web2py compute a unique ID that identifies the machine by adding uuidgetnode() + int(timetime() 1e3)

This is a 48-bit number It converts the number into 16 8-bit tokens It uses this value to initialize the entropysource (lsquodevurandomrsquo) and to seed random

143

web2py Documentation Release 2146-stable

If osrandom() is not supported it falls back to using random and issues a warning

gluonutilsis_loopback_ip_address(ip=None addrinfo=None)Determines whether the address appears to be a loopback address This assumes that the IP is valid

gluonutilsis_valid_ip_address(address)

Examples

Better than a thousand words

gtgtgt is_valid_ip_address(1270)Falsegtgtgt is_valid_ip_address(127001)Truegtgtgt is_valid_ip_address(20016601)True

gluonutilsmd5_hash(text)Generates a md5 hash with the given text

gluonutilspad(s n=32 padchar=rsquo rsquo)

gluonutilspbkdf2_hex(data salt iterations=1000 keylen=24 hashfunc=None)

gluonutilssecure_dumps(data encryption_key hash_key=None compression_level=None)

gluonutilssecure_loads(data encryption_key hash_key=None compression_level=None)

gluonutilssimple_hash(text key=rdquo salt=rdquo digest_alg=rsquomd5rsquo)Generates hash with the given text using the specified digest hashing algorithm

gluonutilsweb2py_uuid(ctokens=(12807810588179607998L 787762416516532974))This function follows from the following discussion httpgroupsgooglecomgroupweb2py-developersbrowse_threadthread7fd5789a7da3f09

It works like uuiduuid4 except that tries to use osurandom() if possible and it XORs the output with the tokensuniquely associated with this machine

144 Chapter 36 utils Module

CHAPTER 37

validators Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)Thanks to ga2arch for help with IS_IN_DB and IS_NOT_IN_DB on GAE

371 Validators

class gluonvalidatorsANY_OF(subs)Bases gluonvalidatorsValidator

Tests if any of the validators in a list returns successfully

gtgtgt ANY_OF([IS_EMAIL()IS_ALPHANUMERIC()])(abco)(abco None)gtgtgt ANY_OF([IS_EMAIL()IS_ALPHANUMERIC()])(abco)(abco None)gtgtgt ANY_OF([IS_EMAIL()IS_ALPHANUMERIC()])(abco)(abco enter only letters numbers and underscore)gtgtgt ANY_OF([IS_ALPHANUMERIC()IS_EMAIL()])(abco)(abco enter a valid email address)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

class gluonvalidatorsCLEANUP(regex=None)Bases gluonvalidatorsValidator

Examples

Use as

145

web2py Documentation Release 2146-stable

INPUT(_type=text _name=name requires=CLEANUP())

removes special characters on validation

REGEX_CLEANUP = lt_sreSRE_Pattern objectgt

class gluonvalidatorsCRYPT(key=None digest_alg=rsquopbkdf2(1000 20 sha512)rsquo min_length=0error_message=rsquoToo shortrsquo salt=True max_length=1024)

Bases object

Examples

Use as

INPUT(_type=text _name=name requires=CRYPT())

encodes the value on validation with a digest

If no arguments are provided CRYPT uses the MD5 algorithm If the key argument is provided the HMAC+MD5algorithm is used If the digest_alg is specified this is used to replace the MD5 with for example SHA512 Thedigest_alg can be the name of a hashlib algorithm as a string or the algorithm itself

min_length is the minimal password length (default 4) - IS_STRONG for serious security error_message is themessage if password is too short

Notice that an empty password is accepted but invalid It will not allow login back Stores junk as hashedpassword

Specify an algorithm or by default we will use sha512

Typical available algorithms md5 sha1 sha224 sha256 sha384 sha512

If salt it hashes a password with a salt If salt is True this method will automatically generate one Either caseit returns an encrypted password string in the following format

ltalgorithmgt$ltsaltgt$lthashgt

Important hashed password is returned as a LazyCrypt object and computed only if needed The LasyCryptobject also knows how to compare itself with an existing salted password

Supports standard algorithms

gtgtgt for alg in (md5sha1sha256sha384sha512) print str(CRYPT(digest_alg=algsalt=True)(test)[0])md5$$sha1$$sha256$$sha384$$sha512$$

The syntax is always alg$salt$hash

Supports for pbkdf2

gtgtgt alg = pbkdf2(100020sha512)gtgtgt print str(CRYPT(digest_alg=algsalt=True)(test)[0])pbkdf2(100020sha512)$$

An optional hmac_key can be specified and it is used as salt prefix

146 Chapter 37 validators Module

web2py Documentation Release 2146-stable

gtgtgt a = str(CRYPT(digest_alg=md5key=mykeysalt=True)(test)[0])gtgtgt print amd5$$

Even if the algorithm changes the hash can still be validated

gtgtgt CRYPT(digest_alg=sha1key=mykeysalt=True)(test)[0] == aTrue

If no salt is specified CRYPT can guess the algorithms from length

gtgtgt a = str(CRYPT(digest_alg=sha1salt=False)(test)[0])gtgtgt asha1$$a94a8fe5ccb19ba61c4c0873d391e987982fbbd3gtgtgt CRYPT(digest_alg=sha1salt=False)(test)[0] == aTruegtgtgt CRYPT(digest_alg=sha1salt=False)(test)[0] == a[6]Truegtgtgt CRYPT(digest_alg=md5salt=False)(test)[0] == aTruegtgtgt CRYPT(digest_alg=md5salt=False)(test)[0] == a[6]True

class gluonvalidatorsIS_ALPHANUMERIC(error_message=rsquoEnter only letters numbers andunderscorersquo)

Bases gluonvalidatorsIS_MATCH

Example

Used as

INPUT(_type=text _name=name requires=IS_ALPHANUMERIC())

gtgtgt IS_ALPHANUMERIC()(1)(1 None)gtgtgt IS_ALPHANUMERIC()()( None)gtgtgt IS_ALPHANUMERIC()(A_a)(A_a None)gtgtgt IS_ALPHANUMERIC()()( enter only letters numbers and underscore)

class gluonvalidatorsIS_DATE_IN_RANGE(minimum=None maximum=None format=rsquoY-m-drsquo error_message=None)

Bases gluonvalidatorsIS_DATE

Examples

Use as

gtgtgt v = IS_DATE_IN_RANGE(minimum=datetimedate(200811)rarr˓ maximum=datetimedate(20091231)rarr˓ format=mdYerror_message=Oops)

(continues on next page)

371 Validators 147

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt v(03032008)(datetimedate(2008 3 3) None)

gtgtgt v(03032010)(03032010 oops)

gtgtgt v(datetimedate(200833))(datetimedate(2008 3 3) None)

gtgtgt v(datetimedate(201033))(datetimedate(2010 3 3) oops)

class gluonvalidatorsIS_DATE(format=rsquoY-m-drsquo error_message=rsquoEnter date as (for-mat)srsquo)

Bases gluonvalidatorsValidator

Examples

Use as

INPUT(_type=text _name=name requires=IS_DATE())

date has to be in the ISO8960 format YYYY-MM-DD

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

class gluonvalidatorsIS_DATETIME_IN_RANGE(minimum=None maximum=Noneformat=rsquoY-m-d HMSrsquo er-ror_message=None timezone=None)

Bases gluonvalidatorsIS_DATETIME

Examples

Use as

gtgtgt v = IS_DATETIME_IN_RANGE( minimum=datetimerarr˓datetime(2008111220) maximum=datetimerarr˓datetime(200912311220) format=mdY HMrarr˓error_message=Oops)gtgtgt v(03032008 1240)(datetimedatetime(2008 3 3 12 40) None)

gtgtgt v(03032010 1034)(03032010 1034 oops)

gtgtgt v(datetimedatetime(20083300))(datetimedatetime(2008 3 3 0 0) None)

gtgtgt v(datetimedatetime(20103300))(datetimedatetime(2010 3 3 0 0) oops)

148 Chapter 37 validators Module

web2py Documentation Release 2146-stable

class gluonvalidatorsIS_DATETIME(format=rsquoY-m-d HMSrsquo er-ror_message=rsquoEnter date and time as (format)srsquotimezone=None)

Bases gluonvalidatorsValidator

Examples

Use as

INPUT(_type=text _name=name requires=IS_DATETIME())

datetime has to be in the ISO8960 format YYYY-MM-DD hhmmss timezome must be None or apytztimezone(ldquoAmericaChicagordquo) object

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

isodatetime = Y-m-d HMS

static nice(format)

class gluonvalidatorsIS_DECIMAL_IN_RANGE(minimum=None maximum=None er-ror_message=None dot=rsquorsquo)

Bases gluonvalidatorsValidator

Determines that the argument is (or can be represented as) a Python Decimal and that it falls within the specifiedinclusive range The comparison is made with Python Decimal arithmetic

The minimum and maximum limits can be None meaning no lower or upper limit respectively

Example

Used as

INPUT(_type=text _name=name requires=IS_DECIMAL_IN_RANGE(0 10))

gtgtgt IS_DECIMAL_IN_RANGE(15)(4)(Decimal(4) None)gtgtgt IS_DECIMAL_IN_RANGE(15)(4)(Decimal(4) None)gtgtgt IS_DECIMAL_IN_RANGE(15)(1)(Decimal(1) None)gtgtgt IS_DECIMAL_IN_RANGE(15)(525)(525 enter a number between 1 and 5)gtgtgt IS_DECIMAL_IN_RANGE(5256)(525)(Decimal(525) None)gtgtgt IS_DECIMAL_IN_RANGE(5256)(525)(Decimal(525) None)gtgtgt IS_DECIMAL_IN_RANGE(15)(60)(60 enter a number between 1 and 5)gtgtgt IS_DECIMAL_IN_RANGE(15)(35)(Decimal(35) None)gtgtgt IS_DECIMAL_IN_RANGE(1555)(35)(Decimal(35) None)gtgtgt IS_DECIMAL_IN_RANGE(1555)(65)(65 enter a number between 15 and 55)

(continues on next page)

371 Validators 149

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_DECIMAL_IN_RANGE(15None)(65)(Decimal(65) None)gtgtgt IS_DECIMAL_IN_RANGE(15None)(05)(05 enter a number greater than or equal to 15)gtgtgt IS_DECIMAL_IN_RANGE(None55)(45)(Decimal(45) None)gtgtgt IS_DECIMAL_IN_RANGE(None55)(65)(65 enter a number less than or equal to 55)gtgtgt IS_DECIMAL_IN_RANGE()(65)(Decimal(65) None)gtgtgt IS_DECIMAL_IN_RANGE(099)(123123)(123123 enter a number between 0 and 99)gtgtgt IS_DECIMAL_IN_RANGE(099)(123123)(123123 enter a number between 0 and 99)gtgtgt IS_DECIMAL_IN_RANGE(099)(1234)(Decimal(1234) None)gtgtgt IS_DECIMAL_IN_RANGE()(abc)(abc enter a number)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

class gluonvalidatorsIS_EMAIL(banned=None forced=None error_message=rsquoEnter a validemail addressrsquo)

Bases gluonvalidatorsValidator

Checks if fieldrsquos value is a valid email address Can be set to disallow or force addresses from certain domain(s)

Email regex adapted from httphaackedcomarchive20070821i-knew-how-to-validate-an-email-address-until-iaspx generally following the RFCs except that we disallow quoted strings and permit underscores and leadingnumerics in subdomain labels

Parameters

bull banned ndash regex text for disallowed address domains

bull forced ndash regex text for required address domains

Both arguments can also be custom objects with a match(value) method

Example

Check for valid email address

INPUT(_type=text _name=namerequires=IS_EMAIL())

Check for valid email address that canrsquot be from a com domain

INPUT(_type=text _name=namerequires=IS_EMAIL(banned=^com(|)$))

Check for valid email address that must be from a edu domain

INPUT(_type=text _name=namerequires=IS_EMAIL(forced=^edu(|)$))

(continues on next page)

150 Chapter 37 validators Module

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_EMAIL()(abcom)(abcom None)gtgtgt IS_EMAIL()(abcdefcom)(abcdefcom None)gtgtgt IS_EMAIL()(abc3defcom)(abc3defcom None)gtgtgt IS_EMAIL()(abcdefus)(abcdefus None)gtgtgt IS_EMAIL()(abcd_-fus)(abcd_-fus None)gtgtgt IS_EMAIL()(defcom) missing name(defcom enter a valid email address)gtgtgt IS_EMAIL()(abcdefcom) quoted name(abcdefcom enter a valid email address)gtgtgt IS_EMAIL()(abc+defcom) no (abc+defcom enter a valid email address)gtgtgt IS_EMAIL()(abcdefx) one-char TLD(abcdefx enter a valid email address)gtgtgt IS_EMAIL()(abcdef12) numeric TLD(abcdef12 enter a valid email address)gtgtgt IS_EMAIL()(abcdefcom) double-dot in domain(abcdefcom enter a valid email address)gtgtgt IS_EMAIL()(abcdefcom) dot starts domain(abcdefcom enter a valid email address)gtgtgt IS_EMAIL()(abcdefc_m) underscore in TLD(abcdefc_m enter a valid email address)gtgtgt IS_EMAIL()(NotAnEmail) missing (NotAnEmail enter a valid email address)gtgtgt IS_EMAIL()(abcNotAnEmail) missing TLD(abcNotAnEmail enter a valid email address)gtgtgt IS_EMAIL()(customerdepartmentexamplecom)(customerdepartmentexamplecom None)gtgtgt IS_EMAIL()($A12345examplecom)($A12345examplecom None)gtgtgt IS_EMAIL()(defxyzabcexamplecom)(defxyzabcexamplecom None)gtgtgt IS_EMAIL()(_YosemiteSamexamplecom)(_YosemiteSamexamplecom None)gtgtgt IS_EMAIL()(~examplecom)(~examplecom None)gtgtgt IS_EMAIL()(woolyexamplecom) dot starts name(woolyexamplecom enter a valid email address)gtgtgt IS_EMAIL()(woolyexamplecom) adjacent dots in name(woolyexamplecom enter a valid email address)gtgtgt IS_EMAIL()(pootietangexamplecom) dot ends name(pootietangexamplecom enter a valid email address)gtgtgt IS_EMAIL()(examplecom) name is bare dot(examplecom enter a valid email address)gtgtgt IS_EMAIL()(ImaFoolexamplecom)(ImaFoolexamplecom None)gtgtgt IS_EMAIL()(Ima Foolexamplecom) space in name(Ima Foolexamplecom enter a valid email address)gtgtgt IS_EMAIL()(localguylocalhost) localhost as domain(localguylocalhost None)

regex = lt_sreSRE_Pattern object at 0x2e0e160gt

371 Validators 151

web2py Documentation Release 2146-stable

regex_proposed_but_failed = lt_sreSRE_Pattern object at 0x2e100d0gt

class gluonvalidatorsIS_LIST_OF_EMAILS(error_message=rsquoInvalid emails srsquo)Bases object

Example

Used as

Field(emailsliststringwidget=SQLFORMwidgetstextwidgetrequires=IS_LIST_OF_EMAILS()represent=lambda vr SPAN([A(x_href=mailto+x)

rarr˓for x in (v or [])]))

formatter(value row=None)

split_emails = lt_sreSRE_Pattern objectgt

class gluonvalidatorsIS_EMPTY_OR(other null=None empty_regex=None)Bases gluonvalidatorsValidator

Dummy class for testing IS_EMPTY_OR

gtgtgt IS_EMPTY_OR(IS_EMAIL())(abcdefcom)(abcdefcom None)gtgtgt IS_EMPTY_OR(IS_EMAIL())( )(None None)gtgtgt IS_EMPTY_OR(IS_EMAIL() null=abc)( )(abc None)gtgtgt IS_EMPTY_OR(IS_EMAIL() null=abc empty_regex=def)(def)(abc None)gtgtgt IS_EMPTY_OR(IS_EMAIL())(abc)(abc enter a valid email address)gtgtgt IS_EMPTY_OR(IS_EMAIL())( abc )(abc enter a valid email address)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

set_self_id(id)

class gluonvalidatorsIS_EXPR(expression error_message=rsquoInvalid expressionrsquo environ-ment=None)

Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=namerequires=IS_EXPR(5 lt int(value) lt 10))

The argument of IS_EXPR must be python condition

152 Chapter 37 validators Module

web2py Documentation Release 2146-stable

gtgtgt IS_EXPR(int(value) lt 2)(1)(1 None)

gtgtgt IS_EXPR(int(value) lt 2)(2)(2 invalid expression)

class gluonvalidatorsIS_FLOAT_IN_RANGE(minimum=None maximum=None er-ror_message=None dot=rsquorsquo)

Bases gluonvalidatorsValidator

Determines that the argument is (or can be represented as) a float and that it falls within the specified inclusiverange The comparison is made with native arithmetic

The minimum and maximum limits can be None meaning no lower or upper limit respectively

Example

Used as

INPUT(_type=text _name=name requires=IS_FLOAT_IN_RANGE(0 10))

gtgtgt IS_FLOAT_IN_RANGE(15)(4)(40 None)gtgtgt IS_FLOAT_IN_RANGE(15)(4)(40 None)gtgtgt IS_FLOAT_IN_RANGE(15)(1)(10 None)gtgtgt IS_FLOAT_IN_RANGE(15)(525)(525 enter a number between 1 and 5)gtgtgt IS_FLOAT_IN_RANGE(15)(60)(60 enter a number between 1 and 5)gtgtgt IS_FLOAT_IN_RANGE(15)(35)(35 None)gtgtgt IS_FLOAT_IN_RANGE(1None)(35)(35 None)gtgtgt IS_FLOAT_IN_RANGE(None5)(35)(35 None)gtgtgt IS_FLOAT_IN_RANGE(1None)(05)(05 enter a number greater than or equal to 1)gtgtgt IS_FLOAT_IN_RANGE(None5)(65)(65 enter a number less than or equal to 5)gtgtgt IS_FLOAT_IN_RANGE()(65)(65 None)gtgtgt IS_FLOAT_IN_RANGE()(abc)(abc enter a number)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

class gluonvalidatorsIS_IMAGE(extensions=(rsquobmprsquo rsquogifrsquo rsquojpegrsquo rsquopngrsquo) maxsize=(1000010000) minsize=(0 0) error_message=rsquoInvalid imagersquo)

Bases gluonvalidatorsValidator

Checks if file uploaded through file input was saved in one of selected image formats and has dimensions (widthand height) within given boundaries

371 Validators 153

web2py Documentation Release 2146-stable

Does not check for maximum file size (use IS_LENGTH for that) Returns validation failure if no data wasuploaded

Supported file formats BMP GIF JPEG PNG

Code parts taken from httpmailpythonorgpipermailpython-list2007-June617126html

Parameters

bull extensions ndash iterable containing allowed lowercase image file extensions

bull extension of uploaded file counts as jpeg) ((jpg) ndash

bull maxsize ndash iterable containing maximum width and height of the image

bull minsize ndash iterable containing minimum width and height of the image

Use (-1 -1) as minsize to pass image size check

Examples

Check if uploaded file is in any of supported image formats

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_IMAGE())

Check if uploaded file is either JPEG or PNG

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_IMAGE(extensions=(lsquojpegrsquo lsquopngrsquo)))

Check if uploaded file is PNG with maximum size of 200x200 pixels

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_IMAGE(extensions=(lsquopngrsquo) maxsize=(200200)))

class gluonvalidatorsIS_IN_DB(dbset field label=None error_message=rsquoValue not indatabasersquo orderby=None groupby=None distinct=Nonecache=None multiple=False zero=rdquo sort=False_and=None left=None delimiter=None auto_add=False)

Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=namerequires=IS_IN_DB(db dbmytablemyfield zero=))

used for reference fields rendered as a dropbox

build_set()

maybe_add(table fieldname value)

options(zero=True)

set_self_id(id)

class gluonvalidatorsIS_IN_SET(theset labels=None error_message=rsquoValue not allowedrsquomultiple=False zero=rdquo sort=False)

Bases gluonvalidatorsValidator

154 Chapter 37 validators Module

web2py Documentation Release 2146-stable

Example

Used as

INPUT(_type=text _name=namerequires=IS_IN_SET([max john]zero=))

The argument of IS_IN_SET must be a list or set

gtgtgt IS_IN_SET([max john])(max)(max None)gtgtgt IS_IN_SET([max john])(massimo)(massimo value not allowed)gtgtgt IS_IN_SET([max john] multiple=True)((max john))((max john) None)gtgtgt IS_IN_SET([max john] multiple=True)((bill john))((bill john) value not allowed)gtgtgt IS_IN_SET((id1id2) [first labelsecond label])(id1) Traditionalrarr˓way(id1 None)gtgtgt IS_IN_SET(id1first label id2second label)(id1)(id1 None)gtgtgt import itertoolsgtgtgt IS_IN_SET(itertoolschain([135][246]))(1)(1 None)gtgtgt IS_IN_SET([(id1first label) (id2second label)])(id1) Redundantrarr˓way(id1 None)

options(zero=True)

class gluonvalidatorsIS_INT_IN_RANGE(minimum=None maximum=None er-ror_message=None)

Bases gluonvalidatorsValidator

Determines that the argument is (or can be represented as) an int and that it falls within the specified range Therange is interpreted in the Pythonic way so the test is min lt= value lt max

The minimum and maximum limits can be None meaning no lower or upper limit respectively

Example

Used as

INPUT(_type=text _name=name requires=IS_INT_IN_RANGE(0 10))

gtgtgt IS_INT_IN_RANGE(15)(4)(4 None)gtgtgt IS_INT_IN_RANGE(15)(4)(4 None)gtgtgt IS_INT_IN_RANGE(15)(1)(1 None)gtgtgt IS_INT_IN_RANGE(15)(5)(5 enter an integer between 1 and 4)gtgtgt IS_INT_IN_RANGE(15)(5)(5 enter an integer between 1 and 4)gtgtgt IS_INT_IN_RANGE(15)(35)

(continues on next page)

371 Validators 155

web2py Documentation Release 2146-stable

(continued from previous page)

(35 enter an integer between 1 and 4)gtgtgt IS_INT_IN_RANGE(None5)(4)(4 None)gtgtgt IS_INT_IN_RANGE(None5)(6)(6 enter an integer less than or equal to 4)gtgtgt IS_INT_IN_RANGE(1None)(4)(4 None)gtgtgt IS_INT_IN_RANGE(1None)(0)(0 enter an integer greater than or equal to 1)gtgtgt IS_INT_IN_RANGE()(6)(6 None)gtgtgt IS_INT_IN_RANGE()(abc)(abc enter an integer)

class gluonvalidatorsIS_IPV4(minip=rsquo0000rsquo maxip=rsquo255255255255rsquo invert=Falseis_localhost=None is_private=None is_automatic=Noneerror_message=rsquoEnter valid IPv4 addressrsquo)

Bases gluonvalidatorsValidator

Checks if fieldrsquos value is an IP version 4 address in decimal form Can be set to force addresses from certainrange

IPv4 regex taken from httpregexlibcomREDetailsaspxregexp_id=1411

Parameters

bull minip ndash lowest allowed address accepts

ndash str eg 19216801

ndash list or tuple of octets eg [192 168 0 1]

bull maxip ndash highest allowed address same as above

bull invert ndash True to allow addresses only from outside of given range note that range bound-aries are not matched this way

bull is_localhost ndash localhost address treatment

ndash None (default) indifferent

ndash True (enforce) query address must match localhost address (127001)

ndash False (forbid) query address must not match localhost address

bull is_private ndash same as above except that query address is checked against two addressranges 1721600 - 17231255255 and 19216800 - 192168255255

bull is_automatic ndash same as above except that query address is checked against one addressrange 16925400 - 169254255255

Minip and maxip may also be lists or tuples of addresses in all above forms (str int list tuple) allowing setupof multiple address ranges

minip = (minip1 minip2 minipN)| | || | |

maxip = (maxip1 maxip2 maxipN)

Longer iterable will be truncated to match length of shorter one

156 Chapter 37 validators Module

web2py Documentation Release 2146-stable

Examples

Check for valid IPv4 address

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV4())

Check for valid IPv4 address belonging to specific range

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV4(minip=lsquo10020000rsquomaxip=lsquo100200255255rsquo))

Check for valid IPv4 address belonging to either 10011000 - 100110255255 or 2005000 - 200500255address range

INPUT(_type=rsquotextrsquo _name=rsquonamersquo

requires=IS_IPV4(minip=(lsquo10011000rsquo lsquo2005000rsquo) maxip=(lsquo100110255255rsquolsquo200500255rsquo)))

Check for valid IPv4 address belonging to private address space

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV4(is_private=True))

Check for valid IPv4 address that is not a localhost address

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV4(is_localhost=False))

gtgtgt IS_IPV4()(1234)(1234 None)gtgtgt IS_IPV4()(255255255255)(255255255255 None)gtgtgt IS_IPV4()(1234 )(1234 enter valid IPv4 address)gtgtgt IS_IPV4()(12345)(12345 enter valid IPv4 address)gtgtgt IS_IPV4()(123123)(123123 enter valid IPv4 address)gtgtgt IS_IPV4()(1111234)(1111234 enter valid IPv4 address)gtgtgt IS_IPV4()(0111234)(0111234 enter valid IPv4 address)gtgtgt IS_IPV4()(256234)(256234 enter valid IPv4 address)gtgtgt IS_IPV4()(300234)(300234 enter valid IPv4 address)gtgtgt IS_IPV4(minip=1234 maxip=1234)(1234)(1234 None)gtgtgt IS_IPV4(minip=1235 maxip=1239 error_message=Bad ip)(1rarr˓234)(1234 bad ip)gtgtgt IS_IPV4(maxip=1234 invert=True)(127001)(127001 None)gtgtgt IS_IPV4(maxip=1234 invert=True)(1234)(1234 enter valid IPv4 address)gtgtgt IS_IPV4(is_localhost=True)(127001)(127001 None)gtgtgt IS_IPV4(is_localhost=True)(1234)(1234 enter valid IPv4 address)gtgtgt IS_IPV4(is_localhost=False)(127001)(127001 enter valid IPv4 address)

(continues on next page)

371 Validators 157

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_IPV4(maxip=100000 is_localhost=True)(127001)(127001 enter valid IPv4 address)

automatic = (2851995648L 2852061183L)

localhost = 2130706433

numbers = (16777216 65536 256 1)

private = ((2886729728L 2886795263L) (3232235520L 3232301055L))

regex = lt_sreSRE_Pattern object at 0x2e26320gt

class gluonvalidatorsIS_IPV6(is_private=None is_link_local=None is_reserved=Noneis_multicast=None is_routeable=None is_6to4=Noneis_teredo=None subnets=None error_message=rsquoEnter validIPv6 addressrsquo)

Bases gluonvalidatorsValidator

Checks if fieldrsquos value is an IP version 6 address First attempts to use the ipaddress library and falls back tocontribipaddrpy from Google (httpscodegooglecompipaddr-py)

Parameters

bull is_private ndash None (default) indifferent True (enforce) address must be in fc007range False (forbid) address must NOT be in fc007 range

bull is_link_local ndash Same as above but uses fe8010 range

bull is_reserved ndash Same as above but uses IETF reserved range

bull is_mulicast ndash Same as above but uses ff008 range

bull is_routeable ndash Similar to above but enforces not private link_local reserved or multi-cast

bull is_6to4 ndash Same as above but uses 200216 range

bull is_teredo ndash Same as above but uses 200132 range

bull subnets ndash value must be a member of at least one from list of subnets

Examples

Check for valid IPv6 address

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV6())

Check for valid IPv6 address is a link_local address

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV6(is_link_local=True))

Check for valid IPv6 address that is Internet routeable

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV6(is_routeable=True))

Check for valid IPv6 address in specified subnet

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV6(subnets=[lsquo200132rsquo])

158 Chapter 37 validators Module

web2py Documentation Release 2146-stable

gtgtgt IS_IPV6()(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPV6()(19216811)(19216811 enter valid IPv6 address)gtgtgt IS_IPV6(error_message=Bad ip)(19216811)(19216811 bad ip)gtgtgt IS_IPV6(is_link_local=True)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPV6(is_link_local=False)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(is_link_local=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(is_multicast=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(is_multicast=True)(ff00126c8ffafe22b3af)(ff00126c8ffafe22b3af None)gtgtgt IS_IPV6(is_routeable=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af None)gtgtgt IS_IPV6(is_routeable=True)(ff00126c8ffafe22b3af)(ff00126c8ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(subnets=200132)(20018ffafe22b3af)(20018ffafe22b3af None)gtgtgt IS_IPV6(subnets=fb008)(20018ffafe22b3af)(20018ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(subnets=[fc008200132])(20018ffafe22b3af)(20018ffafe22b3af None)gtgtgt IS_IPV6(subnets=invalidsubnet)(20018ffafe22b3af)(20018ffafe22b3af invalid subnet provided)

class gluonvalidatorsIS_IPADDRESS(minip=rsquo0000rsquo maxip=rsquo255255255255rsquo in-vert=False is_localhost=None is_private=Noneis_automatic=None is_ipv4=None is_link_local=Noneis_reserved=None is_multicast=Noneis_routeable=None is_6to4=None is_teredo=Nonesubnets=None is_ipv6=None error_message=rsquoEntervalid IP addressrsquo)

Bases gluonvalidatorsValidator

Checks if fieldrsquos value is an IP Address (v4 or v6) Can be set to force addresses from within a specific rangeChecks are done with the correct IS_IPV4 and IS_IPV6 validators

Uses ipaddress library if found falls back to PEP-3144 ipaddrpy from Google (in contrib)

Parameters

bull minip ndash lowest allowed address accepts str eg 19216801 list or tuple of octets eg[192 168 0 1]

bull maxip ndash highest allowed address same as above

bull invert ndash True to allow addresses only from outside of given range note that range bound-aries are not matched this way

IPv4 specific arguments

bull is_localhost localhost address treatment

ndash None (default) indifferent

ndash True (enforce) query address must match localhost address (127001)

371 Validators 159

web2py Documentation Release 2146-stable

ndash False (forbid) query address must not match localhost address

bull is_private same as above except that query address is checked against two address ranges 1721600 -17231255255 and 19216800 - 192168255255

bull is_automatic same as above except that query address is checked against one address range 16925400- 169254255255

bull is_ipv4 either

ndash None (default) indifferent

ndash True (enforce) must be an IPv4 address

ndash False (forbid) must NOT be an IPv4 address

IPv6 specific arguments

bull is_link_local Same as above but uses fe8010 range

bull is_reserved Same as above but uses IETF reserved range

bull is_mulicast Same as above but uses ff008 range

bull is_routeable Similar to above but enforces not private link_local reserved or multicast

bull is_6to4 Same as above but uses 200216 range

bull is_teredo Same as above but uses 200132 range

bull subnets value must be a member of at least one from list of subnets

bull is_ipv6 either

ndash None (default) indifferent

ndash True (enforce) must be an IPv6 address

ndash False (forbid) must NOT be an IPv6 address

Minip and maxip may also be lists or tuples of addresses in all above forms (str int list tuple) allowing setupof multiple address ranges

minip = (minip1 minip2 minipN)| | || | |

maxip = (maxip1 maxip2 maxipN)

Longer iterable will be truncated to match length of shorter one

gtgtgt IS_IPADDRESS()(19216815)(19216815 None)gtgtgt IS_IPADDRESS(is_ipv6=False)(19216815)(19216815 None)gtgtgt IS_IPADDRESS()(255255255255)(255255255255 None)gtgtgt IS_IPADDRESS()(19216815 )(19216815 enter valid IP address)gtgtgt IS_IPADDRESS()(192168115)(192168115 enter valid IP address)gtgtgt IS_IPADDRESS()(123123)(123123 enter valid IP address)gtgtgt IS_IPADDRESS()(1111234)(1111234 enter valid IP address)gtgtgt IS_IPADDRESS()(0111234)

(continues on next page)

160 Chapter 37 validators Module

web2py Documentation Release 2146-stable

(continued from previous page)

(0111234 enter valid IP address)gtgtgt IS_IPADDRESS()(256234)(256234 enter valid IP address)gtgtgt IS_IPADDRESS()(300234)(300234 enter valid IP address)gtgtgt IS_IPADDRESS(minip=19216810 maxip=1921681255)(1921681100)(1921681100 None)gtgtgt IS_IPADDRESS(minip=1235 maxip=1239 error_message=Bad ip)(123rarr˓4)(1234 bad ip)gtgtgt IS_IPADDRESS(maxip=1234 invert=True)(127001)(127001 None)gtgtgt IS_IPADDRESS(maxip=19216814 invert=True)(19216814)(19216814 enter valid IP address)gtgtgt IS_IPADDRESS(is_localhost=True)(127001)(127001 None)gtgtgt IS_IPADDRESS(is_localhost=True)(192168110)(192168110 enter valid IP address)gtgtgt IS_IPADDRESS(is_localhost=False)(127001)(127001 enter valid IP address)gtgtgt IS_IPADDRESS(maxip=100000 is_localhost=True)(127001)(127001 enter valid IP address)

gtgtgt IS_IPADDRESS()(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPADDRESS(is_ipv4=False)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPADDRESS()(fe80126c8ffafe22b3af )(fe80126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_ipv4=True)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_ipv6=True)(19216811)(19216811 enter valid IP address)gtgtgt IS_IPADDRESS(is_ipv6=True error_message=Bad ip)(19216811)(19216811 bad ip)gtgtgt IS_IPADDRESS(is_link_local=True)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPADDRESS(is_link_local=False)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_link_local=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_multicast=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_multicast=True)(ff00126c8ffafe22b3af)(ff00126c8ffafe22b3af None)gtgtgt IS_IPADDRESS(is_routeable=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af None)gtgtgt IS_IPADDRESS(is_routeable=True)(ff00126c8ffafe22b3af)(ff00126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(subnets=200132)(20018ffafe22b3af)(20018ffafe22b3af None)gtgtgt IS_IPADDRESS(subnets=fb008)(20018ffafe22b3af)(20018ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(subnets=[fc008200132])(20018ffafe22b3af)(20018ffafe22b3af None)gtgtgt IS_IPADDRESS(subnets=invalidsubnet)(20018ffafe22b3af)(20018ffafe22b3af invalid subnet provided)

371 Validators 161

web2py Documentation Release 2146-stable

class gluonvalidatorsIS_LENGTH(maxsize=255 minsize=0 error_message=rsquoEnter from(min)g to (max)g charactersrsquo)

Bases gluonvalidatorsValidator

Checks if length of fieldrsquos value fits between given boundaries Works for both text and file inputs

Parameters

bull maxsize ndash maximum allowed length size

bull minsize ndash minimum allowed length size

Examples

Check if text string is shorter than 33 characters

INPUT(_type=text _name=name requires=IS_LENGTH(32))

Check if password string is longer than 5 characters

INPUT(_type=password _name=name requires=IS_LENGTH(minsize=6))

Check if uploaded file has size between 1KB and 1MB

INPUT(_type=file _name=name requires=IS_LENGTH(1048576 1024))

Other examples

gtgtgt IS_LENGTH()()( None)gtgtgt IS_LENGTH()(1234567890)(1234567890 None)gtgtgt IS_LENGTH(maxsize=5 minsize=0)(1234567890) too long(1234567890 enter from 0 to 5 characters)gtgtgt IS_LENGTH(maxsize=50 minsize=20)(1234567890) too short(1234567890 enter from 20 to 50 characters)

class gluonvalidatorsIS_LIST_OF(other=None minimum=0 maximum=100 er-ror_message=None)

Bases gluonvalidatorsValidator

class gluonvalidatorsIS_LOWERBases gluonvalidatorsValidator

Converts to lower case

gtgtgt IS_LOWER()(ABC)(abc None)gtgtgt IS_LOWER()(Ntilde)(xc3xb1 None)

class gluonvalidatorsIS_MATCH(expression error_message=rsquoInvalid expressionrsquo strict=Falsesearch=False extract=False is_unicode=False)

Bases gluonvalidatorsValidator

Example

Used as

162 Chapter 37 validators Module

web2py Documentation Release 2146-stable

INPUT(_type=text _name=name requires=IS_MATCH(+))

The argument of IS_MATCH is a regular expression

gtgtgt IS_MATCH(+)(hello)(hello None)

gtgtgt IS_MATCH(hell)(hello)(hello None)

gtgtgt IS_MATCH(hell strict=False)(hello)(hello None)

gtgtgt IS_MATCH(hello)(shello)(shello invalid expression)

gtgtgt IS_MATCH(hello search=True)(shello)(shello None)

gtgtgt IS_MATCH(hello search=True strict=False)(shellox)(shellox None)

gtgtgt IS_MATCH(hello search=True strict=False)(shellox)(shellox None)

gtgtgt IS_MATCH(+)()( invalid expression)

class gluonvalidatorsIS_EQUAL_TO(expression error_message=rsquoNo matchrsquo)Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=password)INPUT(_type=text _name=password2

requires=IS_EQUAL_TO(requestvarspassword))

The argument of IS_EQUAL_TO is a string

gtgtgt IS_EQUAL_TO(aaa)(aaa)(aaa None)

gtgtgt IS_EQUAL_TO(aaa)(aab)(aab no match)

class gluonvalidatorsIS_NOT_EMPTY(error_message=rsquoEnter a valuersquo empty_regex=None)Bases gluonvalidatorsValidator

Example

Used as

371 Validators 163

web2py Documentation Release 2146-stable

INPUT(_type=text _name=name requires=IS_NOT_EMPTY())

gtgtgt IS_NOT_EMPTY()(1)(1 None)gtgtgt IS_NOT_EMPTY()(0)(0 None)gtgtgt IS_NOT_EMPTY()(x)(x None)gtgtgt IS_NOT_EMPTY()( x )(x None)gtgtgt IS_NOT_EMPTY()(None)(None enter a value)gtgtgt IS_NOT_EMPTY()()( enter a value)gtgtgt IS_NOT_EMPTY()( )( enter a value)gtgtgt IS_NOT_EMPTY()( nt)( enter a value)gtgtgt IS_NOT_EMPTY()([])([] enter a value)gtgtgt IS_NOT_EMPTY(empty_regex=def)(def)( enter a value)gtgtgt IS_NOT_EMPTY(empty_regex=de[fg])(deg)( enter a value)gtgtgt IS_NOT_EMPTY(empty_regex=def)(abc)(abc None)

class gluonvalidatorsIS_NOT_IN_DB(dbset field error_message=rsquoValue already indatabase or emptyrsquo allowed_override=[] ig-nore_common_filters=False)

Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=name requires=IS_NOT_IN_DB(db dbtable))

makes the field unique

set_self_id(id)

gluonvalidatorsIS_NULL_ORalias of gluonvalidatorsIS_EMPTY_OR

class gluonvalidatorsIS_SLUG(maxlen=80 check=False error_message=rsquoMust be slugrsquokeep_underscores=False)

Bases gluonvalidatorsValidator

converts arbitrary text string to a slug

gtgtgt IS_SLUG()(abc123)(abc123 None)gtgtgt IS_SLUG()(ABC123)(abc123 None)gtgtgt IS_SLUG()(abc-123)(abc-123 None)

(continues on next page)

164 Chapter 37 validators Module

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_SLUG()(abc--123)(abc-123 None)gtgtgt IS_SLUG()(abc 123)(abc-123 None)gtgtgt IS_SLUG()(abc _123)(abc-123 None)gtgtgt IS_SLUG()(-abc-)(abc None)gtgtgt IS_SLUG()(--a--b--_ -c--)(a-b-c None)gtgtgt IS_SLUG()(abcampamp123)(abc123 None)gtgtgt IS_SLUG()(abcampamp123ampampdef)(abc123def None)gtgtgt IS_SLUG()(ntilde)(n None)gtgtgt IS_SLUG(maxlen=4)(abc123)(abc1 None)gtgtgt IS_SLUG()(abc_123)(abc-123 None)gtgtgt IS_SLUG(keep_underscores=False)(abc_123)(abc-123 None)gtgtgt IS_SLUG(keep_underscores=True)(abc_123)(abc_123 None)gtgtgt IS_SLUG(check=False)(abc)(abc None)gtgtgt IS_SLUG(check=True)(abc)(abc None)gtgtgt IS_SLUG(check=False)(a bc)(a-bc None)gtgtgt IS_SLUG(check=True)(a bc)(a bc must be slug)

static urlify(value maxlen=80 keep_underscores=False)

class gluonvalidatorsIS_STRONG(min=None max=None upper=None lower=Nonenumber=None entropy=None special=Nonespecials=rsquo~$^amp()_+-=ltgt []|rsquo invalid=rsquorsquo error_message=None es=False)

Bases object

Examples

Use as

INPUT(_type=password _name=passwdrequires=IS_STRONG(min=10 special=2 upper=2))

enforces complexity requirements on a field

gtgtgt IS_STRONG(es=True)(Abcd1234)(Abcd1234Must include at least 1 of the following ~$^amp()_+-=ltgt[]|)gtgtgt IS_STRONG(es=True)(Abcd1234)(Abcd1234 None)

(continues on next page)

371 Validators 165

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_STRONG(es=True entropy=1)(a)(a None)gtgtgt IS_STRONG(es=True entropy=1 min=2)(a)(a Minimum length is 2)gtgtgt IS_STRONG(es=True entropy=100)(abc123)(abc123 Entropy (3235) less than required (100))gtgtgt IS_STRONG(es=True entropy=100)(and)(and Entropy (1457) less than required (100))gtgtgt IS_STRONG(es=True entropy=100)(aaa)(aaa Entropy (1442) less than required (100))gtgtgt IS_STRONG(es=True entropy=100)(a1d)(a1d Entropy (1597) less than required (100))gtgtgt IS_STRONG(es=True entropy=100)(antilded)(axc3xb1d Entropy (1813) less than required (100))

class gluonvalidatorsIS_TIME(error_message=rsquoEnter time as hhmmss (seconds am pm op-tional)rsquo)

Bases gluonvalidatorsValidator

Example

Use as

INPUT(_type=text _name=name requires=IS_TIME())

understands the following formats hhmmss [ampm] hhmm [ampm] hh [ampm]

[ampm] is optional lsquorsquo can be replaced by any other non-space non-digit

gtgtgt IS_TIME()(2130)(datetimetime(21 30) None)gtgtgt IS_TIME()(21-30)(datetimetime(21 30) None)gtgtgt IS_TIME()(2130)(datetimetime(21 30) None)gtgtgt IS_TIME()(213059)(datetimetime(21 30 59) None)gtgtgt IS_TIME()(530)(datetimetime(5 30) None)gtgtgt IS_TIME()(530 am)(datetimetime(5 30) None)gtgtgt IS_TIME()(530 pm)(datetimetime(17 30) None)gtgtgt IS_TIME()(530 whatever)(530 whatever enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()(530 20)(530 20 enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()(2430)(2430 enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()(2160)(2160 enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()(2130)(2130 enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()()( enter time as hhmmss (seconds am pm optional))ugrave

166 Chapter 37 validators Module

web2py Documentation Release 2146-stable

class gluonvalidatorsIS_UPLOAD_FILENAME(filename=None extension=None lastdot=Truecase=1 error_message=rsquoEnter valid filenamersquo)

Bases gluonvalidatorsValidator

Checks if name and extension of file uploaded through file input matches given criteria

Does not ensure the file type in any way Returns validation failure if no data was uploaded

Parameters

bull filename ndash filename (before dot) regex

bull extension ndash extension (after dot) regex

bull lastdot ndash which dot should be used as a filename extension separator True means lastdot eg filepng -gt file png False means first dot eg filetargz -gt file targz

bull case ndash 0 - keep the case 1 - transform the string into lowercase (default) 2 - transform thestring into uppercase

If there is no dot present extension checks will be done against empty string and filename checks against wholevalue

Examples

Check if file has a pdf extension (case insensitive)

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_UPLOAD_FILENAME(extension=rsquopdfrsquo))

Check if file has a targz extension and name starting with backup

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_UPLOAD_FILENAME(filename=rsquobackuprsquo exten-sion=rsquotargzrsquo lastdot=False))

Check if file has no extension and name matching README (case sensitive)

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_UPLOAD_FILENAME(filename=rsquo^README$rsquoextension=rsquo^$rsquo case=0)

class gluonvalidatorsIS_UPPERBases gluonvalidatorsValidator

Converts to upper case

gtgtgt IS_UPPER()(abc)(ABC None)gtgtgt IS_UPPER()(ntilde)(xc3x91 None)

class gluonvalidatorsIS_URL(error_message=rsquoEnter a valid URLrsquo mode=rsquohttprsquo al-lowed_schemes=None prepend_scheme=rsquohttprsquo al-lowed_tlds=None)

Bases gluonvalidatorsValidator

Rejects a URL string if any of the following is true

bull The string is empty or None

bull The string uses characters that are not allowed in a URL

bull The string breaks any of the HTTP syntactic rules

bull The URL scheme specified (if one is specified) is not lsquohttprsquo or lsquohttpsrsquo

371 Validators 167

web2py Documentation Release 2146-stable

bull The top-level domain (if a host name is specified) does not exist

(These rules are based on RFC 2616 httpwwwfaqsorgrfcsrfc2616html)

This function only checks the URLrsquos syntax It does not check that the URL points to a real document forexample or that it otherwise makes sense semantically This function does automatically prepend lsquohttprsquo infront of a URL in the case of an abbreviated URL (eg lsquogooglecarsquo)

If the parameter mode=rsquogenericrsquo is used then this functionrsquos behavior changes It then rejects a URL string ifany of the following is true

bull The string is empty or None

bull The string uses characters that are not allowed in a URL

bull The URL scheme specified (if one is specified) is not valid

(These rules are based on RFC 2396 httpwwwfaqsorgrfcsrfc2396html)

The list of allowed schemes is customizable with the allowed_schemes parameter If you exclude None fromthe list then abbreviated URLs (lacking a scheme such as lsquohttprsquo) will be rejected

The default prepended scheme is customizable with the prepend_scheme parameter If you set prepend_schemeto None then prepending will be disabled URLs that require prepending to parse will still be accepted but thereturn value will not be modified

IS_URL is compatible with the Internationalized Domain Name (IDN) standard specified in RFC 3490 (httptoolsietforghtmlrfc3490) As a result URLs can be regular strings or unicode strings If the URLrsquos domaincomponent (eg googleca) contains non-US-ASCII letters then the domain will be converted into Punycode(defined in RFC 3492 httptoolsietforghtmlrfc3492) IS_URL goes a bit beyond the standards and allowsnon-US-ASCII characters to be present in the path and query components of the URL as well These non-US-ASCII characters will be escaped using the standard lsquo20rsquo type syntax eg the unicode character with hexcode 0x4e86 will become lsquo4e86rsquo

Parameters

bull error_message ndash a string the error message to give the end user if the URL does notvalidate

bull allowed_schemes ndash a list containing strings or None Each element is a scheme theinputed URL is allowed to use

bull prepend_scheme ndash a string this scheme is prepended if itrsquos necessary to make the URLvalid

Code Examples

INPUT(_type=text _name=name requires=IS_URL())gtgtgt IS_URL()(abccom)(httpabccom None)

INPUT(_type=text _name=name requires=IS_URL(mode=generic))gtgtgt IS_URL(mode=generic)(abccom)(abccom None)

INPUT(_type=text _name=namerequires=IS_URL(allowed_schemes=[https] prepend_scheme=https))

gtgtgt IS_URL(allowed_schemes=[https] prepend_scheme=https)(httpsabccom)(httpsabccom None)

INPUT(_type=text _name=namerequires=IS_URL(prepend_scheme=https))

(continues on next page)

168 Chapter 37 validators Module

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_URL(prepend_scheme=https)(abccom)(httpsabccom None)

INPUT(_type=text _name=namerequires=IS_URL(mode=generic allowed_schemes=[ftps https]

prepend_scheme=https))gtgtgt IS_URL(mode=generic allowed_schemes=[ftps https] prepend_scheme=rarr˓https)(httpsabccom)(httpsabccom None)gtgtgt IS_URL(mode=generic allowed_schemes=[ftps https None] prepend_rarr˓scheme=https)(abccom)(abccom None)

author Jonathan Benn

class gluonvalidatorsIS_JSON(error_message=rsquoInvalid jsonrsquo native_json=False)Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=namerequires=IS_JSON(error_message=This is not a valid json input)

gtgtgt IS_JSON()(a 100)(ua 100 None)

gtgtgt IS_JSON()(spam1234)(spam1234 invalid json)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

371 Validators 169

web2py Documentation Release 2146-stable

170 Chapter 37 validators Module

CHAPTER 38

widget Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

381 The widget is called from web2py

class gluonwidgetIOBases object

write(data)

gluonwidgetcheck_existent_app(options appname)

gluonwidgetconsole()Defines the behavior of the console web2py execution

gluonwidgetget_code_for_scheduler(app options)

gluonwidgetget_url(host path=rsquorsquo proto=rsquohttprsquo port=80)

gluonwidgetrun_system_tests(options)Runs unittests for gluontests

gluonwidgetstart(cron=True)Starts server

gluonwidgetstart_browser(url startup=False)

gluonwidgetstart_schedulers(options)

class gluonwidgetweb2pyDialog(root options)Bases object

Main window dialog

171

web2py Documentation Release 2146-stable

checkTaskBar()Checks taskbar status

connect_pages()Connects pages

error(message)Shows error message

quit(justHide=False)Finishes the program execution

server_ready()

start()Starts web2py server

start_schedulers(app)

stop()Stops web2py server

try_start_scheduler(app)

try_stop_scheduler(app)

update(text)Updates app text

update_canvas()Updates canvas

update_schedulers(start=False)

172 Chapter 38 widget Module

CHAPTER 39

xmlrpc Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

gluonxmlrpchandler(request response methods)

173

web2py Documentation Release 2146-stable

174 Chapter 39 xmlrpc Module

CHAPTER 40

Indices and tables

bull genindex

bull modindex

bull search

175

web2py Documentation Release 2146-stable

176 Chapter 40 Indices and tables

Python Module Index

ggluonadmin 3gluoncache 7gluoncfs 9gluoncompileapp 11gluoncontenttype 15gluoncustom_import 17gluondal 19gluondebug 21gluondecoder 23gluonfileutils 25gluonglobals 27gluonhighlight 33gluonhtml 35gluonhttp 51gluonlanguages 53gluonmain 57gluonmessageboxhandler 59gluonmyregex 61gluonnewcron 63gluonportalocker 65gluonrecfile 67gluonrestricted 69gluonrewrite 71gluonsanitizer 75gluonscheduler 77gluonserializers 83gluonsettings 85gluonshell 87gluonsql 89gluonsqlhtml 97gluonstorage 107gluonstreamer 111gluontemplate 113gluontools 117gluonutf8 139gluonutils 143gluonvalidators 145gluonwidget 171

gluonxmlrpc 173

177

web2py Documentation Release 2146-stable

178 Python Module Index

Index

AA (class in gluonhtml) 35absolute_path_link() (in module gluonnewcron) 63abspath() (in module gluonfileutils) 25accepts() (gluonhtmlFORM method) 41accepts() (gluonsqlhtmlSQLFORM method) 101accessible_query() (gluontoolsAuth method) 121acf() (gluonrewriteMapUrlOut method) 72acquire() (gluonnewcronToken method) 63action() (gluoncacheCache method) 7add_button() (gluonhtmlFORM method) 41add_class() (in module gluonsqlhtml) 104add_deps() (gluonschedulerJobGraph method) 77add_group() (gluontoolsAuth method) 121add_membership() (gluontoolsAuth method) 121add_path_first() (in module gluonadmin) 3add_permission() (gluontoolsAuth method) 122adj_hibernation() (gluonschedulerScheduler method)

79AES_new() (in module gluonutils) 143allows_jwt() (gluontoolsAuth method) 122amfrpc() (gluontoolsService method) 131amfrpc3() (gluontoolsService method) 131ANY_OF (class in gluonvalidators) 145apath() (in module gluonadmin) 3API_SERVER (gluontoolsRecaptcha attribute) 129API_SSL_SERVER (gluontoolsRecaptcha attribute)

129API_URI (gluontoolsRecaptcha2 attribute) 130app_cleanup() (in module gluonadmin) 3app_compile() (in module gluonadmin) 3app_create() (in module gluonadmin) 4app_install() (in module gluonadmin) 4app_pack() (in module gluonadmin) 4app_pack_compiled() (in module gluonadmin) 4app_uninstall() (in module gluonadmin) 4append() (gluonhtmlDIV method) 37append() (gluontemplateBlockNode method) 113append() (gluontemplateContent method) 114

appfactory() (in module gluonmain) 58apply_filter() (gluonlanguagestranslator method) 53archive() (gluontoolsAuth static method) 122archive() (gluontoolsCrud static method) 130arg0 (gluonrewriteMapUrlIn attribute) 71as_dict() (gluonhtmlFORM method) 41as_dict() (gluonsqlDAL method) 92as_dict() (gluonsqlDALField method) 91as_dict() (gluonsqlDALRow method) 91as_dict() (gluonsqlDALTable method) 92as_dict() (gluonsqlField method) 96as_json() (gluonhtmlFORM method) 41as_json() (gluonsqlDALRow method) 91as_xml() (gluonhtmlFORM method) 41as_xml() (gluonsqlDALRow method) 91as_yaml() (gluonhtmlFORM method) 41assert_status() (gluonhtmlFORM method) 41assert_status() (gluonsqlhtmlSQLFORM method) 101assign_tasks() (gluonschedulerScheduler method) 79ASSIGNJS() (in module gluonhtml) 35async() (gluonschedulerMetaScheduler method) 77Auth (class in gluontools) 121AutocompleteWidget (class in gluonsqlhtml) 97autoDetectXMLEncoding() (in module gluondecoder)

23autokey (gluoncacheCache attribute) 8automatic (gluonvalidatorsIS_IPV4 attribute) 158automenu() (gluontoolsWiki method) 135AUTOTYPES (gluonsqlhtmlSQLFORM attribute) 101

BB (class in gluonhtml) 36basic() (gluontoolsAuth method) 122BEAUTIFY (class in gluonhtml) 36being_a_ticker() (gluonschedulerScheduler method) 79BlockNode (class in gluontemplate) 113BODY (class in gluonhtml) 36body (gluonglobalsRequest attribute) 28BooleanWidget (class in gluonsqlhtml) 97BR (class in gluonhtml) 36

179

web2py Documentation Release 2146-stable

build_acf() (gluonrewriteMapUrlOut method) 72build_environment() (in module gluoncompileapp) 12build_query() (gluonsqlhtmlSQLFORM static method)

101build_set() (gluonvalidatorsIS_IN_DB method) 154bulk_insert() (gluonsqlDALTable method) 92bulk_register() (gluontoolsAuth method) 123BUTTON (class in gluonhtml) 36

CCache (class in gluoncache) 7CacheRepresenter (class in gluonsqlhtml) 97callback() (gluonsqlhtmlAutocompleteWidget method)

97can_edit() (gluontoolsWiki method) 135can_join() (gluonsqlDAL method) 92can_manage() (gluontoolsWiki method) 135can_read() (gluontoolsWiki method) 135can_search() (gluontoolsWiki method) 135can_see_menu() (gluontoolsWiki method) 135capitalize() (gluonutf8Utf8 method) 139cas_login() (gluontoolsAuth method) 123cas_validate() (gluontoolsAuth method) 123cast_keys() (in module gluonserializers) 83CAT (class in gluonhtml) 36CENTER (class in gluonhtml) 36center() (gluonutf8Utf8 method) 139change_password() (gluontoolsAuth method) 123check_credentials() (in module gluonfileutils) 26check_existent_app() (in module gluonwidget) 171check_interaction() (in module gluondebug) 22check_new_version() (in module gluonadmin) 4check_reserved_keyword() (gluonsqlDAL method) 92CheckboxesWidget (class in gluonsqlhtml) 97checkTaskBar() (gluonwidgetweb2pyDialog method)

171cleanpath() (in module gluonfileutils) 25CLEANUP (class in gluonvalidators) 145clear() (gluonglobalsSession method) 30clear_content() (gluontemplateContent method) 114clear_interaction() (gluondebugWebDebugger method)

21clear_session_cookies() (gluonglobalsSession method)

30clone() (gluonsqlDALField method) 91clone() (gluonsqlField method) 96close() (gluonportalockerLockedFile method) 65close() (gluonsqlDAL method) 92cloud() (gluontoolsWiki method) 135CODE (class in gluonhtml) 36COL (class in gluonhtml) 37COLGROUP (class in gluonhtml) 37commit() (gluonsqlDAL method) 92communicate() (in module gluondebug) 22

compare() (in module gluonutils) 143compile2() (in module gluonrestricted) 69compile_application() (in module gluoncompileapp) 12compile_controllers() (in module gluoncompileapp) 12compile_models() (in module gluoncompileapp) 12compile_regex() (in module gluonrewrite) 72compile_views() (in module gluoncompileapp) 12component() (gluontoolsWiki static method) 135compute_uuid() (gluonglobalsRequest method) 28confirm() (gluonhtmlFORM static method) 41confirm_registration() (gluontoolsAuth method) 123connect() (gluonglobalsSession method) 30connect_pages() (gluonwidgetweb2pyDialog method)

172console() (in module gluonwidget) 171Content (class in gluontemplate) 114content_type (gluonsqlhtmlExportClass attribute) 98content_type (gluonsqlhtmlExporterCSV attribute) 98content_type (gluonsqlhtmlExporterCSV_hidden

attribute) 98content_type (gluonsqlhtmlExporterHTML attribute)

98content_type (gluonsqlhtmlExporterJSON attribute) 98content_type (gluonsqlhtmlExporterTSV attribute) 99content_type (gluonsqlhtmlExporterXML attribute) 99contenttype() (in module gluoncontenttype) 15cookies2headers() (gluonhttpHTTP method) 51count() (gluonsqlDALField method) 91count() (gluonsqlField method) 96count() (gluonutf8Utf8 method) 139create() (gluontoolsCrud method) 130create() (gluontoolsWiki method) 135create_missing_app_folders() (in module gluonadmin) 5create_missing_folders() (in module gluonadmin) 5createform() (gluonsqlhtmlSQLFORM method) 102crondance() (in module gluonnewcron) 63cronlauncher (class in gluonnewcron) 63Crud (class in gluontools) 130CRYPT (class in gluonvalidators) 146csv() (gluontoolsService method) 132csv() (in module gluonserializers) 83custom_import_install() (in module

gluoncustom_import) 17custom_importer() (in module gluoncustom_import) 17custom_json() (in module gluonserializers) 83CustomImportException 17

DDAL (class in gluonsql) 89DALField (class in gluonsql) 91DALRow (class in gluonsql) 91DALTable (class in gluonsql) 92DatetimeWidget (class in gluonsqlhtml) 98DateWidget (class in gluonsqlhtml) 98

180 Index

web2py Documentation Release 2146-stable

DecimalWidget (class in gluonsqlhtml) 98decode() (gluonutf8Utf8 method) 139decoder() (in module gluondecoder) 23default_delimiters (gluontemplateTemplateParser

attribute) 115default_messages (gluontoolsAuth attribute) 123default_settings (gluontoolsAuth attribute) 124DEFAULT_WIDTH (gluonsqlhtmlUploadWidget

attribute) 104define_signature() (gluontoolsAuth method) 125define_table() (gluonsqlDAL method) 93define_tables() (gluonschedulerScheduler method) 79define_tables() (gluontoolsAuth method) 125del_group() (gluontoolsAuth method) 125del_membership() (gluontoolsAuth method) 125del_permission() (gluontoolsAuth method) 125delete() (gluontoolsCrud method) 130DELETE_FILE (gluonsqlhtmlUploadWidget attribute)

104dictform() (gluonsqlhtmlSQLFORM static method) 102die() (gluonschedulerMetaScheduler method) 78die() (in module gluonshell) 87disable() (gluonschedulerScheduler method) 79distributed_transaction_begin() (gluonsqlDAL static

method) 93distributed_transaction_commit() (gluonsqlDAL static

method) 93DIV (class in gluonhtml) 37do_continue() (gluondebugWebDebugger method) 21do_exec() (gluondebugWebDebugger method) 21do_next() (gluondebugWebDebugger method) 21do_quit() (gluondebugWebDebugger method) 21do_return() (gluondebugWebDebugger method) 21do_step() (gluondebugWebDebugger method) 21DoubleWidget (class in gluonsqlhtml) 98download() (gluonglobalsResponse method) 28drop() (gluonsqlDALTable method) 92DummyResponse (class in gluontemplate) 114

Eedit() (gluontoolsWiki method) 135editmedia() (gluontoolsWiki method) 135element() (gluonhtmlDIV method) 38elements() (gluonhtmlDIV method) 38elements() (gluonhtmlXML method) 49EM (class in gluonhtml) 40email_registration() (gluontoolsAuth method) 125email_reset_password() (gluontoolsAuth method) 125EMBED (class in gluonhtml) 40embed64() (in module gluonhtml) 50emit() (gluonmessageboxhandlerMessageBoxHandler

method) 59emit() (gluonmessageboxhandlerNotifySendHandler

method) 59

enable_autocomplete_and_history() (in modulegluonshell) 87

enable_record_versioning() (gluontoolsAuth method)125

encode() (gluonutf8Utf8 method) 140endswith() (gluonutf8Utf8 method) 140env() (in module gluonshell) 87error() (gluontoolsService method) 132error() (gluonwidgetweb2pyDialog method) 172everybody (gluontoolsWiki attribute) 135exception() (gluondebugWebDebugger method) 21exec_environment() (in module gluonshell) 87exec_pythonrc() (in module gluonshell) 87execute_from_command_line() (in module gluonshell)

87executesql() (gluonsqlDAL method) 93executor() (in module gluonscheduler) 82exists() (in module gluonrecfile) 67expandtabs() (gluonutf8Utf8 method) 140export() (gluonsqlhtmlExportClass method) 98export() (gluonsqlhtmlExporterCSV method) 98export() (gluonsqlhtmlExporterCSV_hidden method)

98export() (gluonsqlhtmlExporterHTML method) 98export() (gluonsqlhtmlExporterJSON method) 98export() (gluonsqlhtmlExporterTSV method) 99export() (gluonsqlhtmlExporterXML method) 99export_to_csv_file() (gluonsqlDAL method) 93ExportClass (class in gluonsqlhtml) 98ExporterCSV (class in gluonsqlhtml) 98ExporterCSV_hidden (class in gluonsqlhtml) 98ExporterHTML (class in gluonsqlhtml) 98ExporterJSON (class in gluonsqlhtml) 98ExporterTSV (class in gluonsqlhtml) 99ExporterXML (class in gluonsqlhtml) 99extcron (class in gluonnewcron) 63extend() (gluontemplateBlockNode method) 113extend() (gluontemplateContent method) 114extend() (gluontemplateTemplateParser method) 115

Ffactory() (gluonsqlhtmlSQLFORM static method) 102fast_urandom16() (in module gluonutils) 143fetch() (in module gluontools) 137Field (class in gluonsql) 95FIELDKEY_DELETE_RECORD

(gluonsqlhtmlSQLFORM attribute) 101FIELDNAME_REQUEST_DELETE

(gluonsqlhtmlSQLFORM attribute) 101fields (gluonsqlDALTable attribute) 92FIELDSET (class in gluonhtml) 40file_ext (gluonsqlhtmlExportClass attribute) 98file_ext (gluonsqlhtmlExporterCSV attribute) 98

Index 181

web2py Documentation Release 2146-stable

file_ext (gluonsqlhtmlExporterCSV_hidden attribute)98

file_ext (gluonsqlhtmlExporterHTML attribute) 98file_ext (gluonsqlhtmlExporterJSON attribute) 98file_ext (gluonsqlhtmlExporterTSV attribute) 99file_ext (gluonsqlhtmlExporterXML attribute) 99filter_err() (in module gluonrewrite) 72filter_url() (in module gluonrewrite) 72find() (gluonutf8Utf8 method) 140find_exposed_functions() (in module gluoncompileapp)

12findT() (in module gluonlanguages) 55first_paragraph() (gluontoolsWiki method) 135fix_hostname() (gluontoolsWiki method) 135fix_newlines() (in module gluonfileutils) 26fixup_missing_path_info() (in module gluonrewrite) 72flatten() (gluonhtmlDIV method) 39flatten() (gluonhtmlMARKMIN method) 44flatten() (gluonhtmlXML method) 49flush() (gluondebugPipe method) 21force() (gluonlanguagestranslator method) 53forget() (gluonglobalsSession method) 30FORM (class in gluonhtml) 40form_factory() (in module gluonsqlhtml) 104format() (gluonutf8Utf8 method) 140formatter() (gluonsqlDALField method) 91formatter() (gluonsqlField method) 96formatter() (gluonvalidatorsANY_OF method) 145formatter() (gluonvalidatorsIS_DATE method) 148formatter() (gluonvalidatorsIS_DATETIME method)

149formatter() (gluonvalidatorsIS_DECIMAL_IN_RANGE

method) 150formatter() (gluonvalidatorsIS_EMPTY_OR method)

152formatter() (gluonvalidatorsIS_FLOAT_IN_RANGE

method) 153formatter() (gluonvalidatorsIS_JSON method) 169formatter() (gluonvalidatorsIS_LIST_OF_EMAILS

method) 152formstyle_bootstrap() (in module gluonsqlhtml) 105formstyle_bootstrap3_inline_factory() (in module

gluonsqlhtml) 105formstyle_bootstrap3_stacked() (in module

gluonsqlhtml) 105formstyle_divs() (in module gluonsqlhtml) 105formstyle_inline() (in module gluonsqlhtml) 105formstyle_table2cols() (in module gluonsqlhtml) 105formstyle_table3cols() (in module gluonsqlhtml) 105formstyle_ul() (in module gluonsqlhtml) 105formstyles (gluonsqlhtmlSQLFORM attribute) 102FormWidget (class in gluonsqlhtml) 99frameset (gluonhtmlHTML attribute) 43frameset (gluonhtmlXHTML attribute) 49

Ggenerate() (in module gluonrecfile) 67GENERIC_DESCRIPTION

(gluonsqlhtmlUploadWidget attribute)104

geocode() (in module gluontools) 137get() (gluonhtmlDIV method) 39get() (gluonsqlDALRow method) 91get_callable_argspec() (in module gluonutils) 143get_code_for_scheduler() (in module gluonwidget) 171get_digest() (in module gluonutils) 143get_effective_router() (in module gluonrewrite) 72get_format() (gluontoolsCrud method) 130get_instances() (gluonsqlDAL static method) 93get_or_create_key() (gluontoolsAuth static method)

125get_or_create_user() (gluontoolsAuth method) 125get_parsed() (in module gluontemplate) 115get_possible_languages() (gluonlanguagestranslator

method) 54get_possible_languages_info()

(gluonlanguagestranslator method) 54get_query() (gluontoolsCrud method) 130get_renderer() (gluontoolsWiki method) 135get_session() (in module gluonfileutils) 26get_t() (gluonlanguagestranslator method) 54get_url() (in module gluonwidget) 171get_usage() (in module gluonshell) 87get_vars (gluonglobalsRequest attribute) 28get_vars_next() (gluontoolsAuth method) 126get_workers() (gluonschedulerScheduler method) 79getcfs() (in module gluoncfs) 9getfirst() (gluonstorageStorage method) 108getipaddrinfo() (in module gluonutils) 143getlast() (gluonstorageStorage method) 108getlist() (gluonstorageStorage method) 108give_up() (gluonschedulerMetaScheduler method) 78gluonadmin (module) 3gluoncache (module) 7gluoncfs (module) 9gluoncompileapp (module) 11gluoncontenttype (module) 15gluoncustom_import (module) 17gluondal (module) 19gluondebug (module) 21gluondecoder (module) 23gluonfileutils (module) 25gluonglobals (module) 27gluonhighlight (module) 33gluonhtml (module) 35gluonhttp (module) 51gluonlanguages (module) 53gluonmain (module) 57gluonmessageboxhandler (module) 59

182 Index

web2py Documentation Release 2146-stable

gluonmyregex (module) 61gluonnewcron (module) 63gluonportalocker (module) 65gluonrecfile (module) 67gluonrestricted (module) 69gluonrewrite (module) 71gluonsanitizer (module) 75gluonscheduler (module) 77gluonserializers (module) 83gluonsettings (module) 85gluonshell (module) 87gluonsql (module) 89gluonsqlhtml (module) 97gluonstorage (module) 107gluonstreamer (module) 111gluontemplate (module) 113gluontools (module) 117gluonutf8 (module) 139gluonutils (module) 143gluonvalidators (module) 145gluonwidget (module) 171gluonxmlrpc (module) 173grid() (gluonsqlhtmlSQLFORM static method) 102groups() (gluontoolsAuth method) 126

HH1 (class in gluonhtml) 42H2 (class in gluonhtml) 42H3 (class in gluonhtml) 42H4 (class in gluonhtml) 42H5 (class in gluonhtml) 42H6 (class in gluonhtml) 42handler() (in module gluonxmlrpc) 173hardcron (class in gluonnewcron) 64harg0 (gluonrewriteMapUrlIn attribute) 71has_membership() (gluontoolsAuth method) 126has_options() (gluonsqlhtmlOptionsWidget static

method) 100has_permission() (gluontoolsAuth method) 126has_permission() (gluontoolsCrud method) 130has_representer() (gluonsqlDAL method) 94HEAD (class in gluonhtml) 42here() (gluontoolsAuth method) 126hidden_fields() (gluonhtmlFORM method) 41highlight() (in module gluonhighlight) 33HR (class in gluonhtml) 42HTML (class in gluonhtml) 42html5 (gluonhtmlHTML attribute) 43html_render() (gluontoolsWiki method) 135HTTP 51HttpServer (class in gluonmain) 58

II (class in gluonhtml) 43

ics() (in module gluonserializers) 83ID_DELETE_SUFFIX (gluonsqlhtmlUploadWidget at-

tribute) 104id_group() (gluontoolsAuth method) 126ID_LABEL_SUFFIX (gluonsqlhtmlSQLFORM at-

tribute) 101ID_ROW_SUFFIX (gluonsqlhtmlSQLFORM attribute)

101IFRAME (class in gluonhtml) 43IMG (class in gluonhtml) 43impersonate() (gluontoolsAuth method) 126import_from_csv_file() (gluonsqlDAL method) 94import_from_csv_file() (gluonsqlDALTable method)

92import_table_definitions() (gluonsqlDAL method) 94include() (gluontemplateTemplateParser method) 115include_files() (gluonglobalsResponse method) 28include_meta() (gluonglobalsResponse method) 28index() (gluonutf8Utf8 method) 140initialize_urandom() (in module gluonutils) 143INPUT (class in gluonhtml) 43insert() (gluonhtmlDIV method) 40insert() (gluonsqlDALTable method) 92insert() (gluontemplateContent method) 114instances (gluontoolsPluginManager attribute) 137IntegerWidget (class in gluonsqlhtml) 99interaction() (gluondebugWebDebugger method) 22invalid_url() (in module gluonrewrite) 72IO (class in gluonwidget) 171IS_ALPHANUMERIC (class in gluonvalidators) 147IS_DATE (class in gluonvalidators) 148IS_DATE_IN_RANGE (class in gluonvalidators) 147IS_DATETIME (class in gluonvalidators) 148IS_DATETIME_IN_RANGE (class in gluonvalidators)

148IS_DECIMAL_IN_RANGE (class in gluonvalidators)

149IS_EMAIL (class in gluonvalidators) 150IS_EMPTY_OR (class in gluonvalidators) 152IS_EQUAL_TO (class in gluonvalidators) 163is_expired() (gluonglobalsSession method) 30IS_EXPR (class in gluonvalidators) 152IS_FLOAT_IN_RANGE (class in gluonvalidators) 153IS_IMAGE (class in gluonvalidators) 153is_image() (gluonsqlhtmlUploadWidget static method)

104is_impersonating() (gluontoolsAuth method) 126IS_IN_DB (class in gluonvalidators) 154IS_IN_SET (class in gluonvalidators) 154IS_INT_IN_RANGE (class in gluonvalidators) 155IS_IPADDRESS (class in gluonvalidators) 159IS_IPV4 (class in gluonvalidators) 156IS_IPV6 (class in gluonvalidators) 158IS_JSON (class in gluonvalidators) 169

Index 183

web2py Documentation Release 2146-stable

IS_LENGTH (class in gluonvalidators) 161IS_LIST_OF (class in gluonvalidators) 162IS_LIST_OF_EMAILS (class in gluonvalidators) 152is_logged_in() (gluontoolsAuth method) 126is_loopback_ip_address() (in module gluonutils) 144IS_LOWER (class in gluonvalidators) 162IS_MATCH (class in gluonvalidators) 162is_new() (gluonglobalsSession method) 30IS_NOT_EMPTY (class in gluonvalidators) 163IS_NOT_IN_DB (class in gluonvalidators) 164IS_NULL_OR (in module gluonvalidators) 164IS_SLUG (class in gluonvalidators) 164IS_STRONG (class in gluonvalidators) 165IS_TIME (class in gluonvalidators) 166is_tracking_changes() (in module gluoncustom_import)

17IS_UPLOAD_FILENAME (class in gluonvalidators)

166IS_UPPER (class in gluonvalidators) 167IS_URL (class in gluonvalidators) 167is_valid_ip_address() (in module gluonutils) 144isalnum() (gluonutf8Utf8 method) 140isalpha() (gluonutf8Utf8 method) 140isdigit() (gluonutf8Utf8 method) 140islower() (gluonutf8Utf8 method) 140isodatetime (gluonvalidatorsIS_DATETIME attribute)

149isspace() (gluonutf8Utf8 method) 140istitle() (gluonutf8Utf8 method) 140isupper() (gluonutf8Utf8 method) 140

JJobGraph (class in gluonscheduler) 77join() (gluonutf8Utf8 method) 140json() (gluonglobalsResponse method) 28json() (gluontoolsService method) 132json() (in module gluonserializers) 83jsonrpc() (gluontoolsService method) 132jsonrpc2() (gluontoolsService method) 132jsonrpc_errors (gluontoolsService attribute) 133JSONWidget (class in gluonsqlhtml) 99jwt() (gluontoolsAuth method) 126

Kkeys() (gluontoolsPluginManager method) 137kill() (gluonschedulerScheduler method) 79

LLABEL (class in gluonhtml) 44label (gluonsqlhtmlExportClass attribute) 98label (gluonsqlhtmlExporterCSV attribute) 98label (gluonsqlhtmlExporterCSV_hidden attribute) 98label (gluonsqlhtmlExporterHTML attribute) 98label (gluonsqlhtmlExporterJSON attribute) 98

label (gluonsqlhtmlExporterTSV attribute) 99label (gluonsqlhtmlExporterXML attribute) 99launch() (gluonnewcronhardcron method) 64Lazy (gluonsqlDALField attribute) 91Lazy (gluonsqlField attribute) 95lazy_cache() (in module gluoncache) 8lazy_define_table() (gluonsqlDAL method) 94LEGEND (class in gluonhtml) 44LI (class in gluonhtml) 44LINK (class in gluonhtml) 44List (class in gluonstorage) 107listdir() (in module gluonfileutils) 25ListWidget (class in gluonsqlhtml) 99ljust() (gluonutf8Utf8 method) 140load() (gluonrestrictedRestrictedError method) 69load() (gluonrestrictedTicketStorage method) 69LOAD() (in module gluoncompileapp) 11load() (in module gluonrewrite) 72load_routers() (in module gluonrewrite) 73load_storage() (in module gluonstorage) 109LoadFactory (class in gluoncompileapp) 12loads_json() (in module gluonserializers) 83loads_yaml() (in module gluonserializers) 83local_import_aux() (in module gluoncompileapp) 12localhost (gluonvalidatorsIS_IPV4 attribute) 158lock() (in module gluonportalocker) 66LockedFile (class in gluonportalocker) 65log() (gluonrestrictedRestrictedError method) 69log_event() (gluontoolsAuth method) 127log_event() (gluontoolsCrud method) 130log_rewrite() (in module gluonrewrite) 73logger (gluonsqlDAL attribute) 94login() (gluontoolsAuth method) 127login_bare() (gluontoolsAuth method) 127login_user() (gluontoolsAuth method) 127logout() (gluontoolsAuth method) 127logout_bare() (gluontoolsAuth method) 127loop() (gluonschedulerMetaScheduler method) 78loop() (gluonschedulerScheduler method) 79lower() (gluonutf8Utf8 method) 141lstrip() (gluonutf8Utf8 method) 141

MM() (gluonlanguagestranslator method) 53Mail (class in gluontools) 117MailAttachment (class in gluontools) 118main() (in module gluonscheduler) 82make_fake_file_like_object() (in module gluonfileutils)

26manage_tokens() (gluontoolsAuth method) 127map_app() (gluonrewriteMapUrlIn method) 71map_controller() (gluonrewriteMapUrlIn method) 71map_function() (gluonrewriteMapUrlIn method) 71map_language() (gluonrewriteMapUrlIn method) 71

184 Index

web2py Documentation Release 2146-stable

map_prefix() (gluonrewriteMapUrlIn method) 71map_root_static() (gluonrewriteMapUrlIn method) 72map_static() (gluonrewriteMapUrlIn method) 72map_url_in() (in module gluonrewrite) 73map_url_out() (in module gluonrewrite) 73MapUrlIn (class in gluonrewrite) 71MapUrlOut (class in gluonrewrite) 72MARKMIN (class in gluonhtml) 44markmin_base() (gluontoolsWiki method) 135markmin_render() (gluontoolsWiki method) 135maybe_add() (gluonvalidatorsIS_IN_DB method) 154md5_hash() (in module gluonutils) 144media() (gluontoolsWiki method) 135MENU (class in gluonhtml) 44menu() (gluontoolsWiki method) 135message (gluonhttpHTTP attribute) 51MessageBoxHandler (class in

gluonmessageboxhandler) 59Messages (class in gluonstorage) 108META (class in gluonhtml) 45MetaScheduler (class in gluonscheduler) 77Method (gluonsqlDALField attribute) 91Method (gluonsqlField attribute) 95mktree() (in module gluonfileutils) 25model_cmp() (in module gluoncompileapp) 12model_cmp_sep() (in module gluoncompileapp) 12MultipleOptionsWidget (class in gluonsqlhtml) 99mybuiltin (class in gluoncompileapp) 12

Nnavbar() (gluontoolsAuth method) 127nice() (gluonvalidatorsIS_DATETIME static method)

149no_underscore() (gluonhtmlBEAUTIFY static method)

36Node (class in gluontemplate) 114NOESCAPE (class in gluontemplate) 114not_authorized() (gluontoolsAuth method) 127not_authorized() (gluontoolsWiki method) 135NotifySendHandler (class in gluonmessageboxhandler)

59now() (gluonschedulerScheduler method) 79numbers (gluonvalidatorsIS_IPV4 attribute) 158

OOBJECT (class in gluonhtml) 45OL (class in gluonhtml) 44omit_acf() (gluonrewriteMapUrlOut method) 72omit_lang() (gluonrewriteMapUrlOut method) 72on() (gluonsqlDALTable method) 92open() (in module gluonrecfile) 67OPTGROUP (class in gluonhtml) 45OPTION (class in gluonhtml) 45options() (gluonvalidatorsIS_IN_DB method) 154

options() (gluonvalidatorsIS_IN_SET method) 155OptionsWidget (class in gluonsqlhtml) 100output() (gluontemplateBlockNode method) 113output_aux() (in module gluontemplate) 115

PP (class in gluonhtml) 45PACKAGE_PATH_SUFFIX

(gluoncustom_importTrackImporter at-tribute) 17

pad() (in module gluonutils) 144pages() (gluontoolsWiki method) 136params_substitution() (gluonlanguagestranslator

method) 54parse() (gluontemplateTemplateParser method) 115parse_all_vars() (gluonglobalsRequest method) 28parse_as_rest() (gluonsqlDAL method) 94parse_get_vars() (gluonglobalsRequest method) 28parse_path_info() (in module gluonshell) 87parse_post_vars() (gluonglobalsRequest method) 28parse_template() (in module gluontemplate) 115parse_version() (in module gluonfileutils) 25parsecronline() (in module gluonnewcron) 64partition() (gluonutf8Utf8 method) 141PasswordWidget (class in gluonsqlhtml) 100pbkdf2_hex() (in module gluonutils) 144Pipe (class in gluondebug) 21plugin_install() (in module gluonadmin) 5plugin_pack() (in module gluonadmin) 5PluginManager (class in gluontools) 136plural() (gluonlanguagestranslator method) 55pop_arg_if() (gluonrewriteMapUrlIn method) 72pop_task() (gluonschedulerMetaScheduler method) 78pop_task() (gluonschedulerScheduler method) 79post_vars (gluonglobalsRequest attribute) 28PRE (class in gluonhtml) 45prettydate() (in module gluontools) 137preview() (gluontoolsWiki method) 136private (gluonvalidatorsIS_IPV4 attribute) 158process() (gluonhtmlFORM method) 41profile() (gluontoolsAuth method) 127

Qqueue_task() (gluonschedulerScheduler method) 79quit() (gluonwidgetweb2pyDialog method) 172

Rr_multiline (gluontemplateTemplateParser attribute)

115r_tag (gluontemplateTemplateParser attribute) 115RadioWidget (class in gluonsqlhtml) 100random_password() (gluontoolsAuth method) 127rangetolist() (in module gluonnewcron) 64re_block (gluontemplateTemplateParser attribute) 115

Index 185

web2py Documentation Release 2146-stable

re_compile() (in module gluoncompileapp) 12re_pass (gluontemplateTemplateParser attribute) 115re_unblock (gluontemplateTemplateParser attribute)

115read() (gluondebugPipe method) 21read() (gluonportalockerLockedFile method) 66read() (gluontoolsCrud method) 130read() (gluontoolsWiki method) 136read_file() (in module gluonfileutils) 25read_locked() (in module gluonportalocker) 66read_pyc() (in module gluoncompileapp) 12readline() (gluondebugPipe method) 21readline() (gluonportalockerLockedFile method) 66readlines() (gluonportalockerLockedFile method) 66readlines_file() (in module gluonfileutils) 25Recaptcha (class in gluontools) 129Recaptcha2 (class in gluontools) 129recursive_unlink() (in module gluonfileutils) 25redirect() (in module gluonhttp) 51REDIRECT_JS (gluonhtmlFORM attribute) 41regex (gluonvalidatorsIS_EMAIL attribute) 151regex (gluonvalidatorsIS_IPV4 attribute) 158regex_attr (gluonhtmlDIV attribute) 40regex_class (gluonhtmlDIV attribute) 40REGEX_CLEANUP (gluonvalidatorsCLEANUP

attribute) 146regex_filter_in() (in module gluonrewrite) 73regex_filter_out() (in module gluonrewrite) 73regex_id (gluonhtmlDIV attribute) 40regex_proposed_but_failed (gluonvalidatorsIS_EMAIL

attribute) 151regex_select() (in module gluonrewrite) 73regex_tag (gluonhtmlDIV attribute) 40regex_uri() (in module gluonrewrite) 73regex_url_in() (in module gluonrewrite) 73register() (gluontoolsAuth method) 127register_bare() (gluontoolsAuth method) 127reindent() (gluontemplateTemplateParser method) 115release() (gluonnewcronToken method) 63remove() (in module gluonrecfile) 67remove_compiled_application() (in module

gluoncompileapp) 12render() (gluonglobalsResponse method) 28render() (in module gluontemplate) 115render_tags() (gluontoolsWiki method) 136renew() (gluonglobalsSession method) 30replace() (gluonutf8Utf8 method) 141report_task() (gluonschedulerMetaScheduler method)

78report_task() (gluonschedulerScheduler method) 80represent() (gluonsqlDAL method) 94represent() (gluonsqlhtmlUploadWidget class method)

104represent() (in module gluonsqlhtml) 105

represented() (gluonsqlhtmlExportClass method) 98representers (gluonsqlDAL attribute) 94Request (class in gluonglobals) 27request_reset_password() (gluontoolsAuth method) 127requires() (gluontoolsAuth method) 127requires_https() (gluonglobalsRequest method) 28requires_login() (gluontoolsAuth method) 127requires_login_or_token() (gluontoolsAuth method)

127requires_membership() (gluontoolsAuth method) 128requires_permission() (gluontoolsAuth method) 128requires_signature() (gluontoolsAuth method) 128reset_password() (gluontoolsAuth method) 128reset_password_deprecated() (gluontoolsAuth method)

128Response (class in gluonglobals) 28restful() (gluonglobalsRequest method) 28restricted() (in module gluonrestricted) 69RestrictedError 69resume() (gluonschedulerScheduler method) 80retrieve() (gluonsqlDALField method) 91retrieve() (gluonsqlField method) 96retrieve_file_properties() (gluonsqlDALField method)

91retrieve_file_properties() (gluonsqlField method) 96retrieve_password() (gluontoolsAuth method) 128retrieve_username() (gluontoolsAuth method) 128reverse_geocode() (in module gluontools) 137rfind() (gluonutf8Utf8 method) 141rindex() (gluonutf8Utf8 method) 141rjust() (gluonutf8Utf8 method) 141rollback() (gluonsqlDAL method) 94rows() (gluontoolsCrud method) 130rows_page (gluontoolsWiki attribute) 136rpartition() (gluonutf8Utf8 method) 141rsplit() (gluonutf8Utf8 method) 141rss() (gluontoolsService method) 133rss() (in module gluonserializers) 83rstrip() (gluonutf8Utf8 method) 141run() (gluondebugWebDebugger method) 22run() (gluonnewcroncronlauncher method) 63run() (gluonnewcronextcron method) 64run() (gluonnewcronhardcron method) 64run() (gluonnewcronsoftcron method) 64run() (gluonschedulerMetaScheduler method) 78run() (gluontoolsService method) 133run() (in module gluonshell) 88run_controller_in() (in module gluoncompileapp) 13run_login_onaccept() (gluontoolsAuth method) 128run_models_in() (in module gluoncompileapp) 13run_system_tests() (in module gluonwidget) 171run_view_in() (in module gluoncompileapp) 13

186 Index

web2py Documentation Release 2146-stable

Ssafe_encode() (in module gluonserializers) 83safe_float() (in module gluonsqlhtml) 105safe_int() (in module gluonsqlhtml) 105sanitize() (in module gluonsanitizer) 75save_password() (in module gluonmain) 58save_pyc() (in module gluoncompileapp) 13save_session_id_cookie() (gluonglobalsSession

method) 31save_storage() (in module gluonstorage) 109Scheduler (class in gluonscheduler) 78SCRIPT (class in gluonhtml) 45search() (gluontoolsCrud method) 130search() (gluontoolsWiki method) 136search_menu() (gluonsqlhtmlSQLFORM static

method) 102secure() (gluonglobalsSession method) 31secure_dumps() (in module gluonutils) 144secure_loads() (in module gluonutils) 144SELECT (class in gluonhtml) 45select() (gluontoolsCrud method) 131select_host() (gluontoolsAuth method) 128send() (gluontoolsMail method) 119send_heartbeat() (gluonschedulerMetaScheduler

method) 78send_heartbeat() (gluonschedulerScheduler method) 80serialize() (gluonhtmlMENU method) 45serialize_mobile() (gluonhtmlMENU method) 45serializers (gluonsqlDAL attribute) 95serve_amfrpc() (gluontoolsService method) 133serve_csv() (gluontoolsService method) 134serve_json() (gluontoolsService method) 134serve_jsonrpc() (gluontoolsService method) 134serve_jsonrpc2() (gluontoolsService method) 134serve_rss() (gluontoolsService method) 134serve_run() (gluontoolsService method) 134serve_soap() (gluontoolsService method) 134serve_xml() (gluontoolsService method) 134serve_xmlrpc() (gluontoolsService method) 134server_ready() (gluonwidgetweb2pyDialog method)

172Service (class in gluontools) 131ServiceJsonRpcException 131Session (class in gluonglobals) 29set_attributes() (gluonsqlDALField method) 91set_attributes() (gluonsqlField method) 96set_current_languages() (gluonlanguagestranslator

method) 55set_folder() (gluonsqlDAL static method) 95set_requirements() (gluonschedulerScheduler method)

80set_self_id() (gluonvalidatorsIS_EMPTY_OR method)

152set_self_id() (gluonvalidatorsIS_IN_DB method) 154

set_self_id() (gluonvalidatorsIS_NOT_IN_DB method)164

set_trace() (in module gluondebug) 22set_worker_status() (gluonschedulerScheduler method)

80Settings (class in gluonstorage) 108show_if() (in module gluonsqlhtml) 105sibling() (gluonhtmlDIV method) 40siblings() (gluonhtmlDIV method) 40simple_hash() (in module gluonutils) 144sleep() (gluonschedulerMetaScheduler method) 78sleep() (gluonschedulerScheduler method) 80sluggify() (gluonrewriteMapUrlIn method) 72sluggify() (in module gluonrewrite) 73smart_query() (gluonsqlDAL method) 95smartdictform() (gluonsqlhtmlSQLFORM static

method) 102smartgrid() (gluonsqlhtmlSQLFORM static method)

102soap() (gluontoolsService method) 134softcron (class in gluonnewcron) 64SPAN (class in gluonhtml) 46split() (gluonutf8Utf8 method) 141split_emails (gluonvalidatorsIS_LIST_OF_EMAILS at-

tribute) 152splitlines() (gluonutf8Utf8 method) 141SQLFORM (class in gluonsqlhtml) 100sqlsafe (gluonsqlDALField attribute) 91sqlsafe (gluonsqlDALTable attribute) 92sqlsafe (gluonsqlField attribute) 96sqlsafe_alias (gluonsqlDALTable attribute) 92sqlsafe_name (gluonsqlDALField attribute) 91sqlsafe_name (gluonsqlField attribute) 96SQLTABLE (class in gluonsqlhtml) 103start() (gluonmainHttpServer method) 58start() (gluonwidgetweb2pyDialog method) 172start() (in module gluonwidget) 171start_browser() (in module gluonwidget) 171start_heartbeats() (gluonschedulerMetaScheduler

method) 78start_schedulers() (gluonwidgetweb2pyDialog method)

172start_schedulers() (in module gluonwidget) 171startswith() (gluonutf8Utf8 method) 141stop() (gluonmainHttpServer method) 58stop() (gluonwidgetweb2pyDialog method) 172stop_task() (gluonschedulerScheduler method) 80stop_trace() (in module gluondebug) 22stopcron() (in module gluonnewcron) 64Storage (class in gluonstorage) 107StorageList (class in gluonstorage) 109store() (gluonrestrictedTicketStorage method) 69store() (gluonsqlDALField method) 91store() (gluonsqlField method) 96

Index 187

web2py Documentation Release 2146-stable

stream() (gluonglobalsResponse method) 28stream_file_or_304_or_206() (in module

gluonstreamer) 111streamer() (in module gluonstreamer) 111strict (gluonhtmlHTML attribute) 43strict (gluonhtmlXHTML attribute) 49StringWidget (class in gluonsqlhtml) 103strip() (gluonutf8Utf8 method) 141STRONG (class in gluonhtml) 46STYLE (class in gluonhtml) 46style() (gluonsqlhtmlSQLTABLE method) 103SuperNode (class in gluontemplate) 114swapcase() (gluonutf8Utf8 method) 142

TTABLE (class in gluonhtml) 46table_cas() (gluontoolsAuth method) 128table_event() (gluontoolsAuth method) 128table_group() (gluontoolsAuth method) 128table_membership() (gluontoolsAuth method) 128table_permission() (gluontoolsAuth method) 128table_token() (gluontoolsAuth method) 128table_user() (gluontoolsAuth method) 128tables (gluonsqlDAL attribute) 95tables() (gluontoolsCrud method) 131tag (gluonhtmlA attribute) 35tag (gluonhtmlB attribute) 36tag (gluonhtmlBEAUTIFY attribute) 36tag (gluonhtmlBODY attribute) 36tag (gluonhtmlBR attribute) 36tag (gluonhtmlBUTTON attribute) 36tag (gluonhtmlCAT attribute) 36tag (gluonhtmlCENTER attribute) 36tag (gluonhtmlCOL attribute) 37tag (gluonhtmlCOLGROUP attribute) 37tag (gluonhtmlDIV attribute) 40tag (gluonhtmlEM attribute) 40tag (gluonhtmlEMBED attribute) 40tag (gluonhtmlFIELDSET attribute) 40tag (gluonhtmlFORM attribute) 41tag (gluonhtmlH1 attribute) 42tag (gluonhtmlH2 attribute) 42tag (gluonhtmlH3 attribute) 42tag (gluonhtmlH4 attribute) 42tag (gluonhtmlH5 attribute) 42tag (gluonhtmlH6 attribute) 42tag (gluonhtmlHEAD attribute) 42tag (gluonhtmlHR attribute) 42tag (gluonhtmlHTML attribute) 43tag (gluonhtmlI attribute) 43tag (gluonhtmlIFRAME attribute) 43tag (gluonhtmlIMG attribute) 43tag (gluonhtmlINPUT attribute) 44tag (gluonhtmlLABEL attribute) 44

tag (gluonhtmlLEGEND attribute) 44tag (gluonhtmlLI attribute) 44tag (gluonhtmlLINK attribute) 44tag (gluonhtmlMENU attribute) 45tag (gluonhtmlMETA attribute) 45tag (gluonhtmlOBJECT attribute) 45tag (gluonhtmlOL attribute) 44tag (gluonhtmlOPTGROUP attribute) 45tag (gluonhtmlOPTION attribute) 45tag (gluonhtmlP attribute) 45tag (gluonhtmlPRE attribute) 45tag (gluonhtmlSCRIPT attribute) 45tag (gluonhtmlSELECT attribute) 46tag (gluonhtmlSPAN attribute) 46tag (gluonhtmlSTRONG attribute) 46tag (gluonhtmlSTYLE attribute) 46tag (gluonhtmlTABLE attribute) 46tag (gluonhtmlTBODY attribute) 47tag (gluonhtmlTD attribute) 46tag (gluonhtmlTEXTAREA attribute) 46tag (gluonhtmlTFOOT attribute) 47tag (gluonhtmlTH attribute) 47tag (gluonhtmlTHEAD attribute) 47tag (gluonhtmlTITLE attribute) 47tag (gluonhtmlTR attribute) 47tag (gluonhtmlTT attribute) 47tag (gluonhtmlUL attribute) 44tag (gluonhtmlXHTML attribute) 49TAG (in module gluonhtml) 46tar() (in module gluonfileutils) 26tar_compiled() (in module gluonfileutils) 26Task (class in gluonscheduler) 81task_status() (gluonschedulerScheduler method) 81TaskReport (class in gluonscheduler) 82TBODY (class in gluonhtml) 47TD (class in gluonhtml) 46TemplateParser (class in gluontemplate) 114terminate() (gluonschedulerScheduler method) 81terminate_process() (gluonschedulerMetaScheduler

method) 78test() (in module gluoncompileapp) 13test() (in module gluonshell) 88TEXTAREA (class in gluonhtml) 46TextWidget (class in gluonsqlhtml) 103TFOOT (class in gluonhtml) 47TH (class in gluonhtml) 46THEAD (class in gluonhtml) 47THREAD_LOCAL (gluoncustom_importTrackImporter

attribute) 17TicketStorage (class in gluonrestricted) 69TimeWidget (class in gluonsqlhtml) 104TITLE (class in gluonhtml) 47title() (gluonutf8Utf8 method) 142to() (gluonhttpHTTP method) 51

188 Index

web2py Documentation Release 2146-stable

to_string() (gluontemplateTemplateParser method) 115Token (class in gluonnewcron) 63toolbar() (gluonglobalsResponse method) 29total_seconds() (gluonschedulerScheduler static

method) 81TR (class in gluonhtml) 47track_changes() (in module gluoncustom_import) 17TrackImporter (class in gluoncustom_import) 17transitional (gluonhtmlHTML attribute) 43transitional (gluonhtmlXHTML attribute) 49translate() (gluonlanguagestranslator method) 55translate() (gluonutf8Utf8 method) 142translator (class in gluonlanguages) 53truncate() (gluonsqlDALTable method) 92try_redirect_on_error() (in module gluonrewrite) 73try_rewrite_on_error() (in module gluonrewrite) 73try_start_scheduler() (gluonwidgetweb2pyDialog

method) 172try_stop_scheduler() (gluonwidgetweb2pyDialog

method) 172TT (class in gluonhtml) 47TYPE (class in gluonscheduler) 81

UUL (class in gluonhtml) 44unlock() (in module gluonportalocker) 66untar() (in module gluonfileutils) 26unzip() (in module gluonadmin) 5up() (in module gluonfileutils) 25update() (gluonhtmlDIV method) 40update() (gluonsqlDALTable method) 92update() (gluontoolsCrud method) 131update() (gluonwidgetweb2pyDialog method) 172update_all_languages() (in module gluonlanguages) 55update_canvas() (gluonwidgetweb2pyDialog method)

172update_dependencies() (gluonschedulerScheduler

method) 81update_groups() (gluontoolsAuth method) 128update_or_insert() (gluonsqlDALTable method) 92update_request() (gluonrewriteMapUrlIn method) 72update_schedulers() (gluonwidgetweb2pyDialog

method) 172upgrade() (in module gluonadmin) 5UploadWidget (class in gluonsqlhtml) 104upper() (gluonutf8Utf8 method) 142url() (gluontoolsAuth method) 128url() (gluontoolsCrud method) 131URL() (in module gluonhtml) 47url_in() (in module gluonrewrite) 73url_out() (in module gluonrewrite) 73urlify() (gluonvalidatorsIS_SLUG static method) 165user_agent() (gluonglobalsRequest method) 28user_group() (gluontoolsAuth method) 128

user_group_role() (gluontoolsAuth method) 128user_id (gluontoolsAuth attribute) 128Utf8 (class in gluonutf8) 139uuid (gluonglobalsRequest attribute) 28uuid() (gluonsqlDAL method) 95

Vvalidate() (gluonhtmlFORM method) 41validate() (gluonschedulerJobGraph method) 77validate() (gluonsqlDALField method) 91validate() (gluonsqlField method) 96validate_and_insert() (gluonsqlDALTable method) 92validate_and_update() (gluonsqlDALTable method) 92validate_and_update_or_insert() (gluonsqlDALTable

method) 92validate_args() (gluonrewriteMapUrlIn method) 72validators (gluonsqlDAL attribute) 95validators_method() (gluonsqlDAL method) 95vars (gluonglobalsRequest attribute) 28verify_email() (gluontoolsAuth method) 128VERIFY_SERVER (gluontoolsRecaptcha attribute)

129VERIFY_SERVER (gluontoolsRecaptcha2 attribute)

130Virtual (gluonsqlDALField attribute) 91Virtual (gluonsqlField attribute) 96

Ww2p_pack() (in module gluonfileutils) 26w2p_pack_plugin() (in module gluonfileutils) 26w2p_unpack() (in module gluonfileutils) 26w2p_unpack_plugin() (in module gluonfileutils) 26web2py_uuid() (in module gluonutils) 144web2pyDialog (class in gluonwidget) 171WebDebugger (class in gluondebug) 21when_is_logged_in_bypass_next_in_url()

(gluontoolsAuth method) 128where() (gluonsqlDAL method) 95widget() (gluonsqlhtmlBooleanWidget class method)

97widget() (gluonsqlhtmlCheckboxesWidget class

method) 97widget() (gluonsqlhtmlFormWidget class method) 99widget() (gluonsqlhtmlJSONWidget class method) 99widget() (gluonsqlhtmlListWidget class method) 99widget() (gluonsqlhtmlMultipleOptionsWidget class

method) 100widget() (gluonsqlhtmlOptionsWidget class method)

100widget() (gluonsqlhtmlPasswordWidget class method)

100widget() (gluonsqlhtmlRadioWidget class method) 100widget() (gluonsqlhtmlStringWidget class method) 103widget() (gluonsqlhtmlTextWidget class method) 104

Index 189

web2py Documentation Release 2146-stable

widget() (gluonsqlhtmlUploadWidget class method)104

widgets (gluonsqlhtmlSQLFORM attribute) 103Wiki (class in gluontools) 135wiki() (gluontoolsAuth method) 129wikimenu() (gluontoolsAuth method) 129with_alias() (gluonsqlDALTable method) 92with_prefix() (gluoncacheCache static method) 8wrapped_assign_tasks() (gluonschedulerScheduler

method) 81wrapped_pop_task() (gluonschedulerScheduler

method) 81wrapped_report_task() (gluonschedulerScheduler

method) 81write() (gluondebugPipe method) 21write() (gluonglobalsResponse method) 29write() (gluonportalockerLockedFile method) 66write() (gluontemplateDummyResponse method) 114write() (gluonwidgetIO method) 171write_file() (in module gluonfileutils) 25write_locked() (in module gluonportalocker) 66wsgibase() (in module gluonmain) 57

XXHTML (class in gluonhtml) 49XML (class in gluonhtml) 49xml() (gluonhtmlA method) 35xml() (gluonhtmlCODE method) 37xml() (gluonhtmlDIV method) 40xml() (gluonhtmlFORM method) 42xml() (gluonhtmlHTML method) 43xml() (gluonhtmlINPUT method) 44xml() (gluonhtmlMARKMIN method) 44xml() (gluonhtmlMENU method) 45xml() (gluonhtmlP method) 45xml() (gluonhtmlSCRIPT method) 45xml() (gluonhtmlSTYLE method) 46xml() (gluonhtmlXHTML method) 49xml() (gluonhtmlXML method) 50xml() (gluontemplateNOESCAPE method) 114xml() (gluontoolsRecaptcha method) 129xml() (gluontoolsRecaptcha2 method) 130xml() (gluontoolsService method) 134xml() (in module gluonserializers) 83xml_rec() (in module gluonserializers) 83xmlescape() (in module gluonhtml) 50xmlns (gluonhtmlXHTML attribute) 49xmlrpc() (gluonglobalsResponse method) 29xmlrpc() (gluontoolsService method) 134

Yyaml() (in module gluonserializers) 83

Zzfill() (gluonutf8Utf8 method) 142

190 Index

  • admin Module
    • Utility functions for the Admin application
      • cache Module
        • Basic caching classes and methods
          • cfs Module
            • Functions required to execute app components
              • compileapp Module
                • Functions required to execute app components
                  • contenttype Module
                  • custom_import Module
                    • Support for smart import syntax for web2py applications
                      • dal Module
                        • Takes care of adapting pyDAL to web2pyrsquos needs
                          • debug Module
                            • Debugger support classes
                              • decoder Module
                              • fileutils Module
                                • File operations
                                  • globals Module
                                  • highlight Module
                                  • html Module
                                    • Template helpers
                                      • http Module
                                        • HTTP statuses helpers
                                          • languages Module
                                            • Translation system
                                              • main Module
                                                • The gluon wsgi application
                                                  • messageboxhandler Module
                                                  • myregex Module
                                                    • Useful regexes
                                                      • newcron Module
                                                      • portalocker Module
                                                      • recfile Module
                                                        • Generates names for cache and session files
                                                          • restricted Module
                                                            • Restricted environment to execute applicationrsquos code
                                                              • rewrite Module
                                                              • sanitizer Module
                                                                • Cross-site scripting (XSS) defense
                                                                  • scheduler Module
                                                                    • Background processes made simple
                                                                      • serializers Module
                                                                      • settings Module
                                                                      • shell Module
                                                                        • Web2py environment in the shell
                                                                          • sql Module
                                                                            • Just for backward compatibility
                                                                              • sqlhtml Module
                                                                              • storage Module
                                                                              • streamer Module
                                                                                • Facilities to handle file streaming
                                                                                  • template Module
                                                                                    • Templating syntax
                                                                                      • tools Module
                                                                                        • Auth Mail PluginManager and various utilities
                                                                                          • utf8 Module
                                                                                            • Utilities and class for UTF8 strings managing
                                                                                              • utils Module
                                                                                                • This file specifically includes utilities for security
                                                                                                  • validators Module
                                                                                                    • Validators
                                                                                                      • widget Module
                                                                                                        • The widget is called from web2py
                                                                                                          • xmlrpc Module
                                                                                                          • Indices and tables
                                                                                                          • Python Module Index
Page 5: web2py Documentation - Read the Docs

iv

web2py Documentation Release 2146-stable

Contents

Contents 1

web2py Documentation Release 2146-stable

2 Contents

CHAPTER 1

admin Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

11 Utility functions for the Admin application

gluonadminadd_path_first(path)

gluonadminapath(path=rdquo r=None)Builds a path inside an application folder

Parameters

bull path (str) ndash path within the application folder

bull r ndash the global request object

gluonadminapp_cleanup(app request)Removes session cache and error files

Parameters

bull app (str) ndash application name

bull request ndash the global request object

Returns True if everything went ok False otherwise

gluonadminapp_compile(app request skip_failed_views=False)Compiles the application

Parameters

bull app (str) ndash application name

bull request ndash the global request object

3

web2py Documentation Release 2146-stable

Returns None if everything went ok traceback text if errors are found

gluonadminapp_create(app request force=False key=None info=False)Create a copy of welcomew2p (scaffolding) app

Parameters

bull app (str) ndash application name

bull request ndash the global request object

gluonadminapp_install(app fobj request filename overwrite=None)Installs an application

bull Identifies file type by filename

bull Writes fobj contents to the deposit folder

bull Calls w2p_unpack() to do the job

Parameters

bull app (str) ndash new application name

bull fobj (obj) ndash file object containing the application to be installed

bull request ndash the global request object

bull filename (str) ndash original filename of the fobj required to determine extension

bull overwrite (bool) ndash force overwrite of existing application

Returns name of the file where app is temporarily stored or None on failure

gluonadminapp_pack(app request raise_ex=False filenames=None)Builds a w2p package for the application

Parameters

bull app (str) ndash application name

bull request ndash the global request object

Returns filename of the w2p file or None on error

gluonadminapp_pack_compiled(app request raise_ex=False)Builds a w2p bytecode-compiled package for the application

Parameters

bull app (str) ndash application name

bull request ndash the global request object

Returns filename of the w2p file or None on error

gluonadminapp_uninstall(app request)Uninstalls the application

Parameters

bull app (str) ndash application name

bull request ndash the global request object

Returns True on success False on failure

4 Chapter 1 admin Module

web2py Documentation Release 2146-stable

gluonadmincheck_new_version(myversion version_url)Compares current web2pyrsquos version with the latest stable web2py version

Parameters

bull myversion ndash the current version as stored in file web2pyVERSION

bull version_URL ndash the URL that contains the version of the latest stable release

Returns

state version

bull state True if upgrade available False if current version is up-to-date -1 on error

bull version the most up-to-version available

Return type tuple

gluonadmincreate_missing_app_folders(request)

gluonadmincreate_missing_folders()

gluonadminplugin_install(app fobj request filename)Installs a plugin

bull Identifies file type by filename

bull Writes fobj contents to the deposit folder

bull Calls w2p_unpack_plugin() to do the job

Parameters

bull app (str) ndash new application name

bull fobj ndash file object containing the application to be installed

bull request ndash the global request object

bull filename ndash original filename of the fobj required to determine extension

Returns name of the file where plugin is temporarily stored or False on failure

gluonadminplugin_pack(app plugin_name request)Builds a w2p package for the plugin

Parameters

bull app (str) ndash application name

bull plugin_name (str) ndash the name of the plugin without plugin_ prefix

bull request ndash the current request app

Returns filename of the w2p file or False on error

gluonadminunzip(filename dir subfolder=rdquo)Unzips filename into dir (zip only no gz etc)

Parameters

bull filename (str) ndash archive

bull dir (str) ndash destination

bull subfolder (str) ndash if = lsquorsquo unzips only files in subfolder

11 Utility functions for the Admin application 5

web2py Documentation Release 2146-stable

gluonadminupgrade(request url=rsquohttpweb2pycomrsquo)Upgrades web2py (src osx win) if a new version is posted It detects whether src osx or win is running anddownloads the right one

Parameters

bull request ndash the current request object (required to determine version and path)

bull url ndash the incomplete url where to locate the latest web2py (actual url isurl+rsquoexamplesstaticweb2py_(src|osx|win)ziprsquo)

Returns tuple completed traceback

bull completed True on success False on failure (network problem or old version)

bull traceback None on success raised exception details on failure

6 Chapter 1 admin Module

CHAPTER 2

cache Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

21 Basic caching classes and methods

bull Cache - The generic caching object interfacing with the others

bull CacheInRam - providing caching in ram

bull CacheOnDisk - provides caches on disk

Memcache is also available via a different module (see gluoncontribmemcache)

When web2py is running on Google App Engine caching will be provided by the GAE memcache (seegluoncontribgae_memcache)

class gluoncacheCache(request)Bases object

Sets up generic caching creating an instance of both CacheInRam and CacheOnDisk In case of GAE will makeuse of gluoncontribgae_memcache

bull selfram is an instance of CacheInRam

bull selfdisk is an instance of CacheOnDisk

action(time_expire=300 cache_model=None prefix=None session=False vars=True lang=Trueuser_agent=False public=True valid_statuses=None quick=None)

Better fit for caching an action

Warning Experimental

7

web2py Documentation Release 2146-stable

Currently only HTTP 11 compliant reference httpcodegooglecompdoctype-mirrorwikiArticleHttpCaching

Parameters

bull time_expire (int) ndash same as cache

bull cache_model (str) ndash same as cache

bull prefix (str) ndash add a prefix to the calculated key

bull session (bool) ndash adds responsesession_id to the key

bull vars (bool) ndash adds requestenvquery_string

bull lang (bool) ndash adds Taccepted_language

bull user_agent (bool or dict) ndash if True adds is_mobile and is_tablet tothe key Pass a dict to use all the needed values (uses str(items())) (eguser_agent=requestuser_agent()) Used only if session is not True

bull public (bool) ndash if False forces the Cache-Control to be lsquoprivatersquo

bull valid_statuses ndash by default only status codes starting with 123 will be cached passan explicit list of statuses on which turn the cache on

bull quick ndash SessionVarsLangUser-agentPublic fast overrides with initials eg lsquoSVLPrsquoor lsquoVLPrsquo or lsquoVLPrsquo

autokey = (name)s(args)s(vars)s

static with_prefix(cache_model prefix)allow replacing cacheram with cachewith_prefix(cacheramrsquoprefixrsquo) it will add prefix to all the cachekeys used

gluoncachelazy_cache(key=None time_expire=None cache_model=rsquoramrsquo)Can be used to cache any function including ones in modules as long as the cached function is only calledwithin a web2py request

If a key is not provided one is generated from the function name time_expire defaults to None (no cacheexpiration)

If cache_model is ldquoramrdquo then the model is currentcacheram etc

8 Chapter 2 cache Module

CHAPTER 3

cfs Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

31 Functions required to execute app components

Note FOR INTERNAL USE ONLY

gluoncfsgetcfs(key filename filter=None)Caches the filtered file filename with key until the file is modified

Parameters

bull key (str) ndash the cache key

bull filename ndash the file to cache

bull filter ndash is the function used for filtering Normally filename is a py file and filter is afunction that bytecode compiles the file In this way the bytecode compiled file is cached(Default = None)

This is used on Google App Engine since pyc files cannot be saved

9

web2py Documentation Release 2146-stable

10 Chapter 3 cfs Module

CHAPTER 4

compileapp Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

41 Functions required to execute app components

Note FOR INTERNAL USE ONLY

gluoncompileappLOAD(c=None f=rsquoindexrsquo args=None vars=None extension=None target=Noneajax=False ajax_trap=False url=None user_signature=False time-out=None times=1 content=rsquoloadingrsquo post_vars= attr)

LOADs a component into the actionrsquos document

Parameters

bull c (str) ndash controller

bull f (str) ndash function

bull args (tuple or list) ndash arguments

bull vars (dict) ndash vars

bull extension (str) ndash extension

bull target (str) ndash id of the target

bull ajax (bool) ndash True to enable AJAX bahaviour

bull ajax_trap (bool) ndash True if ajax is set to True traps both links and forms ldquoinsiderdquo thetarget

bull url (str) ndash overrides clsquoflsquolsquoargslsquo and vars

11

web2py Documentation Release 2146-stable

bull user_signature (bool) ndash adds hmac signature to all links with a key that is differentfor every user

bull timeout (int) ndash in milliseconds specifies the time to wait before starting the request orthe frequency if times is greater than 1 or ldquoinfinityrdquo

bull times (integer or str) ndash how many times the component will be requested ldquoinfin-ityrdquo or ldquocontinuousrdquo are accepted to reload indefinitely the component

class gluoncompileappLoadFactory(environment)Bases object

Attention this helper is new and experimental

gluoncompileappbuild_environment(request response session store_current=True)Build the environment dictionary into which web2py files are executed

gluoncompileappcompile_application(folder skip_failed_views=False)Compiles all models views controller for the application in folder

gluoncompileappcompile_controllers(folder)Compiles all the controllers in the application specified by folder

gluoncompileappcompile_models(folder)Compiles all the models in the application specified by folder

gluoncompileappcompile_views(folder skip_failed_views=False)Compiles all the views in the application specified by folder

gluoncompileappfind_exposed_functions(data)

gluoncompileapplocal_import_aux(name reload_force=False app=rsquowelcomersquo)In apps instead of importing a local module (in applicationsappmodules) with

import abc as d

you should do

d = local_import(abc)

or (to force a reload)

d = local_import(lsquoabcrsquo reload=True)

This prevents conflict between applications and un-necessary execs It can be used to import any moduleincluding regular Python modules

gluoncompileappmodel_cmp(a b sep=rsquorsquo)

gluoncompileappmodel_cmp_sep(a b sep=rsquorsquo)

class gluoncompileappmybuiltinBases object

NOTE could simple use a dict and populate it NOTE not sure if this changes things though if monkey patchingimport

gluoncompileappre_compile(regex)

gluoncompileappread_pyc(filename)Read the code inside a bytecode compiled file if the MAGIC number is compatible

Returns a code object

12 Chapter 4 compileapp Module

web2py Documentation Release 2146-stable

gluoncompileappremove_compiled_application(folder)Deletes the folder compiled containing the compiled application

gluoncompileapprun_controller_in(controller function environment)Runs the controllerfunction() (for the app specified by the current folder) It tries pre-compiled con-troller_functionpyc first before compiling it

gluoncompileapprun_models_in(environment)Runs all models (in the app specified by the current folder) It tries pre-compiled models first before compilingthem

gluoncompileapprun_view_in(environment)Executes the view for the requested action The view is the one specified in responseview or determined by theurl or viewgenericextension It tries the pre-compiled views_controller_functionpyc before compiling it

gluoncompileappsave_pyc(filename)Bytecode compiles the file filename

gluoncompileapptest()Example

gtgtgt import traceback typesgtgtgt environment=x1gtgtgt open(apy w)write(print 1x)gtgtgt save_pyc(apy)gtgtgt osunlink(apy)gtgtgt if type(read_pyc(apyc))==typesCodeType print codecodegtgtgt exec read_pyc(apyc) in environment1

41 Functions required to execute app components 13

web2py Documentation Release 2146-stable

14 Chapter 4 compileapp Module

CHAPTER 5

contenttype Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

CONTENT_TYPE dictionary created against freedesktoporgrsquos shared mime info database version 11

Deviations from official standards

bull md applicationx-genesis-rom ndashgt textx-markdown

bull png imagex-apple-ios-png ndashgt imagepng

Additions

bull load texthtml

bull json applicationjson

bull jsonp applicationjsonp

bull pickle applicationpython-pickle

bull w2prsquo applicationw2p

gluoncontenttypecontenttype(filename default=rsquotextplainrsquo)Returns the Content-Type string matching extension of the given filename

15

web2py Documentation Release 2146-stable

16 Chapter 5 contenttype Module

CHAPTER 6

custom_import Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

61 Support for smart import syntax for web2py applications

exception gluoncustom_importCustomImportExceptionBases exceptionsImportError

class gluoncustom_importTrackImporterBases object

An importer tracking the date of the module files and reloading them when they are changed

PACKAGE_PATH_SUFFIX = __init__py

THREAD_LOCAL = ltthread_local objectgt

gluoncustom_importcustom_import_install()

gluoncustom_importcustom_importer(name globals=None locals=None fromlist=Nonelevel=-1)

web2pyrsquos custom importer It behaves like the standard Python importer but it tries to transform importstatements as something like ldquoimport applicationsapp_namemodulesxrdquo If the import fails it falls back onnaive_importer

gluoncustom_importis_tracking_changes()

gluoncustom_importtrack_changes(track=True)

17

web2py Documentation Release 2146-stable

18 Chapter 6 custom_import Module

CHAPTER 7

dal Module

Go to httppydalreadthedocsorgenlatest for docs on pyDAL

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

71 Takes care of adapting pyDAL to web2pyrsquos needs

19

web2py Documentation Release 2146-stable

20 Chapter 7 dal Module

CHAPTER 8

debug Module

This file is part of the web2py Web FrameworkDeveloped by Massimo Di Pierro ltmdipierrocsdepauledugtlimodou ltlimodougmailcomgt and srackham ltsrackhamgmailcomgtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

81 Debugger support classes

class gluondebugPipe(name mode=rsquorrsquo args kwargs)Bases QueueQueue

flush()

read(count=None timeout=None)

readline()

write(data)

class gluondebugWebDebugger(pipe completekey=rsquotabrsquo stdin=None stdout=None)Bases gluoncontribqdbFrontend

Qdb web2py interface

clear_interaction()

do_continue(args kwargs)

do_exec(statement)

do_next(args kwargs)

do_quit(args kwargs)

do_return(args kwargs)

do_step(args kwargs)

21

web2py Documentation Release 2146-stable

exception(title extype exvalue trace request)Show a user_exception

interaction(filename lineno line context)

run()Main method dispatcher (infinite loop)

gluondebugcheck_interaction(fn)Decorator to clean and prevent interaction when not available

gluondebugcommunicate(command=None)send command to debbuger wait result

gluondebugset_trace()breakpoint shortcut (like pdb)

gluondebugstop_trace()stop waiting for the debugger (called atexit)

22 Chapter 8 debug Module

CHAPTER 9

decoder Module

Caller will hand this library a buffer and ask it to either convert it or auto-detect the type

Based on httpcodeactivestatecomrecipes52257

Licensed under the PSF License

gluondecoderautoDetectXMLEncoding(buffer)buffer -gt encoding_name The buffer should be at least 4 bytes long Returns None if encoding cannot bedetected Note that encoding_name might not have an installed decoder (eg EBCDIC)

gluondecoderdecoder(buffer)

23

web2py Documentation Release 2146-stable

24 Chapter 9 decoder Module

CHAPTER 10

fileutils Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

101 File operations

gluonfileutilsparse_version(version)Attempts to parse SemVer fallbacks on legacy

gluonfileutilsread_file(filename mode=rsquorrsquo)Returns content from filename making sure to close the file explicitly on exit

gluonfileutilswrite_file(filename value mode=rsquowrsquo)Writes ltvaluegt to filename making sure to close the file explicitly on exit

gluonfileutilsreadlines_file(filename mode=rsquorrsquo)Applies split(lsquo lsquo) to the output of read_file()

gluonfileutilsup(path)

gluonfileutilsabspath(relpath base)Converts relative path to absolute path based (by default) on applications_parent

gluonfileutilsmktree(path)

gluonfileutilslistdir(path expression=rsquo^+$rsquo drop=True add_dirs=False sort=Truemaxnum=None exclude_content_from=None)

Like oslistdir() but you can specify a regex pattern to filter files If add_dirs is True the returned items willhave the full path

gluonfileutilsrecursive_unlink(f)Deletes f If itrsquos a folder also its contents will be deleted

gluonfileutilscleanpath(path)Turns any expressionpath into a valid filename replaces with _ and removes special characters

25

web2py Documentation Release 2146-stable

gluonfileutilstar(file dir expression=rsquo^+$rsquo filenames=None exclude_content_from=None)Tars dir into file only tars file that match expression

gluonfileutilsuntar(file dir)Untar file into dir

gluonfileutilstar_compiled(file dir expression=rsquo^+$rsquo exclude_content_from=None)Used to tar a compiled application The content of models views controllers is not stored in the tar file

gluonfileutilsget_session(request other_application=rsquoadminrsquo)Checks that user is authorized to access other_application

gluonfileutilscheck_credentials(request other_application=rsquoadminrsquo expiration=3600gae_login=True)

Checks that user is authorized to access other_application

gluonfileutilsw2p_pack(filename path compiled=False filenames=None)Packs a web2py application

Parameters

bull filename (str) ndash path to the resulting archive

bull path (str) ndash path to the application

bull compiled (bool) ndash if True packs the compiled version

bull filenames (list) ndash adds filenames to the archive

gluonfileutilsw2p_unpack(filename path delete_tar=True)

gluonfileutilsw2p_pack_plugin(filename path plugin_name)Packs the given plugin into a w2p file Will match files at

ltpathgtplugin_[name]ltpathgtplugin_[name]

gluonfileutilsw2p_unpack_plugin(filename path delete_tar=True)

gluonfileutilsfix_newlines(path)

gluonfileutilsmake_fake_file_like_object()

26 Chapter 10 fileutils Module

CHAPTER 11

globals Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

Contains the classes for the global used variables

bull Request

bull Response

bull Session

class gluonglobalsRequest(env)Bases gluonstorageStorage

Defines the request object and the default values of its members

bull env environment variables by gluonmainwsgibase()

bull cookies

bull get_vars

bull post_vars

bull vars

bull folder

bull application

bull function

bull args

bull extension

bull now datetimedatetimenow()

27

web2py Documentation Release 2146-stable

bull utcnow datetimedatetimeutcnow()

bull is_local

bull is_https

bull restful()

body

compute_uuid()

get_varsLazily parses the query string into get_vars

parse_all_vars()Merges get_vars and post_vars to vars

parse_get_vars()Takes the QUERY_STRING and unpacks it to get_vars

parse_post_vars()Takes the body of the request and unpacks it into post_vars applicationjson is also automatically parsed

post_varsLazily parse the body into post_vars

requires_https()If request comes in over HTTP redirects it to HTTPS and secures the session

restful()

user_agent()

uuidLazily uuid

varsLazily parses all get_vars and post_vars to fill vars

class gluonglobalsResponseBases gluonstorageStorage

Defines the response object and the default values of its members responsewrite( ) can be used to write in theoutput html

download(request db chunk_size=65536 attachment=True download_filename=None)Example of usage in controller

def download()return responsedownload(request db)

Downloads from http downloadfilename

include_files(extensions=None)Includes files (usually in the head) Can minify and cache local files By default caches in ram for 5minutes To change responsecache_includes = (cache_method time_expire) Example (cachedisk 60) caches to disk for 1 minute

include_meta()

json(data default=None)

render(a b)

28 Chapter 11 globals Module

web2py Documentation Release 2146-stable

stream(stream chunk_size=65536 request=None attachment=False filename=None)If in a controller function

return responsestream(file 100)

the file content will be streamed at 100 bytes at the time

Parameters

bull stream ndash filename or read()able content

bull chunk_size (int) ndash Buffer size

bull request ndash the request object

bull attachment (bool) ndash prepares the correct headers to download the file as an attach-ment Usually creates a pop-up download window on browsers

bull filename (str) ndash the name for the attachment

Note for using the stream name (filename) with attachments the option must be explicitly set as functionparameter (will default to the last request argument otherwise)

toolbar()

write(data escape=True)

xmlrpc(request methods)assuming

def add(a b)return a+b

if a controller function ldquofuncrdquo

return responsexmlrpc(request [add])

the controller will be able to handle xmlrpc requests for the add function Example

import xmlrpclibconnection = xmlrpclibServerProxy(

httphostnameappcontrfunc)print connectionadd(3 4)

class gluonglobalsSessionBases gluonstorageStorage

Defines the session object and the default values of its members (None)

bull session_storage_type lsquofilersquo lsquodbrsquo or lsquocookiersquo

bull session_cookie_compression_level

bull session_cookie_expires cookie expiration

bull session_cookie_key for encrypted sessions in cookies

bull session_id a number or None if no session

bull session_id_name

bull session_locked

29

web2py Documentation Release 2146-stable

bull session_masterapp

bull session_new a new session obj is being created

bull session_hash hash of the pickled loaded session

bull session_pickled picked session

if session in cookie

bull session_data_name name of the cookie for session data

if session in db

bull session_db_record_id

bull session_db_table

bull session_db_unique_key

if session in file

bull session_file

bull session_filename

clear()rarr None Remove all items from D

clear_session_cookies()

connect(request=None response=None db=None tablename=rsquoweb2py_sessionrsquo master-app=None migrate=True separate=None check_client=False cookie_key=Nonecookie_expires=None compression_level=None)

Used in models allows to customize Session handling

Parameters

bull request ndash the request object

bull response ndash the response object

bull db ndash to storeretrieve sessions in db (a table is created)

bull tablename (str) ndash table name

bull masterapp (str) ndash points to anotherrsquos app sessions This enables a ldquoSSOrdquo environmentamong apps

bull migrate ndash passed to the underlying db

bull separate ndash with True creates a folder with the 2 initials of the session id Can also bea function eg

separate=lambda(session_name) session_name[-2]

bull check_client ndash if True sessions can only come from the same ip

bull cookie_key (str) ndash secret for cookie encryption

bull cookie_expires ndash sets the expiration of the cookie

bull compression_level (int) ndash 0-9 sets zlib compression on the data before the en-cryption

forget(response=None)

is_expired(seconds=3600)

is_new()

30 Chapter 11 globals Module

web2py Documentation Release 2146-stable

renew(clear_session=False)

save_session_id_cookie()

secure()

31

web2py Documentation Release 2146-stable

32 Chapter 11 globals Module

CHAPTER 12

highlight Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

gluonhighlighthighlight(code language link=rsquoexamplesglobalsvarsrsquo counter=1styles=None highlight_line=None context_lines=None at-tributes=None)

33

web2py Documentation Release 2146-stable

34 Chapter 12 highlight Module

CHAPTER 13

html Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

131 Template helpers

class gluonhtmlA(components attributes)Bases gluonhtmlDIV

Generates an A() link A() in web2py is really important and with the included web2pyjs allows lots of Ajaxinteractions in the page

On top of ldquousualrdquo _attributes it takes

Parameters

bull callback ndash an url to call but not redirect to

bull cid ndash if you want to load the _href into an element of the page (component) pass its id(without the ) here

bull delete ndash element to delete after calling callback

bull target ndash same thing as cid

bull confirm ndash text to display upon a callback with a delete

bull noconfirm ndash donrsquot display alert upon a callback with delete

tag = a

xml()generates the xml for this component

gluonhtmlASSIGNJS(kargs)

35

web2py Documentation Release 2146-stable

Example

ASSIGNJS(var1=lsquo1rsquo var2=lsquo2rsquo) will return the following javascript variables assignations

var var1 = ldquo1rdquo var var2 = ldquo2rdquo

Parameters kargs ndash Any keywords arguments and assigned values

Returns Javascript vars assignations for the keyvalue passed

class gluonhtmlB(components attributes)Bases gluonhtmlDIV

tag = b

class gluonhtmlBEAUTIFY(component attributes)Bases gluonhtmlDIV

Turns any list dictionary etc into decent looking html

Two special attributes are

bull sorted a function that takes the dict and returned sorted keys

bull keyfilter a function that takes a key and returns its representation or None if the key is to be skipped Bydefault key[1]==rsquo_rsquo is skipped

Examples

gtgtgt BEAUTIFY([a b hello world])xml()ltdivgtlttablegtlttrgtlttdgtltdivgtaltdivgtlttdgtlttrgtlttrgtlttdgtltdivgtbltdivgtlttdgtlttrgtlttrgtlttdgtrarr˓ltdivgtlttablegtlttrgtlttd style=font-weightboldvertical-aligntopgthellolttdgtlttdrarr˓style=vertical-aligntopgtlttdgtlttdgtltdivgtworldltdivgtlttdgtlttrgtlttablegtltdivgtltrarr˓tdgtlttrgtlttablegtltdivgt

static no_underscore(key)

tag = div

class gluonhtmlBODY(components attributes)Bases gluonhtmlDIV

tag = body

class gluonhtmlBR(components attributes)Bases gluonhtmlDIV

tag = br

class gluonhtmlBUTTON(components attributes)Bases gluonhtmlDIV

tag = button

class gluonhtmlCENTER(components attributes)Bases gluonhtmlDIV

tag = center

class gluonhtmlCAT(components attributes)Bases gluonhtmlDIV

tag =

36 Chapter 13 html Module

web2py Documentation Release 2146-stable

class gluonhtmlCODE(components attributes)Bases gluonhtmlDIV

Displays code in HTML with syntax highlighting

Parameters

bull language ndash indicates the language otherwise PYTHON is assumed

bull link ndash can provide a link

bull styles ndash for styles

Examples

=CODE(ldquoprint lsquohello worldrsquordquo language=rsquopythonrsquo link=None counter=1 styles= high-light_line=None)

supported languages are

ldquopythonrdquo ldquohtml_plainrdquo ldquocrdquo ldquocpprdquo ldquoweb2pyrdquo ldquohtmlrdquo

The ldquohtmlrdquo language interprets and tags as ldquoweb2pyrdquo code ldquohtml_plainrdquo doesnrsquot

if a link=rsquoexamplesglobalvarsrsquo is provided web2py keywords are linked to the online docs

the counter is used for line numbering counter can be None or a prompt string

xml()generates the xml for this component

class gluonhtmlCOL(components attributes)Bases gluonhtmlDIV

tag = col

class gluonhtmlCOLGROUP(components attributes)Bases gluonhtmlDIV

tag = colgroup

class gluonhtmlDIV(components attributes)Bases gluonhtmlXmlComponent

HTML helper for easy generating and manipulating a DOM structure Little or no validation is done

Behaves like a dictionary regarding updating of attributes Behaves like a list regarding insertingappendingcomponents

Examples

gtgtgt DIV(hello world _style=colorred)xml()ltdiv style=colorredgthelloworldltdivgt

All other HTML helpers are derived from DIV

_something=rdquovaluerdquo attributes are transparently translated into something=rdquovaluerdquo HTML attributes

append(value)list style appending of components

Examples

131 Template helpers 37

web2py Documentation Release 2146-stable

gtgtgt a=DIV()gtgtgt aappend(SPAN(x))gtgtgt print altdivgtltspangtxltspangtltdivgt

element(args kargs)Finds the first component that matches the supplied attribute dictionary or None if nothing could be found

Also the components of the components are searched

elements(args kargs)Find all components that match the supplied attribute dictionary or None if nothing could be found

All components of the components are searched

Examples

gtgtgt a = DIV(DIV(SPAN(x)3DIV(SPAN(y))))gtgtgt for c in aelements(span first_only=True) c[0]=zgtgtgt print altdivgtltdivgtltspangtzltspangt3ltdivgtltspangtyltspangtltdivgtltdivgtltdivgtgtgtgt for c in aelements(span) c[0]=zgtgtgt print altdivgtltdivgtltspangtzltspangt3ltdivgtltspangtzltspangtltdivgtltdivgtltdivgt

It also supports a syntax compatible with jQuery

Examples

gtgtgt a=TAG(ltdivgtltspangtlta id=1-1 uv=$gthelloltagtltspangtltp class=this is ararr˓testgtworldltpgtltdivgt)gtgtgt for e in aelements(div a1-1 pis) print eflatten()helloworldgtgtgt for e in aelements(1-1) print eflatten()hellogtgtgt aelements(a[uv=$])[0]xml()lta id=1-1 uv=$gthelloltagtgtgtgt a=FORM( INPUT(_type=text) SELECT(range(1)) TEXTAREA() )gtgtgt for c in aelements(input select textarea) c[_disabled] = disabledrarr˓gtgtgt axml()ltform action= enctype=multipartform-data method=postgtltinput disabled=rarr˓disabled type=text gtltselect disabled=disabledgtltoption value=0gt0ltrarr˓optiongtltselectgtlttextarea cols=40 disabled=disabled rows=10gtltrarr˓textareagtltformgt

Elements that are matched can also be replaced or removed by specifying a ldquoreplacerdquo argument (note alist of the original matching elements is still returned as usual)

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=abc) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(spanabc replace=P(x _class=xyz))gtgtgt print a We should xml() here instead of printltdivgtltdivgtltp class=xyzgtxltpgtltdivgtltp class=xyzgtxltpgtltp class=xyzgtxltpgtltrarr˓divgtltdivgtltdivgt

38 Chapter 13 html Module

web2py Documentation Release 2146-stable

ldquoreplacerdquo can be a callable which will be passed the original element and should return a new element toreplace it

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=abc) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(spanabc replace=lambda el P(el[0] _class=xyz))gtgtgt print altdivgtltdivgtltp class=xyzgtxltpgtltdivgtltp class=xyzgtyltpgtltp class=xyzgtzltpgtltrarr˓divgtltdivgtltdivgt

If replace=None matching elements will be removed completely

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=abc) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(span find=y replace=None)gtgtgt print altdivgtltdivgtltspan class=abcgtxltspangtltdivgtltspan class=abcgtzltspangtltdivgtltrarr˓divgtltdivgt

If a ldquofind_textrdquo argument is specified elements will be searched for text components that match find_textand any matching text components will be replaced (find_text is ignored if ldquoreplacerdquo is not also specified)Like the ldquofindrdquo argument ldquofind_textrdquo can be a string or a compiled regex

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=abc) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(find_text=recompile(x|y|z) replace=hello)gtgtgt print altdivgtltdivgtltspan class=abcgthelloltspangtltdivgtltspan class=abcgthelloltspangtrarr˓ltspan class=abcgthelloltspangtltdivgtltdivgtltdivgt

If other attributes are specified along with find_text then only components that match the specified at-tributes will be searched for find_text

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=efg) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(spanefg find_text=recompile(x|y|z) replace=hello)gtgtgt print altdivgtltdivgtltspan class=abcgtxltspangtltdivgtltspan class=efggthelloltspangtltspanrarr˓class=abcgtzltspangtltdivgtltdivgtltdivgt

flatten(render=None)Returns the text stored by the DIV object rendered by the render function the render function must taketext tagname and attributes render=None is equivalent to render=lambda text tag attr text

Examples

gtgtgt markdown = lambda text tag=None attributes=rarr˓None resub(s+ text) h1+text+nnrarr˓ ptext+nget(tagtext)gtgtgt a=TAG(lth1gtHeaderlth1gtltpgtthis is a testltpgt)gtgtgt aflatten(markdown)Headernnthis is a testn

131 Template helpers 39

web2py Documentation Release 2146-stable

get(i)

insert(i value)List-style inserting of components

Examples

gtgtgt a=DIV()gtgtgt ainsert(0 SPAN(x))gtgtgt print altdivgtltspangtxltspangtltdivgt

regex_attr = lt_sreSRE_Pattern objectgt

regex_class = lt_sreSRE_Pattern objectgt

regex_id = lt_sreSRE_Pattern objectgt

regex_tag = lt_sreSRE_Pattern objectgt

sibling(args kargs)Finds the first sibling component that match the supplied argument list and attribute dictionary or None ifnothing could be found

siblings(args kargs)Finds all sibling components that match the supplied argument list and attribute dictionary or None ifnothing could be found

tag = div

update(kargs)dictionary like updating of the tag attributes

xml()generates the xml for this component

class gluonhtmlEM(components attributes)Bases gluonhtmlDIV

tag = em

class gluonhtmlEMBED(components attributes)Bases gluonhtmlDIV

tag = embed

class gluonhtmlFIELDSET(components attributes)Bases gluonhtmlDIV

tag = fieldset

class gluonhtmlFORM(components attributes)Bases gluonhtmlDIV

Examples

gtgtgt from validators import IS_NOT_EMPTYgtgtgt form=FORM(INPUT(_name=test requires=IS_NOT_EMPTY()))gtgtgt formxml()ltform action= enctype=multipartform-data method=postgtltinput name=testrarr˓type=text gtltformgt

a FORM is container for INPUT TEXTAREA SELECT and other helpers

form has one important method

40 Chapter 13 html Module

web2py Documentation Release 2146-stable

formaccepts(requestvars session)

if form is accepted (and all validators pass) formvars contains the accepted vars otherwise formerrors containsthe errors in case of errors the form is modified to present the errors to the user

REDIRECT_JS = windowlocation=sreturn false

accepts(request_vars session=None formname=rsquodefaultrsquo keepvalues=False onvalidation=Nonehideerror=False kwargs)

kwargs is not used but allows to specify the same interface for FORM and SQLFORM

add_button(value url _class=None)

as_dict(flat=False sanitize=True)EXPERIMENTAL

Sanitize is naive It should catch any unsafe value for client retrieval

as_json(sanitize=True)

as_xml(sanitize=True)

as_yaml(sanitize=True)

assert_status(status request_vars)

static confirm(text=rsquoOKrsquo buttons=None hidden=None)

hidden_fields()

process(kwargs)Perform the validate() method but returns the form

Usage in controllers

directly on returndef action()

some code herereturn dict(form=FORM()process())

You can use it with FORM SQLFORM or FORM based plugins

responseflash messagesdef action()

form = SQLFORM(dbtable)process(message_onsuccess=Sucess)return dict(form=form)

callback function callback receives True or False as first arg and a list of argsdef my_callback(status msg)

responseflash = Success +msg if status else Errors occured

after argument can be flash to responseflash messages or a function name to use as callback or None to do nothingdef action()

return dict(form=SQLFORM(dbtable)process(onsuccess=my_callback)

tag = form

validate(kwargs)This function validates the form you can use it instead of directly formaccepts

Usage In controller

131 Template helpers 41

web2py Documentation Release 2146-stable

def action()form=FORM(INPUT(_name=test requires=IS_NOT_EMPTY()))formvalidate() you can pass some args here - see belowreturn dict(form=form)

This can receive a bunch of arguments

onsuccess = lsquoflashrsquo - will show message_onsuccess in responseflash None - will do nothing can be afunction (lambda form pass)

onfailure = lsquoflashrsquo - will show message_onfailure in responseflash None - will do nothing can be afunction (lambda form pass)

onchange = lsquoflashrsquo - will show message_onchange in responseflash None - will do nothing can be afunction (lambda form pass)

message_onsuccess message_onfailure message_onchange next = where to redirect in case of success anyother kwargs will be passed for formaccepts( )

xml()generates the xml for this component

class gluonhtmlH1(components attributes)Bases gluonhtmlDIV

tag = h1

class gluonhtmlH2(components attributes)Bases gluonhtmlDIV

tag = h2

class gluonhtmlH3(components attributes)Bases gluonhtmlDIV

tag = h3

class gluonhtmlH4(components attributes)Bases gluonhtmlDIV

tag = h4

class gluonhtmlH5(components attributes)Bases gluonhtmlDIV

tag = h5

class gluonhtmlH6(components attributes)Bases gluonhtmlDIV

tag = h6

class gluonhtmlHEAD(components attributes)Bases gluonhtmlDIV

tag = head

class gluonhtmlHR(components attributes)Bases gluonhtmlDIV

tag = hr

class gluonhtmlHTML(components attributes)Bases gluonhtmlDIV

42 Chapter 13 html Module

web2py Documentation Release 2146-stable

There are four predefined document type definitions They can be specified in the lsquodoctypersquo parameter

bull lsquostrictrsquo enables strict doctype

bull lsquotransitionalrsquo enables transitional doctype (default)

bull lsquoframesetrsquo enables frameset doctype

bull lsquohtml5rsquo enables HTML 5 doctype

bull any other string will be treated as userrsquos own doctype

lsquolangrsquo parameter specifies the language of the document Defaults to lsquoenrsquo

See also DIV

frameset = ltDOCTYPE HTML PUBLIC -W3CDTD HTML 401 FramesetEN httpwwww3orgTRhtml4framesetdtdgtn

html5 = ltDOCTYPE HTMLgtn

strict = ltDOCTYPE HTML PUBLIC -W3CDTD HTML 401EN httpwwww3orgTRhtml4strictdtdgtn

tag = html

transitional = ltDOCTYPE HTML PUBLIC -W3CDTD HTML 401 TransitionalEN httpwwww3orgTRhtml4loosedtdgtn

xml()generates the xml for this component

class gluonhtmlI(components attributes)Bases gluonhtmlDIV

tag = i

class gluonhtmlIFRAME(components attributes)Bases gluonhtmlDIV

tag = iframe

class gluonhtmlIMG(components attributes)Bases gluonhtmlDIV

tag = img

class gluonhtmlINPUT(components attributes)Bases gluonhtmlDIV

INPUT Component

Takes two special attributes value= and requires=

Parameters

bull value ndash used to pass the initial value for the input field value differs from _value becauseit works for checkboxes radio textarea and selectoption too For a checkbox value shouldbe lsquorsquo or lsquoonrsquo For a radio or selectoption value should be the _value of the checkedselecteditem

bull requires ndash should be None or a validator or a list of validators for the value of the field

Examples

gtgtgt INPUT(_type=text _name=name value=Max)xml()ltinput name=name type=text value=Max gt

gtgtgt INPUT(_type=checkbox _name=checkbox value=on)xml()ltinput checked=checked name=checkbox type=checkbox value=on gt

131 Template helpers 43

web2py Documentation Release 2146-stable

gtgtgt INPUT(_type=radio _name=radio _value=yes value=yes)xml()ltinput checked=checked name=radio type=radio value=yes gt

gtgtgt INPUT(_type=radio _name=radio _value=no value=yes)xml()ltinput name=radio type=radio value=no gt

tag = input

xml()generates the xml for this component

class gluonhtmlLABEL(components attributes)Bases gluonhtmlDIV

tag = label

class gluonhtmlLEGEND(components attributes)Bases gluonhtmlDIV

tag = legend

class gluonhtmlLI(components attributes)Bases gluonhtmlDIV

tag = li

class gluonhtmlLINK(components attributes)Bases gluonhtmlDIV

tag = link

class gluonhtmlOL(components attributes)Bases gluonhtmlUL

tag = ol

class gluonhtmlUL(components attributes)Bases gluonhtmlDIV

UL Component

If subcomponents are not LI-components they will be wrapped in a LI

tag = ul

class gluonhtmlMARKMIN(text extra=None allowed=None sep=rsquoprsquo url=None environ-ment=None latex=rsquogooglersquo autolinks=rsquodefaultrsquo protolinks=rsquodefaultrsquoclass_prefix=rdquo id_prefix=rsquomarkmin_rsquo kwargs)

Bases gluonhtmlXmlComponent

For documentation httpweb2pycomexamplesstaticmarkminhtml

flatten()

xml()

class gluonhtmlMENU(data args)Bases gluonhtmlDIV

Used to build menus

Parameters

bull _class ndash defaults to lsquoweb2py-menu web2py-menu-verticalrsquo

bull ul_class ndash defaults to lsquoweb2py-menu-verticalrsquo

44 Chapter 13 html Module

web2py Documentation Release 2146-stable

bull li_class ndash defaults to lsquoweb2py-menu-expandrsquo

bull li_first ndash defaults to lsquoweb2py-menu-firstrsquo

bull li_last ndash defaults to lsquoweb2py-menu-lastrsquo

Use like

menu = MENU([[name False URL() [submenu]] ])=menu

serialize(data level=0)

serialize_mobile(data select=None prefix=rdquo)

tag = ul

xml()generates the xml for this component

class gluonhtmlMETA(components attributes)Bases gluonhtmlDIV

tag = meta

class gluonhtmlOBJECT(components attributes)Bases gluonhtmlDIV

tag = object

class gluonhtmlOPTION(components attributes)Bases gluonhtmlDIV

tag = option

class gluonhtmlP(components attributes)Bases gluonhtmlDIV

Will replace n by ltbr gt if the cr2br attribute is provided

see also DIV

tag = p

xml()generates the xml for this component

class gluonhtmlPRE(components attributes)Bases gluonhtmlDIV

tag = pre

class gluonhtmlSCRIPT(components attributes)Bases gluonhtmlDIV

tag = script

xml()generates the xml for this component

class gluonhtmlOPTGROUP(components attributes)Bases gluonhtmlDIV

tag = optgroup

131 Template helpers 45

web2py Documentation Release 2146-stable

class gluonhtmlSELECT(components attributes)Bases gluonhtmlINPUT

Examples

gtgtgt from validators import IS_IN_SETgtgtgt SELECT(yes no _name=selector value=yes requires=IS_IN_SET([yes no]))xml()ltselect name=selectorgtltoption selected=selected value=yesgtyesltoptiongtrarr˓ltoption value=nogtnoltoptiongtltselectgt

tag = select

class gluonhtmlSPAN(components attributes)Bases gluonhtmlDIV

tag = span

class gluonhtmlSTRONG(components attributes)Bases gluonhtmlDIV

tag = strong

class gluonhtmlSTYLE(components attributes)Bases gluonhtmlDIV

tag = style

xml()generates the xml for this component

class gluonhtmlTABLE(components attributes)Bases gluonhtmlDIV

TABLE Component

If subcomponents are not TRTBODYTHEADTFOOT-components they will be wrapped in a TR

tag = table

gluonhtmlTAGTAG factory

Examples

gtgtgt print TAGfirst(TAGsecond(test) _key = 3)ltfirst key=3gtltsecondgttestltsecondgtltfirstgt

class gluonhtmlTD(components attributes)Bases gluonhtmlDIV

tag = td

class gluonhtmlTEXTAREA(components attributes)Bases gluonhtmlINPUT

Examples

TEXTAREA(_name=sometext value=blah 100 requires=IS_NOT_EMPTY())

lsquoblah blah blah rsquo will be the content of the textarea field

tag = textarea

46 Chapter 13 html Module

web2py Documentation Release 2146-stable

class gluonhtmlTH(components attributes)Bases gluonhtmlDIV

tag = th

class gluonhtmlTHEAD(components attributes)Bases gluonhtmlDIV

tag = thead

class gluonhtmlTBODY(components attributes)Bases gluonhtmlDIV

tag = tbody

class gluonhtmlTFOOT(components attributes)Bases gluonhtmlDIV

tag = tfoot

class gluonhtmlTITLE(components attributes)Bases gluonhtmlDIV

tag = title

class gluonhtmlTR(components attributes)Bases gluonhtmlDIV

TR Component

If subcomponents are not TDTH-components they will be wrapped in a TD

tag = tr

class gluonhtmlTT(components attributes)Bases gluonhtmlDIV

tag = tt

gluonhtmlURL(a=None c=None f=None r=None args=None vars=None an-chor=rdquo extension=None env=None hmac_key=None hash_vars=Truesalt=None user_signature=None scheme=None host=None port=None en-code_embedded_slash=False url_encode=True language=None)

generates a url lsquoacfrsquo corresponding to application a controller c and function f If r=request is passed a c fare set respectively to rapplication rcontroller rfunction

The more typical usage is

URL(lsquoindexrsquo)

that generates a url for the index function within the present application and controller

Parameters

bull a ndash application (default to current if r is given)

bull c ndash controller (default to current if r is given)

bull f ndash function (default to current if r is given)

bull r ndash request (optional)

bull args ndash any arguments (optional) Additional ldquopathrdquo elements

bull vars ndash any variables (optional) Querystring elements

bull anchor ndash anchorname without (optional)

131 Template helpers 47

web2py Documentation Release 2146-stable

bull extension ndash force an extension

bull hmac_key ndash key to use when generating hmac signature (optional)

bull hash_vars ndash which of the vars to include in our hmac signature True (default) - hash allvars False - hash none of the vars iterable - hash only the included vars [lsquokey1rsquorsquokey2rsquo]

bull salt ndash salt hashing with this string

bull user_signature ndash signs automatically the URL in such way that only the user canaccess the URL (use with URLverify or authrequires_signature())

bull scheme ndash URI scheme (True lsquohttprsquo or lsquohttpsrsquo etc) forces absolute URL (optional)

bull host ndash string to force absolute URL with host (True means http_host)

bull port ndash optional port number (forces absolute URL)

bull encode_embedded_slash ndash encode slash characters included in args

bull url_encode ndash encode characters included in vars

Raises SyntaxError ndash when no application controller or function is available or when a CRLFis found in the generated url

Examples

gtgtgt str(URL(a=a c=c f=f args=[x y z] vars=p1 q2 anchor=1))acfxyzp=1ampq=21

gtgtgt str(URL(a=a c=c f=f args=[x y z] vars=p(13) q2 anchor=1))acfxyzp=1ampp=3ampq=21

gtgtgt str(URL(a=a c=c f=f args=[x y z] vars=p(31) q2 anchor=1))acfxyzp=3ampp=1ampq=21

gtgtgt str(URL(a=a c=c f=f anchor=1+2))acf12B2

gtgtgt str(URL(a=a c=c f=f args=[x y z] vars=p(13) q2 anchor=1 hmac_key=key))acfxyzp=1ampp=3ampq=2amp_signature=a32530f0d0caa80964bb92aad2bedf8a4486a31f1

gtgtgt str(URL(a=a c=c f=f args=[wx yz]))acfwxyz

gtgtgt str(URL(a=a c=c f=f args=[wx yz] encode_embedded_slash=True))acfw2Fxy2Fz

gtgtgt str(URL(a=a c=c f=f args=[(id)d] url_encode=False))acf(id)d

gtgtgt str(URL(a=a c=c f=f args=[(id)d] url_encode=True))acf2528id29d

48 Chapter 13 html Module

web2py Documentation Release 2146-stable

gtgtgt str(URL(a=a c=c f=f vars=id (id)d url_encode=False))acfid=(id)d

gtgtgt str(URL(a=a c=c f=f vars=id (id)d url_encode=True))acfid=2528id29d

gtgtgt str(URL(a=a c=c f=f anchor=(id)d url_encode=False))acf(id)d

gtgtgt str(URL(a=a c=c f=f anchor=(id)d url_encode=True))acf2528id29d

class gluonhtmlXHTML(components attributes)Bases gluonhtmlDIV

This is XHTML version of the HTML helper

There are three predefined document type definitions They can be specified in the lsquodoctypersquo parameter

bull lsquostrictrsquo enables strict doctype

bull lsquotransitionalrsquo enables transitional doctype (default)

bull lsquoframesetrsquo enables frameset doctype

bull any other string will be treated as userrsquos own doctype

lsquolangrsquo parameter specifies the language of the document and the xml document Defaults to lsquoenrsquo

lsquoxmlnsrsquo parameter specifies the xml namespace Defaults to lsquohttpwwww3org1999xhtmlrsquo

See also DIV

frameset = ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 FramesetEN httpwwww3orgTRxhtml1DTDxhtml1-framesetdtdgtn

strict = ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgtn

tag = html

transitional = ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 TransitionalEN httpwwww3orgTRxhtml1DTDxhtml1-transitionaldtdgtn

xml()generates the xml for this component

xmlns = httpwwww3org1999xhtml

class gluonhtmlXML(text sanitize=False permitted_tags=[rsquoarsquo rsquobrsquo rsquoblockquotersquo rsquobrrsquo rsquoirsquo rsquolirsquo rsquoolrsquorsquoulrsquo rsquoprsquo rsquocitersquo rsquocodersquo rsquoprersquo rsquoimgrsquo rsquoh1rsquo rsquoh2rsquo rsquoh3rsquo rsquoh4rsquo rsquoh5rsquo rsquoh6rsquo rsquotablersquo rsquotrrsquorsquotdrsquo rsquodivrsquo rsquostrongrsquo rsquospanrsquo] allowed_attributes=rsquoarsquo [rsquohrefrsquo rsquotitlersquo rsquotargetrsquo]rsquoblockquotersquo [rsquotypersquo] rsquoimgrsquo [rsquosrcrsquo rsquoaltrsquo] rsquotdrsquo [rsquocolspanrsquo])

Bases gluonhtmlXmlComponent

use it to wrap a string that contains XMLHTML so that it will not be escaped by the template

Examples

gtgtgt XML(lth1gtHellolth1gt)xml()lth1gtHellolth1gt

elements(args kargs)to be considered experimental since the behavior of this method is questionable another option could beTAG(selftext)elements(args kwargs)

131 Template helpers 49

web2py Documentation Release 2146-stable

flatten(render=None)returns the text stored by the XML object rendered by the render function

xml()

gluonhtmlxmlescape(data quote=True)Returns an escaped string of the provided data

Parameters

bull data ndash the data to be escaped

bull quote ndash optional (default False)

gluonhtmlembed64(filename=None file=None data=None extension=rsquoimagegifrsquo)helper to encode the provided (binary) data into base64

Parameters

bull filename ndash if provided opens and reads this file in lsquorbrsquo mode

bull file ndash if provided reads this file

bull data ndash if provided uses the provided data

50 Chapter 13 html Module

CHAPTER 14

http Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

141 HTTP statuses helpers

exception gluonhttpHTTP(status body=rdquo cookies=None headers)Bases exceptionsException

Raises an HTTP response

Parameters

bull status ndash usually an integer If itrsquos a well known status code the ERROR message will beautomatically added A string can also be passed as 510 Foo Bar and in that case the statuscode and the error message will be parsed accordingly

bull body ndash what to return as body If left as is will return the error code and the status messagein the body itself

bull cookies ndash pass cookies along (usually not needed)

bull headers ndash pass headers as usual dict mapping

cookies2headers(cookies)

messagecompose a message describing this exception

ldquostatus defined_status [web2py_error]rdquo

message elements that are not defined are omitted

to(responder env=None)

51

web2py Documentation Release 2146-stable

gluonhttpredirect(location=rdquo how=303 client_side=False headers=None)Raises a redirect (303)

Parameters

bull location ndash the url where to redirect

bull how ndash what HTTP status code to use when redirecting

bull client_side ndash if set to True it triggers a reload of the entire page when the fragmenthas been loaded as a component

52 Chapter 14 http Module

CHAPTER 15

languages Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)Plural subsystem is created by Vladyslav Kozlovskyy (Ukraine) ltdbdevelopgmailcomgt

151 Translation system

class gluonlanguagestranslator(langpath http_accept_language)Bases object

This class is instantiated by gluoncompileappbuild_environment as the T object

Example

Tforce(None) turns off translation Tforce(lsquofr itrsquo) forces web2py to translate using frpy or itpy

T(ldquoHello Worldrdquo) translates ldquoHello Worldrdquo using the selected file

Note

bull there is no need to force since by default T uses http_accept_language to determine a translation file

bull en and en-en are considered different languages

bull if language xx-yy is not found force() probes other similar languages using such algorithm xx-yypy -gtxxpy -gt xx-yypy -gt xxpy

M(message symbols= language=None lazy=None filter=None ftag=None ns=None)Gets cached translated markmin-message with inserted parametes if lazy==True lazyT object is returned

apply_filter(message symbols= filter=None ftag=None)

53

web2py Documentation Release 2146-stable

force(languages)Selects language(s) for translation

if a list of languages is passed as a parameter the first language from this list that matches the ones fromthe possible_languages dictionary will be selected

default language will be selected if none of them matches possible_languages

get_possible_languages()Gets list of all possible languages for current application

get_possible_languages_info(lang=None)Returns info for selected language or dictionary with all possible languages info from APPlanguagespyIt Returns

bull a tuple containing

langcode langname langfile_mtimepluraldict_fname pluraldict_mtimeprules_langcode npluralsget_plural_id construct_plural_form

or None

bull if lang is NOT defined a dictionary with all possible languages

langcode(from filename)( langcode language code from langcodelangname

language name in national spelling from langnamelangfile_mtime m_time of language filepluraldict_fname name of plural dictionary file or None (when

rarr˓defaultpy is not exist)pluraldict_mtime m_time of plural dictionary file or 0 if file is

rarr˓not existprules_langcode code of plural rules language or defaultnplurals nplurals for current languageget_plural_id get_plural_id() for current languageconstruct_plural_form) construct_plural_form() for current

rarr˓language

Parameters lang (str) ndash language

get_t(message prefix=rdquo)Use to add a comment into a translation string the comment can be useful do discriminate differentpossible translations for the same string (for example different locations)

T( hello world ) -gt hello world T( hello world token) -gt hello world T(hello world token) -gt hello world

the notation is ignored in multiline strings and strings that start with This is needed to allow markminsyntax to be translated

params_substitution(message symbols)Substitutes parameters from symbols into message using also parse placeholders for plural-formsprocessing

Returns string with parameters

54 Chapter 15 languages Module

web2py Documentation Release 2146-stable

Note symbols MUST BE OR tuple OR dict of parameters

plural(word n)Gets plural form of word for number n invoked from T()TM() in tag

Note ldquowordrdquo MUST be defined in current language (Taccepted_language)

Parameters

bull word (str) ndash word in singular

bull n (numeric) ndash number plural form created for

Returns word in appropriate singularplural form

Return type word (str)

set_current_languages(languages)Sets current AKA ldquodefaultrdquo languages Setting one of this languages makes the force() function to turntranslation off

translate(message symbols)Gets cached translated message with inserted parameters(symbols)

gluonlanguagesfindT(path language=rsquoenrsquo)

Note Must be run by the admin app

gluonlanguagesupdate_all_languages(application_path)

Note Must be run by the admin app

151 Translation system 55

web2py Documentation Release 2146-stable

56 Chapter 15 languages Module

CHAPTER 16

main Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

161 The gluon wsgi application

gluonmainwsgibase(environ responder)The gluon wsgi application The first function called when a page is requested (static or dynamic) It can becalled by pastehttpserver or by apache mod_wsgi (or any WSGI-compatible server)

bull fills request with info

bull the environment variables replacing lsquorsquo with lsquo_rsquo

bull adds web2py path and version info

bull compensates for fcgi missing path_info and query_string

bull validates the path in url

The url path must be either

1 for static pages

bull ltapplicationgtstaticltfilegt

2 for dynamic pages

bull ltapplicationgt[ltcontrollergt[ltfunctiongt[ltsubgt]]][ltextensiongt]

The naming conventions are

bull application controller function and extension may only contain [a-zA-Z0-9_]

57

web2py Documentation Release 2146-stable

bull file and sub may also contain lsquo-lsquo lsquo=rsquo lsquorsquo and lsquorsquo

gluonmainsave_password(password port)Used by main() to save the password in the parameters_portpy file

gluonmainappfactory(wsgiapp=ltfunction wsgibasegt logfilename=rsquohttpserverlogrsquo pro-filer_dir=None profilerfilename=None)

generates a wsgi application that does logging and profiling and calls wsgibase

Parameters

bull wsgiapp ndash the base application

bull logfilename ndash where to store apache-compatible requests log

bull profiler_dir ndash where to store profile files

class gluonmainHttpServer(ip=rsquo127001rsquo port=8000 password=rdquopid_filename=rsquohttpserverpidrsquo log_filename=rsquohttpserverlogrsquoprofiler_dir=None ssl_certificate=None ssl_private_key=Nonessl_ca_certificate=None min_threads=None max_threads=Noneserver_name=None request_queue_size=5 timeout=10socket_timeout=1 shutdown_timeout=None path=None inter-faces=None)

Bases object

the web2py web server (Rocket)

start()start the web server

stop(stoplogging=False)stop cron and the web server

58 Chapter 16 main Module

CHAPTER 17

messageboxhandler Module

class gluonmessageboxhandlerMessageBoxHandlerBases loggingHandler

emit(record)Do whatever it takes to actually log the specified logging record

This version is intended to be implemented by subclasses and so raises a NotImplementedError

class gluonmessageboxhandlerNotifySendHandlerBases loggingHandler

emit(record)Do whatever it takes to actually log the specified logging record

This version is intended to be implemented by subclasses and so raises a NotImplementedError

59

web2py Documentation Release 2146-stable

60 Chapter 17 messageboxhandler Module

CHAPTER 18

myregex Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

181 Useful regexes

61

web2py Documentation Release 2146-stable

62 Chapter 18 myregex Module

CHAPTER 19

newcron Module

This file is part of the web2py Web FrameworkCreated by Attila Csipa ltweb2pycsipainrsgtModified by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

Cron-style interface

class gluonnewcronToken(path)Bases object

acquire(startup=False)Returns the time when the lock is acquired or None if cron already running

lock is implemented by writing a pickle (start stop) in cronmaster start is time when cron job starts andstop is time when cron completed stop == 0 if job started but did not yet complete if a cron job startedwithin less than 60 seconds acquire returns None if a cron job started before 60 seconds and did not stopa warning is issue ldquoStale cronmaster detectedrdquo

release()Writes into cronmaster the time when cron job was completed

gluonnewcronabsolute_path_link(path)Returns an absolute path for the destination of a symlink

gluonnewcroncrondance(applications_parent ctype=rsquosoftrsquo startup=False apps=None)

class gluonnewcroncronlauncher(cmd shell=True)Bases threadingThread

run()Method representing the threadrsquos activity

You may override this method in a subclass The standard run() method invokes the callable object passedto the objectrsquos constructor as the target argument if any with sequential and keyword arguments takenfrom the args and kwargs arguments respectively

63

web2py Documentation Release 2146-stable

class gluonnewcronextcron(applications_parent apps=None)Bases threadingThread

run()Method representing the threadrsquos activity

You may override this method in a subclass The standard run() method invokes the callable object passedto the objectrsquos constructor as the target argument if any with sequential and keyword arguments takenfrom the args and kwargs arguments respectively

class gluonnewcronhardcron(applications_parent)Bases threadingThread

launch()

run()Method representing the threadrsquos activity

You may override this method in a subclass The standard run() method invokes the callable object passedto the objectrsquos constructor as the target argument if any with sequential and keyword arguments takenfrom the args and kwargs arguments respectively

gluonnewcronparsecronline(line)

gluonnewcronrangetolist(s period=rsquominrsquo)

class gluonnewcronsoftcron(applications_parent)Bases threadingThread

run()Method representing the threadrsquos activity

You may override this method in a subclass The standard run() method invokes the callable object passedto the objectrsquos constructor as the target argument if any with sequential and keyword arguments takenfrom the args and kwargs arguments respectively

gluonnewcronstopcron()Graceful shutdown of cron

64 Chapter 19 newcron Module

CHAPTER 20

portalocker Module

Cross-platform (posixnt) API for flock-style file locking

Synopsis

import portalockerfile = open(somefile r+)portalockerlock(file portalockerLOCK_EX)fileseek(12)filewrite(foo)fileclose()

If you know what yoursquore doing you may choose to

portalockerunlock(file)

before closing the file but why

Methods

lock( file flags )unlock( file )

Constants

LOCK_EXLOCK_SHLOCK_NB

I learned the win32 technique for locking files from sample code provided by John Nielsen ltnielsenjfmy-dejacomgtin the documentation that accompanies the win32 modules

Author Jonathan Feinberg ltjdfpoboxcomgt Version $Id portalockerpyv 13 20010529 184755 AdministratorExp $

class gluonportalockerLockedFile(filename mode=rsquorbrsquo)Bases object

65

web2py Documentation Release 2146-stable

close()

read(size=None)

readline()

readlines()

write(data)

gluonportalockerlock(file flags)

gluonportalockerread_locked(filename)

gluonportalockerunlock(file)

gluonportalockerwrite_locked(filename data)

66 Chapter 20 portalocker Module

CHAPTER 21

recfile Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

211 Generates names for cache and session files

gluonrecfileexists(filename path=None)

gluonrecfilegenerate(filename depth=2 base=512)

gluonrecfileopen(filename mode=rsquorrsquo path=None)

gluonrecfileremove(filename path=None)

67

web2py Documentation Release 2146-stable

68 Chapter 21 recfile Module

CHAPTER 22

restricted Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

221 Restricted environment to execute applicationrsquos code

exception gluonrestrictedRestrictedError(layer=rdquo code=rdquo output=rdquo environ-ment=None)

Bases exceptionsException

Class used to wrap an exception that occurs in the restricted environment below The traceback is used to logthe exception and generate a ticket

load(request app ticket_id)Loads a logged exception

log(request)Logs the exception

gluonrestrictedrestricted(code environment=None layer=rsquoUnknownrsquo)Runs code in environment and returns the output If an exception occurs in code it raises a RestrictedErrorcontaining the traceback Layer is passed to RestrictedError to identify where the error occurred

class gluonrestrictedTicketStorage(db=None tablename=rsquoweb2py_ticketrsquo)Bases gluonstorageStorage

Defines the ticket object and the default values of its members (None)

load(request app ticket_id)

store(request ticket_id ticket_data)Stores the ticket It will figure out if this must be on disk or in db

gluonrestrictedcompile2(code layer)The +n is necessary else compile fails when code ends in a comment

69

web2py Documentation Release 2146-stable

70 Chapter 22 restricted Module

CHAPTER 23

rewrite Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

gluonrewrite parses incoming URLs and formats outgoing URLs for gluonhtmlURL

In addition it rewrites both incoming and outgoing URLs based on the (optional) user-supplied routespy which alsoallows for rewriting of certain error messages

routespy supports two styles of URL rewriting depending on whether lsquoroutersrsquo is defined Refer to routerexamplepyand routesexamplepy for additional documentation

class gluonrewriteMapUrlIn(request=None env=None)Bases object

Logic for mapping incoming URLs

arg0Returns first arg

harg0Returns first arg with optional hyphen mapping

map_app()Determines application name

map_controller()Identifies controller

map_function()Handles functionextension

map_language()Handles language (no hyphen mapping)

71

web2py Documentation Release 2146-stable

map_prefix()Strips path prefix if present in its entirety

map_root_static()Handles root-static files (no hyphen mapping)

a root-static file is one whose incoming URL expects it to be at the root typically robotstxt amp faviconico

map_static()Handles static files file_match but no hyphen mapping

pop_arg_if(dopop)Conditionally removes first arg and returns new first arg

sluggify()

update_request()Updates request from self Builds envrequest_uri Makes lower-case versions of http headers in env

validate_args()Checks args against validation pattern

class gluonrewriteMapUrlOut(request env application controller function args other schemehost port language)

Bases object

Logic for mapping outgoing URLs

acf()Converts components to applangcontrollerfunction

build_acf()Builds acf from components

omit_acf()Omits what we can of acf

omit_lang()Omits language if possible

gluonrewritecompile_regex(k v env=None)Preprocess and compile the regular expressions in routes_appinout The resulting regex will match a pattern ofthe form

[remote address][protocol][host][method] [path]

We allow abbreviated regexes on input here we try to complete them

gluonrewritefilter_err(status application=rsquoapprsquo ticket=rsquotktrsquo)doctestunittest interface to routes_onerror

gluonrewritefilter_url(url method=rsquogetrsquo remote=rsquo0000rsquo out=False app=False lang=Nonedomain=(None None) env=False scheme=None host=Noneport=None language=None)

doctestunittest interface to regex_filter_in() and regex_filter_out()

gluonrewritefixup_missing_path_info(environ)

gluonrewriteget_effective_router(appname)Returns a private copy of the effective router for the specified application

gluonrewriteinvalid_url(routes)

72 Chapter 23 rewrite Module

web2py Documentation Release 2146-stable

gluonrewriteload(routes=rsquoroutespyrsquo app=None data=None rdict=None)load read (if file) and parse routes store results in params (called from mainpy at web2py initialization time)If data is present itrsquos used instead of the routespy contents If rdict is present it must be a dict to be used forrouters (unit test)

gluonrewriteload_routers(all_apps)Load-time post-processing of routers

gluonrewritelog_rewrite(string)Log rewrite activity under control of routespy

gluonrewritemap_url_in(request env app=False)Routes incoming URL

gluonrewritemap_url_out(request env application controller function args other scheme hostport language=None)

Supply acf (or alangcf) portion of outgoing url

The basic rule is that we can only make transformations that map_url_in can reverse

Suppose that the incoming arguments are acfargslang and that the router defaults are da dc df dl

We can perform these transformations trivially if args=[] and lang=None or dl

dadcdf =gt adcdf =gt aacdf =gt ac

We would also like to be able to strip the default application or applicationcontroller from URLs with func-tionargs present thus

dacfargs =gt cfargsdadcfargs =gt fargs

We use [applications] and [controllers] and functions to suppress ambiguous omissions

We assume that language names do not collide with acf names

gluonrewriteregex_filter_in(e)Regex rewrite incoming URL

gluonrewriteregex_filter_out(url e=None)Regex rewrite outgoing URL

gluonrewriteregex_select(env=None app=None request=None)Selects a set of regex rewrite params for the current request

gluonrewriteregex_uri(e regexes tag default=None)Filters incoming URI against a list of regexes

gluonrewriteregex_url_in(request environ)Rewrites and parses incoming URL

gluonrewritesluggify(key)

gluonrewritetry_redirect_on_error(http_object request ticket=None)Called from mainwsgibase to rewrite the http response

gluonrewritetry_rewrite_on_error(http_response request environ ticket=None)Called from mainwsgibase to rewrite the http response

gluonrewriteurl_in(request environ)Parses and rewrites incoming URL

73

web2py Documentation Release 2146-stable

gluonrewriteurl_out(request environ application controller function args other scheme hostport language=None)

Assembles and rewrites outgoing URL

74 Chapter 23 rewrite Module

CHAPTER 24

sanitizer Module

From httpaspnactivestatecomASPNCookbookPythonRecipe496942Submitter Josh Goldfoot (other recipes)Last Updated 20060805Version 10

241 Cross-site scripting (XSS) defense

gluonsanitizersanitize(text permitted_tags=[rsquoarsquo rsquobrsquo rsquoblockquotersquo rsquobrrsquo rsquoirsquo rsquolirsquo rsquoolrsquo rsquoulrsquorsquoprsquo rsquocitersquo rsquocodersquo rsquoprersquo rsquoimgrsquo rsquoh1rsquo rsquoh2rsquo rsquoh3rsquo rsquoh4rsquo rsquoh5rsquo rsquoh6rsquo rsquota-blersquo rsquotbodyrsquo rsquotheadrsquo rsquotfootrsquo rsquotrrsquo rsquotdrsquo rsquodivrsquo rsquostrongrsquo rsquospanrsquo] al-lowed_attributes=rsquoarsquo [rsquohrefrsquo rsquotitlersquo] rsquoblockquotersquo [rsquotypersquo] rsquoimgrsquo[rsquosrcrsquo rsquoaltrsquo] rsquotdrsquo [rsquocolspanrsquo] escape=True)

75

web2py Documentation Release 2146-stable

76 Chapter 24 sanitizer Module

CHAPTER 25

scheduler Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

251 Background processes made simple

class gluonschedulerJobGraph(db job_name)Bases object

Experimental dependencies amongs tasks

add_deps(task_parent task_child)Create a dependency between task_parent and task_child

validate(job_name=None)Validate if all tasks job_name can be completed

Checks if there are no mutual dependencies among tasks Commits at the end if successfull or it rollbacksthe entire transaction Handle with care

class gluonschedulerMetaSchedulerBases threadingThread

Base class documenting schedulerrsquos base methods

async(task)Start the background process

Parameters task ndash a Task object

Returns

containing

77

web2py Documentation Release 2146-stable

(okresultoutput)(errorexceptionNone)(timeoutNoneNone)(terminatedNoneNone)

Return type tuple

die()Forces termination of the worker process along with any running task

give_up()Waits for any running task to be executed then exits the worker process

loop()Main loop fetching tasks and starting executorrsquos background processes

pop_task()Fetches a task ready to be executed

report_task(task task_report)Creates a task report

run()This is executed by the main thread to send heartbeats

send_heartbeat(counter)

sleep()

start_heartbeats()

terminate_process()Terminates any running tasks (internal use only)

class gluonschedulerScheduler(db tasks=None migrate=True worker_name=Nonegroup_names=None heartbeat=3 max_empty_runs=0discard_results=False utc_time=False)

Bases gluonschedulerMetaScheduler

Scheduler object

Parameters

bull db ndash DAL connection where Scheduler will create its tables

bull tasks (dict) ndash either a dict containing namendashgtfunc or None If None functions will besearched in the environment

bull migrate (bool) ndash turn migration onoff for the Schedulerrsquos tables

bull worker_name (str) ndash force worker_name to identify each process Leave it to None toautoassign a name (hostnamepid)

bull group_names (list) ndash process tasks belonging to this group defaults to [lsquomainrsquo] if noth-ing gets passed

bull heartbeat (int) ndash how many seconds the worker sleeps between one execution and thefollowing one Indirectly sets how many seconds will pass between checks for new tasks

bull max_empty_runs (int) ndash how many loops are allowed to pass without processing anytasks before exiting the process 0 to keep always the process alive

78 Chapter 25 scheduler Module

web2py Documentation Release 2146-stable

bull discard_results (bool) ndash Scheduler stores executionsrsquos details into the sched-uler_run table By default only if there is a result the details are kept Turning this toTrue means discarding results even for tasks that return something

bull utc_time (bool) ndash do all datetime calculations assuming UTC as the timezone Remem-ber to pass start_time and stop_time to tasks accordingly

adj_hibernation()Used to increase the ldquosleeprdquo interval for DISABLED workers

assign_tasks(db)Assign task to workers that can then pop them from the queue

Deals with group_name(s) logic in order to assign linearly tasks to available workers for those groups

being_a_ticker()Elect a TICKER process that assigns tasks to available workers

Does its best to elect a worker that is not busy processing other tasks to allow a proper distribution of tasksamong all active workers ASAP

define_tables(db migrate)Define Scheduler tables structure

disable(group_names=None limit=None worker_name=None)Set DISABLED on the workers processing group_names tasks

A DISABLED worker will be kept alive but it wonrsquot be able to process any waiting tasks essentiallyputting it to sleep By default all group_names of Schedulerrsquos instantation are selected

get_workers(only_ticker=False)Returns a dict holding worker_name columns representing all ldquoregisteredrdquo workers only_ticker re-turns only the workers running as a TICKER if there are any

kill(group_names=None limit=None worker_name=None)Sets KILL as worker status The worker will be killed even if itrsquos processing a task

loop(worker_name=None)Main loop

This works basically as a neverending loop that

bull checks if the worker is ready to process tasks (is not DISABLED)

bull pops a task from the queue

bull if there is a task

ndash spawns the executor background process

ndash waits for the process to be finished

ndash sleeps heartbeat seconds

bull if there is not a task

ndash checks for max_empty_runs

ndash sleeps heartbeat seconds

now()Shortcut that fetches current time based on UTC preferences

pop_task(db)Grab a task ready to be executed from the queue

251 Background processes made simple 79

web2py Documentation Release 2146-stable

queue_task(function pargs=[] pvars= kwargs)Queue tasks This takes care of handling the validation of all parameters

Parameters

bull function ndash the function (anything callable with a __name__)

bull pargs ndash ldquorawrdquo args to be passed to the function Automatically jsonified

bull pvars ndash ldquorawrdquo kwargs to be passed to the function Automatically jsonified

bull kwargs ndash all the parameters available (basically every scheduler_task column) If argsand vars are here they should be jsonified already and they will override pargs and pvars

Returns a dict just as a normal validate_and_insert() plus a uuid key holding the uuid of thequeued task If validation is not passed ( ie some parameters are invalid) both id and uuidwill be None and yoursquoll get an ldquoerrorrdquo dict holding the errors found

report_task(task task_report)Take care of storing the result according to preferences

Deals with logic for repeating tasks

resume(group_names=None limit=None worker_name=None)Wakes a worker up (it will be able to process queued tasks)

send_heartbeat(counter)Coordination among available workers

It - sends the heartbeat - elects a ticker among available workers (the only process that

effectively dispatch tasks to workers)

bull deals with workerrsquos statuses

bull does ldquohousecleaningrdquo for dead workers

bull triggers tasks assignment to workers

set_requirements(scheduler_task)Called to set defaults for lazy_tables connections

set_worker_status(group_names=None action=rsquoACTIVErsquo exclude=None limit=Noneworker_name=None)

Internal function to set workerrsquos status

sleep()Calculate the number of seconds to sleep

stop_task(ref)Shortcut for task termination

If the task is RUNNING it will terminate it meaning that status will be set as FAILED

If the task is QUEUED its stop_time will be set as to ldquonowrdquo the enabled flag will be set to False andthe status to STOPPED

Parameters ref ndash can be

bull an integer lookup will be done by scheduler_taskid

bull a string lookup will be done by scheduler_taskuuid

Returns

bull 1 if task was stopped (meaning an update has been done)

80 Chapter 25 scheduler Module

web2py Documentation Release 2146-stable

bull None if task was not found or if task was not RUNNING or QUEUED

Note Experimental

task_status(ref output=False)Retrieves task status and optionally the result of the task

Parameters

bull ref ndash can be

ndash an integer lookup will be done by scheduler_taskid

ndash a string lookup will be done by scheduler_taskuuid

ndash a Query lookup as you wish eg

dbscheduler_tasktask_name == test1

bull output (bool) ndash if True fetch also the scheduler_run record

Returns a single Row object for the last queued task If output == True returns also the lastscheduler_run record The scheduler_run record is fetched by a left join so it can have allfields == None

terminate(group_names=None limit=None worker_name=None)Sets TERMINATE as worker status The worker will wait for any currently running tasks to be executedand then it will exit gracefully

static total_seconds(td)Backport for py26

update_dependencies(db task_id)Unblock execution paths for Jobs

wrapped_assign_tasks(db)Commodity function to call assign_tasks and trap exceptions

If an exception is raised assume it happened because of database contention and retries assign_task after05 seconds

wrapped_pop_task()Commodity function to call pop_task and trap exceptions

If an exception is raised assume it happened because of database contention and retries pop_task after 05seconds

wrapped_report_task(task task_report)Commodity function to call report_task and trap exceptions

If an exception is raised assume it happened because of database contention and retries pop_task after 05seconds

class gluonschedulerTYPE(myclass=lttype rsquolistrsquogt parse=False)Bases object

Validator that checks whether field is valid json and validates its type Used for args and vars of the sched-uler_task table

class gluonschedulerTask(app function timeout args=rsquo[]rsquo vars=rsquorsquo kwargs)Bases object

251 Background processes made simple 81

web2py Documentation Release 2146-stable

Defines a ldquotaskrdquo object that gets passed from the main thread to the executorrsquos one

class gluonschedulerTaskReport(status result=None output=None tb=None)Bases object

Defines a ldquotask reportrdquo object that gets passed from the executorrsquos thread to the main one

gluonschedulerexecutor(queue task out)The function used to execute tasks in the background process

gluonschedulermain()allows to run worker without python web2pypy by simply

python gluonschedulerpy

82 Chapter 25 scheduler Module

CHAPTER 26

serializers Module

This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

gluonserializerscast_keys(o cast=lttype rsquostrrsquogt encoding=rsquoutf-8rsquo)Builds a new object with ltcastgt type keys Use this function if you are in Python lt 265 This avoids syntaxerrors when unpacking dictionary arguments

Parameters

bull o ndash is the object input

bull cast ndash (defaults to str) is an object type or function which supports conversion such as

converted = cast(o)

bull encoding ndash (defaults to utf-8) is the encoding for unicode keys This is not used forcustom cast functions

gluonserializerscsv(value)

gluonserializerscustom_json(o)

gluonserializersics(events title=None link=None timeshift=0 calname=True ignored)

gluonserializersjson(value default=ltfunction custom_jsongt)

gluonserializersloads_json(o unicode_keys=True kwargs)

gluonserializersloads_yaml(data)

gluonserializersrss(feed)

gluonserializerssafe_encode(text)

gluonserializersxml(value encoding=rsquoUTF-8rsquo key=rsquodocumentrsquo quote=True)

gluonserializersxml_rec(value key quote=True)

gluonserializersyaml(data)

83

web2py Documentation Release 2146-stable

84 Chapter 26 serializers Module

CHAPTER 27

settings Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

85

web2py Documentation Release 2146-stable

86 Chapter 27 settings Module

CHAPTER 28

shell Module

This file is part of the web2py Web FrameworkDeveloped by Massimo Di Pierro ltmdipierrocsdepauledugtlimodou ltlimodougmailcomgt and srackham ltsrackhamgmailcomgtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

281 Web2py environment in the shell

gluonshelldie(msg)

gluonshellenable_autocomplete_and_history(adir env)

gluonshellenv(a import_models=False c=None f=None dir=rdquo extra_request=)Returns web2py execution environment for application (a) controller (c) function (f) If import_models is Truethe exec all application models into the environment

extra_request allows you to pass along any extra variables to the request object before your models get executedThis was mainly done to support web2py_utilstest_runner however you can use it with any wrapper scripts thatneed access to the web2py environment

gluonshellexec_environment(pyfile=rdquo request=None response=None session=None)Environment builder and module loader

Builds a web2py environment and optionally executes a Python file into the environment

A Storage dictionary containing the resulting environment is returned The working directory must be web2pyroot ndash this is the web2py default

gluonshellexec_pythonrc()

gluonshellexecute_from_command_line(argv=None)

gluonshellget_usage()

87

web2py Documentation Release 2146-stable

gluonshellparse_path_info(path_info av=False)Parses path info formatted like acf where c and f are optional and a leading is accepted Return tuple (a c f)If invalid path_info a is set to None If c or f are omitted they are set to None If av=True parse args and vars

gluonshellrun(appname plain=False import_models=False startfile=None bpython=Falsepython_code=False cronjob=False)

Start interactive shell or run Python script (startfile) in web2py controller environment appname is formattedlike

bull a web2py application name

bull ac exec the controller c into the application environment

gluonshelltest(testpath import_models=True verbose=False)Run doctests in web2py environment testpath is formatted like

bull a tests all controllers in application a

bull ac tests controller c in application a

bull acf test function f in controller c application a

Where a c and f are application controller and function names respectively If the testpath is a file name the fileis tested If a controller is specified models are executed by default

88 Chapter 28 shell Module

CHAPTER 29

sql Module

This file is part of the web2py Web FrameworkDeveloped by Massimo Di Pierro ltmdipierrocsdepauledugtlimodou ltlimodougmailcomgt and srackham ltsrackhamgmailcomgtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

291 Just for backward compatibility

class gluonsqlDAL(uri=rsquosqlitedummydbrsquo pool_size=0 folder=None db_codec=rsquoUTF-8rsquo check_reserved=None migrate=True fake_migrate=False mi-grate_enabled=True fake_migrate_all=False decode_credentials=Falsedriver_args=None adapter_args=None attempts=5 auto_import=False big-int_id=False debug=False lazy_tables=False db_uid=None do_connect=Trueafter_connection=None tables=None ignore_field_case=True en-tity_quoting=False table_hash=None)

Bases pydalhelpersclassesSerializable pydalhelpersclassesBasicStorage

An instance of this class represents a database connection

Parameters

bull uri (str) ndash contains information for connecting to a database Defaults tolsquosqlitedummydbrsquo

Note experimental you can specify a dictionary as uri parameter ie with

db = DAL(uri sqlitestoragesqlitetables )

for an example of dict input you can check the output of the scaffolding db model with

dbas_dict()

89

web2py Documentation Release 2146-stable

Note that for compatibility with Python older than version 265 you should cast your dictinput keys to str due to a syntax limitation on kwarg names for proper DAL dictionary inputyou can use one of

obj = serializerscast_keys(dict [encoding=utf-8])or else (for parsing json input)obj = serializersloads_json(data unicode_keys=False)

bull pool_size ndash How many open connections to make to the database object

bull folder ndash where table files will be created Automatically set within web2py Use anexplicit path when using DAL outside web2py

bull db_codec ndash string encoding of the database (default lsquoUTF-8rsquo)

bull table_hash ndash database identifier with tables If your connection hash change you canstill using old tables if they have db_hash as prefix

bull check_reserved ndash list of adapters to check tablenames and column names againstsqlnosql reserved keywords Defaults to None

ndash rsquocommonrsquo List of sql keywords that are common to all database types such as ldquoSELECTINSERTrdquo (recommended)

ndash rsquoallrsquo Checks against all known SQL keywords

ndash rsquoltadapternamegtrdquo Checks against the specific adapters list of keywords

ndash rsquoltadapternamegt_nonreservedrsquo Checks against the specific adapters list of nonreservedkeywords (if available)

bull migrate ndash sets default migrate behavior for all tables

bull fake_migrate ndash sets default fake_migrate behavior for all tables

bull migrate_enabled ndash If set to False disables ALL migrations

bull fake_migrate_all ndash If set to True fake migrates ALL tables

bull attempts ndash Number of times to attempt connecting

bull auto_import ndash If set to True tries import automatically table definitions from thedatabases folder (works only for simple models)

bull bigint_id ndash If set turn on bigint instead of int for id and reference fields

bull lazy_tables ndash delays table definition until table access

bull after_connection ndash can a callable that will be executed after the connection

Example

Use as

db = DAL(sqlitetestdb)

or

90 Chapter 29 sql Module

web2py Documentation Release 2146-stable

db = DAL(uri tables []) experimental

dbdefine_table(tablename Field(fieldname1)Field(fieldname2))

class Field(fieldname type=rsquostringrsquo length=None default=ltfunction ltlambdagtgt re-quired=False requires=ltfunction ltlambdagtgt ondelete=rsquoCASCADErsquo not-null=False unique=False uploadfield=True widget=None label=None com-ment=None writable=True readable=True update=None authorize=Noneautodelete=False represent=None uploadfolder=None uploadseparate=Falseuploadfs=None compute=None custom_store=None custom_retrieve=Nonecustom_retrieve_file_properties=None custom_delete=None filter_in=None fil-ter_out=None custom_qualifier=None map_none=None rname=None)

Bases pydalobjectsExpression pydalhelpersclassesSerializable

Lazyalias of FieldMethod

Methodalias of FieldMethod

Virtualalias of FieldVirtual

as_dict(flat=False sanitize=True)

clone(point_self_references_to=False args)

count(distinct=None)

formatter(value)

retrieve(name path=None nameonly=False)If nameonly==True return (filename fullfilename) instead of (filename stream)

retrieve_file_properties(name path=None)

set_attributes(args attributes)

sqlsafe

sqlsafe_name

store(file filename=None path=None)

validate(value)

class Row(args kwargs)Bases pydalhelpersclassesBasicStorage

A dictionary that lets you do d[lsquoarsquo] as well as da this is only used to store a Row

as_dict(datetime_to_str=False custom_types=None)

as_json(mode=rsquoobjectrsquo default=None colnames=None serialize=True kwargs)serializes the row to a JSON object kwargs are passed to as_dict method only ldquoobjectrdquo mode sup-ported

serialize = False used by Rowsas_json

TODO return array mode with query column order

mode and colnames are not implemented

as_xml(row_name=rsquorowrsquo colnames=None indent=rsquo rsquo)

291 Just for backward compatibility 91

web2py Documentation Release 2146-stable

get(key default=None)

class Table(db tablename fields args)Bases pydalhelpersclassesSerializable pydalhelpersclassesBasicStorage

Represents a database table

Example

You can create a table as db = DAL( ) dbdefine_table(lsquousersrsquo Field(lsquonamersquo))

And then

dbusersinsert(name=me) print dbusers_insert() to see SQLdbusersdrop()

as_dict(flat=False sanitize=True)

bulk_insert(items)here items is a list of dictionaries

drop(mode=rdquo)

fields

import_from_csv_file(csvfile id_map=None null=rsquoltNULLgtrsquo unique=rsquouuidrsquoid_offset=None args kwargs)

Import records from csv file Column headers must have same names as table fields Field lsquoidrsquo isignored If column names read lsquotablefilersquo the lsquotablersquo prefix is ignored

bull lsquouniquersquo argument is a field which must be unique (typically a uuid field)bull lsquorestorersquo argument is default False if set True will remove old values in table firstbull lsquoid_maprsquo if set to None will not map ids

The import will keep the id numbers in the restored table This assumes that there is an field of typeid that is integer and in incrementing order Will keep the id numbers in restored table

insert(fields)

on(query)

sqlsafe

sqlsafe_alias

truncate(mode=None)

update(args kwargs)

update_or_insert(_key=ltfunction ltlambdagtgt values)

validate_and_insert(fields)

validate_and_update(_key=ltfunction ltlambdagtgt fields)

validate_and_update_or_insert(_key=ltfunction ltlambdagtgt fields)

with_alias(alias)

as_dict(flat=False sanitize=True)

can_join()

check_reserved_keyword(name)Validates name against SQL keywords Uses selfcheck_reserve which is a list of operators to use

close()

92 Chapter 29 sql Module

web2py Documentation Release 2146-stable

commit()

define_table(tablename fields args)

static distributed_transaction_begin(instances)

static distributed_transaction_commit(instances)

executesql(query placeholders=None as_dict=False fields=None colnames=Noneas_ordered_dict=False)

Executes an arbitrary query

Parameters

bull query (str) ndash the query to submit to the backend

bull placeholders ndash is optional and will always be None If using raw SQL with place-holders placeholders may be a sequence of values to be substituted in or (if supported bythe DB driver) a dictionary with keys matching named placeholders in your SQL

bull as_dict ndash will always be None when using DAL If using raw SQL can be set to Trueand the results cursor returned by the DB driver will be converted to a sequence of dic-tionaries keyed with the db field names Results returned with as_dict=True are the sameas those returned when applying to_list() to a DAL query If ldquoas_ordered_dictrdquo=True thebehaviour is the same as when ldquoas_dictrdquo=True with the keys (field names) guaranteed tobe in the same order as returned by the select name executed on the database

bull fields ndash list of DAL Fields that match the fields returned from the DB The Field objectsshould be part of one or more Table objects defined on the DAL object The ldquofieldsrdquo listcan include one or more DAL Table objects in addition to or instead of including Fieldobjects or it can be just a single table (not in a list) In that case the Field objects will beextracted from the table(s)

Note if either fields or colnames is provided the results will be converted to a DAL Rowsobject using the db_adapterparse() method

bull colnames ndash list of field names in tablenamefieldname format

Note It is also possible to specify both ldquofieldsrdquo and the associated ldquocolnamesrdquo In that case ldquofieldsrdquocan also include DAL Expression objects in addition to Field objects For Field objects in ldquofieldsrdquo theassociated ldquocolnamesrdquo must still be in tablenamefieldname format For Expression objects in ldquofieldsrdquo theassociated ldquocolnamesrdquo can be any arbitrary labels

DAL Table objects referred to by ldquofieldsrdquo or ldquocolnamesrdquo can be dummy tables and do not have to representany real tables in the database Also note that the ldquofieldsrdquo and ldquocolnamesrdquo must be in the same order asthe fields in the results cursor returned from the DB

export_to_csv_file(ofile args kwargs)

static get_instances()Returns a dictionary with uri as key with timings and defined tables

sqlitestoragesqlite dbstats [(select auth_useremail from auth_user 002009)]dbtables

defined [auth_cas auth_event auth_groupauth_membership auth_permission auth_user]

(continues on next page)

291 Just for backward compatibility 93

web2py Documentation Release 2146-stable

(continued from previous page)

lazy []

has_representer(name)

import_from_csv_file(ifile id_map=None null=rsquoltNULLgtrsquo unique=rsquouuidrsquomap_tablenames=None ignore_missing_tables=False args kwargs)

import_table_definitions(path migrate=False fake_migrate=False tables=None)

lazy_define_table(tablename fields args)

logger = ltloggingLogger objectgt

parse_as_rest(patterns args vars queries=None nested_select=True)

Example

Use as

dbdefine_table(personField(name)Field(info))dbdefine_table(pet

Field(ownedbydbperson)Field(name)Field(info)

)

requestrestful()def index()

def GET(argsvars)patterns = [

friends[person]personnamefieldpersonnamepets[petownedby]personnamepets[petownedby]petnamepersonnamepets[petownedby]petnamefield(dogs[pet] dbpetinfo==dog)(dogs[pet]petnamestartswith dbpetinfo==dog)]

parser = dbparse_as_rest(patternsargsvars)if parserstatus == 200

return dict(content=parserresponse)else

raise HTTP(parserstatusparsererror)

def POST(table_namevars)if table_name == person

return dbpersonvalidate_and_insert(vars)elif table_name == pet

return dbpetvalidate_and_insert(vars)else

raise HTTP(400)return locals()

represent(name args kwargs)

representers = rows_render ltfunction represent at 0x7fcf10dcdb18gt rows_xml ltclass gluonsqlhtmlSQLTABLEgt

94 Chapter 29 sql Module

web2py Documentation Release 2146-stable

rollback()

serializers = json ltfunction custom_json at 0x7fcf11069488gt xml ltfunction xml at 0x7fcf11069578gt

static set_folder(folder)

smart_query(fields text)

tables

uuid()

validators = None

validators_method(field)Field type validation using web2pyrsquos validators mechanism

makes sure the content of a field is in line with the declared fieldtype

where(query=None ignore_common_filters=None)

class gluonsqlField(fieldname type=rsquostringrsquo length=None default=ltfunction ltlambdagtgtrequired=False requires=ltfunction ltlambdagtgt ondelete=rsquoCASCADErsquonotnull=False unique=False uploadfield=True widget=None label=Nonecomment=None writable=True readable=True update=None autho-rize=None autodelete=False represent=None uploadfolder=None upload-separate=False uploadfs=None compute=None custom_store=Nonecustom_retrieve=None custom_retrieve_file_properties=None cus-tom_delete=None filter_in=None filter_out=None custom_qualifier=Nonemap_none=None rname=None)

Bases pydalobjectsExpression pydalhelpersclassesSerializable

LazyRepresents a database field

Example

Usage

a = Field(name string length=32 default=None required=Falserequires=IS_NOT_EMPTY() ondelete=CASCADEnotnull=False unique=Falseuploadfield=True widget=None label=None comment=Noneuploadfield=True True means store on disk

a_field_name means store in this field in db False means file content will be discarded

writable=True readable=True update=None authorize=Noneautodelete=False represent=None uploadfolder=Noneuploadseparate=False upload to separate directories by uuid_keys

first 2 character and tablenamefieldname False - old behavior True - put uploaded file in ltuploaddirgtlttablenamegtltfieldnamegtuuid_key[2] directory)

uploadfs=None a pyfilesystem where to store upload)

to be used as argument of DALdefine_table

alias of FieldMethod

291 Just for backward compatibility 95

web2py Documentation Release 2146-stable

Methodalias of FieldMethod

Virtualalias of FieldVirtual

as_dict(flat=False sanitize=True)

clone(point_self_references_to=False args)

count(distinct=None)

formatter(value)

retrieve(name path=None nameonly=False)If nameonly==True return (filename fullfilename) instead of (filename stream)

retrieve_file_properties(name path=None)

set_attributes(args attributes)

sqlsafe

sqlsafe_name

store(file filename=None path=None)

validate(value)

96 Chapter 29 sql Module

CHAPTER 30

sqlhtml Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

Holds

bull SQLFORM provide a form for a table (withwithout record)

bull SQLTABLE provides a table for a set of records

bull form_factory provides a SQLFORM for an non-db backed table

class gluonsqlhtmlAutocompleteWidget(request field id_field=None db=None or-derby=None limitby=(0 10) distinct=False key-word=rsquo_autocomplete_(tablename)s_(fieldname)srsquomin_length=2 help_fields=Nonehelp_string=None at_beginning=True)

Bases object

callback()

class gluonsqlhtmlBooleanWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates an INPUT checkbox tag

see also FormWidgetwidget

class gluonsqlhtmlCacheRepresenterBases object

class gluonsqlhtmlCheckboxesWidgetBases gluonsqlhtmlOptionsWidget

classmethod widget(field value attributes)Generates a TABLE tag including INPUT checkboxes (multiple allowed)

97

web2py Documentation Release 2146-stable

see also FormWidgetwidget

class gluonsqlhtmlDateWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlDatetimeWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlDecimalWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlDoubleWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlExportClass(rows)Bases object

content_type = None

export()

file_ext = None

label = None

represented()

class gluonsqlhtmlExporterCSV(rows)Bases gluonsqlhtmlExportClass

content_type = textcsv

export()

file_ext = csv

label = CSV

class gluonsqlhtmlExporterCSV_hidden(rows)Bases gluonsqlhtmlExportClass

content_type = textcsv

export()

file_ext = csv

label = CSV

class gluonsqlhtmlExporterHTML(rows)Bases gluonsqlhtmlExportClass

content_type = texthtml

export()

file_ext = html

label = HTML

class gluonsqlhtmlExporterJSON(rows)Bases gluonsqlhtmlExportClass

content_type = applicationjson

export()

file_ext = json

98 Chapter 30 sqlhtml Module

web2py Documentation Release 2146-stable

label = JSON

class gluonsqlhtmlExporterTSV(rows)Bases gluonsqlhtmlExportClass

content_type = texttab-separated-values

export()

file_ext = csv

label = TSV

class gluonsqlhtmlExporterXML(rows)Bases gluonsqlhtmlExportClass

content_type = textxml

export()

file_ext = xml

label = XML

class gluonsqlhtmlFormWidgetBases object

Helper for SQLFORM to generate form input fields (widget) related to the fieldtype

classmethod widget(field value attributes)Generates the widget for the field

When serialized will provide an INPUT tag

bull id = tablename_fieldname

bull class = fieldtype

bull name = fieldname

Parameters

bull field ndash the field needing the widget

bull value ndash value

bull attributes ndash any other attributes to be applied

class gluonsqlhtmlIntegerWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlJSONWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates a TEXTAREA for JSON notation

see also FormWidgetwidget

class gluonsqlhtmlListWidgetBases gluonsqlhtmlStringWidget

classmethod widget(field value attributes)Generates an INPUT text tag

see also FormWidgetwidget

99

web2py Documentation Release 2146-stable

class gluonsqlhtmlMultipleOptionsWidgetBases gluonsqlhtmlOptionsWidget

classmethod widget(field value size=5 attributes)Generates a SELECT tag including OPTIONs (multiple options allowed)

see also FormWidgetwidget

Parameters size ndash optional param (default=5) to indicate how many rows must be shown

class gluonsqlhtmlOptionsWidgetBases gluonsqlhtmlFormWidget

static has_options(field)Checks if the field has selectable options

Parameters field ndash the field needing checking

Returns True if the field has options

classmethod widget(field value attributes)Generates a SELECT tag including OPTIONs (only 1 option allowed)

see also FormWidgetwidget

class gluonsqlhtmlPasswordWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates a INPUT password tag If a value is present it will be shown as a number of lsquorsquo not related tothe length of the actual value

see also FormWidgetwidget

class gluonsqlhtmlRadioWidgetBases gluonsqlhtmlOptionsWidget

classmethod widget(field value attributes)Generates a TABLE tag including INPUT radios (only 1 option allowed)

see also FormWidgetwidget

class gluonsqlhtmlSQLFORM(table record=None deletable=False linkto=None upload=Nonefields=None labels=None col3= submit_button=rsquoSubmitrsquodelete_label=rsquoCheck to deletersquo showid=True readonly=False com-ments=True keepopts=[] ignore_rw=False record_id=Noneformstyle=None buttons=[rsquosubmitrsquo] separator=None ex-tra_fields=None attributes)

Bases gluonhtmlFORM

SQLFORM is used to map a table (and a current record) into an HTML form

Given a Table like dbtable

Generates an insert form

SQLFORM(dbtable)

Generates an update form

record=dbtable[some_id]SQLFORM(dbtable record)

Generates an update with a delete button

100 Chapter 30 sqlhtml Module

web2py Documentation Release 2146-stable

SQLFORM(dbtable record deletable=True)

Parameters

bull table ndash Table object

bull record ndash either an int if the id is an int or the record fetched from the table

bull deletable ndash adds the delete checkbox

bull linkto ndash the URL of a controllerfunction to access referencedby records

bull upload ndash the URL of a controllerfunction to download an uploaded file

bull fields ndash a list of fields that should be placed in the form default is all

bull labels ndash a dictionary with labels for each field keys are the field names

bull col3 ndash a dictionary with content for an optional third column (right of each field) keys arefield names

bull submit_button ndash text to show in the submit button

bull delete_label ndash text to show next to the delete checkbox

bull showid ndash shows the id of the record

bull readonly ndash doesnrsquot allow for any modification

bull comments ndash show comments (stored in col3 or in Field definition)

bull ignore_rw ndash overrides readablewritable attributes

bull record_id ndash used to create session key against CSRF

bull formstyle ndash what to use to generate the form layout

bull buttons ndash override buttons as you please (will be also stored in formcustomsubmit)

bull separator ndash character as separator between labels and inputs

any named optional attribute is passed to the ltformgt tag for example _class _id _style _action _method etc

AUTOTYPES = lttype intgt (integer ltgluonvalidatorsIS_INT_IN_RANGE object at 0x7fcf10deb210gt) lttype floatgt (double ltgluonvalidatorsIS_FLOAT_IN_RANGE object at 0x7fcf10deb250gt) lttype unicodegt (string None) lttype boolgt (boolean None) lttype strgt (string None) lttype listgt (liststring None) lttype datetimedatetimegt (datetime ltgluonvalidatorsIS_DATETIME object at 0x7fcf10deb310gt) lttype datetimedategt (date ltgluonvalidatorsIS_DATE object at 0x7fcf10deb2d0gt)

FIELDKEY_DELETE_RECORD = delete_record

FIELDNAME_REQUEST_DELETE = delete_this_record

ID_LABEL_SUFFIX = __label

ID_ROW_SUFFIX = __row

accepts(request_vars session=None formname=rsquo(tablename)s(record_id)srsquo keepvalues=Noneonvalidation=None dbio=True hideerror=False detect_record_change=False kwargs)

Similar to FORMaccepts but also does insert update or delete in DAL If detect_record_change is Truethan

bull formrecord_changed = False (record is properly validatedsubmitted)

bull formrecord_changed = True (record cannot be submitted because changed)

If detect_record_change == False than

bull formrecord_changed = None

assert_status(status request_vars)

101

web2py Documentation Release 2146-stable

static build_query(fields keywords)

createform(xfields)

static dictform(dictionary kwargs)

static factory(fields attributes)Generates a SQLFORM for the given fields

Internally will build a non-database based data model to hold the fields

formstyles = bootstrap ltfunction formstyle_bootstrap at 0x7fcf10de99b0gt bootstrap3_inline ltfunction _inner at 0x7fcf10de9b90gt bootstrap3_stacked ltfunction formstyle_bootstrap3_stacked at 0x7fcf10de9a28gt divs ltfunction formstyle_divs at 0x7fcf10de9848gt inline ltfunction formstyle_inline at 0x7fcf10de98c0gt table2cols ltfunction formstyle_table2cols at 0x7fcf10de97d0gt table3cols ltfunction formstyle_table3cols at 0x7fcf10dcdde8gt ul ltfunction formstyle_ul at 0x7fcf10de9938gt

static grid(query fields=None field_id=None left=None headers= or-derby=None groupby=None searchable=True sortable=True pagi-nate=20 deletable=True editable=True details=True selectable=None cre-ate=True csv=True links=None links_in_grid=True upload=rsquoltdefaultgtrsquoargs=[] user_signature=True maxtextlengths= maxtextlength=20 on-validation=None onfailure=None oncreate=None onupdate=None on-delete=None sorter_icons=(ltgluonhtmlXML objectgt ltgluonhtmlXMLobjectgt) ui=rsquoweb2pyrsquo showbuttontext=True _class=rsquoweb2py_gridrsquo form-name=rsquoweb2py_gridrsquo search_widget=rsquodefaultrsquo advanced_search=True ig-nore_rw=False formstyle=None exportclasses=None formargs= cre-ateargs= editargs= viewargs= selectable_submit_button=rsquoSubmitrsquobuttons_placement=rsquorightrsquo links_placement=rsquorightrsquo noconfirm=Falsecache_count=None client_side_delete=False ignore_common_filters=Noneauto_pagination=True use_cursor=False)

static search_menu(fields search_options=None prefix=rsquow2prsquo)

static smartdictform(session name filename=None query=None kwargs)

static smartgrid(table constraints=None linked_tables=None links=None links_in_grid=Trueargs=None user_signature=True divider=rsquogtrsquo breadcrumbs_class=rdquokwargs)

Builds a system of SQLFORMgrid(s) between any referenced tables

Parameters

bull table ndash main table

bull constraints (dict) ndash lsquotablersquoquery that limits which records can be accessible

bull links (dict) ndash like lsquotablenamersquo[lambda row A( ) ] that will add buttons whentable tablename is displayed

bull linked_tables (list) ndash list of tables to be linked

Example

given you defined a model as

dbdefine_table(person Field(name) format=(name)s)dbdefine_table(dog

Field(name) Field(owner dbperson) format=(name)s)dbdefine_table(comment Field(body) Field(dog dbdog))if db(dbperson)isempty()

from gluoncontribpopulate import populatepopulate(dbperson 300)populate(dbdog 300)populate(dbcomment 1000)

102 Chapter 30 sqlhtml Module

web2py Documentation Release 2146-stable

in a controller you can do

authrequires_login()def index()

form=SQLFORMsmartgrid(db[requestargs(0) or person])return dict(form=form)

widgets = autocomplete ltclass gluonsqlhtmlAutocompleteWidgetgt blob None boolean ltclass gluonsqlhtmlBooleanWidgetgt checkboxes ltclass gluonsqlhtmlCheckboxesWidgetgt date ltclass gluonsqlhtmlDateWidgetgt datetime ltclass gluonsqlhtmlDatetimeWidgetgt decimal ltclass gluonsqlhtmlDecimalWidgetgt double ltclass gluonsqlhtmlDoubleWidgetgt integer ltclass gluonsqlhtmlIntegerWidgetgt json ltclass gluonsqlhtmlJSONWidgetgt list ltclass gluonsqlhtmlListWidgetgt multiple ltclass gluonsqlhtmlMultipleOptionsWidgetgt options ltclass gluonsqlhtmlOptionsWidgetgt password ltclass gluonsqlhtmlPasswordWidgetgt radio ltclass gluonsqlhtmlRadioWidgetgt string ltclass gluonsqlhtmlStringWidgetgt text ltclass gluonsqlhtmlTextWidgetgt time ltclass gluonsqlhtmlTimeWidgetgt upload ltclass gluonsqlhtmlUploadWidgetgt

class gluonsqlhtmlSQLTABLE(sqlrows linkto=None upload=None orderby=None headers=truncate=16 columns=None th_link=rdquo extracolumns=None se-lectid=None renderstyle=False cid=None colgroup=False at-tributes)

Bases gluonhtmlTABLE

Given with a Rows object as returned by a db()select() generates an html table with the rows

Parameters

bull sqlrows ndash the Rows object

bull linkto ndash URL (or lambda to generate a URL) to edit individual records

bull upload ndash URL to download uploaded files

bull orderby ndash Add an orderby link to column headers

bull headers ndash dictionary of headers to headers redefinions headers can also be a string to gen-erate the headers from data for now only headers=rdquofieldnamecapitalizerdquo headers=rdquolabelsrdquoand headers=None are supported

bull truncate ndash length at which to truncate text in table cells Defaults to 16 characters

bull columns ndash a list or dict contaning the names of the columns to be shown Defaults to all

bull th_link ndash base link to support orderby headers

bull extracolumns ndash a list of dicts

bull selectid ndash The id you want to select

bull renderstyle ndash Boolean render the style with the table

bull cid ndash use this cid for all links

bull colgroup ndash FIXME

Extracolumns example

[labelA(Extra _href=)class class name of the headerwidth width in pixels or contentlambda row rc A(Edit _href=editsrowid)selected False agregate class selected to this column]

style()

class gluonsqlhtmlStringWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates an INPUT text tag

see also FormWidgetwidget

103

web2py Documentation Release 2146-stable

class gluonsqlhtmlTextWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates a TEXTAREA tag

see also FormWidgetwidget

class gluonsqlhtmlTimeWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlUploadWidgetBases gluonsqlhtmlFormWidget

DEFAULT_WIDTH = 150px

DELETE_FILE = delete

GENERIC_DESCRIPTION = file download

ID_DELETE_SUFFIX = __delete

static is_image(value)Tries to check if the filename provided references to an image

Checking is based on filename extension Currently recognized gif png jp(e)g bmp

Parameters value ndash filename

classmethod represent(field value download_url=None)How to represent the file

bull with download url and if it is an image ltA href= gtltIMG gtltAgt

bull otherwise with download url ltA href= gtfileltAgt

bull otherwise file

Parameters

bull field ndash the field

bull value ndash the field value

bull download_url ndash url for the file download (default = None)

classmethod widget(field value download_url=None attributes)generates a INPUT file tag

Optionally provides an A link to the file including a checkbox so the file can be deleted

All is wrapped in a DIV

see also FormWidgetwidget

Parameters

bull field ndash the field

bull value ndash the field value

bull download_url ndash url for the file download (default = None)

gluonsqlhtmladd_class(a b)

104 Chapter 30 sqlhtml Module

web2py Documentation Release 2146-stable

gluonsqlhtmlform_factory(fields attributes)Generates a SQLFORM for the given fields

Internally will build a non-database based data model to hold the fields

gluonsqlhtmlformstyle_bootstrap(form fields)bootstrap 23x format form layout

gluonsqlhtmlformstyle_bootstrap3_inline_factory(col_label_size=3)bootstrap 3 horizontal form layout

Note Experimental

gluonsqlhtmlformstyle_bootstrap3_stacked(form fields)bootstrap 3 format form layout

Note Experimental

gluonsqlhtmlformstyle_divs(form fields)divs only

gluonsqlhtmlformstyle_inline(form fields)divs only but inline

gluonsqlhtmlformstyle_table2cols(form fields)2 column table

gluonsqlhtmlformstyle_table3cols(form fields)3 column table - default

gluonsqlhtmlformstyle_ul(form fields)unordered list

gluonsqlhtmlrepresent(field value record)

gluonsqlhtmlsafe_float(x)

gluonsqlhtmlsafe_int(x)

gluonsqlhtmlshow_if(cond)

105

web2py Documentation Release 2146-stable

106 Chapter 30 sqlhtml Module

CHAPTER 31

storage Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

Provides

bull List like list but returns None instead of IndexOutOfBounds

bull Storage like dictionary allowing also for objfoo for obj[lsquofoorsquo]

class gluonstorageListBases list

Like a regular python list but callable When a(i) is called if i is out of bounds returns None instead of IndexError

class gluonstorageStorageBases dict

A Storage object is like a dictionary except objfoo can be used in addition to obj[lsquofoorsquo] and setting objfoo =None deletes item foo

Example

gtgtgt o = Storage(a=1)gtgtgt print oa1

gtgtgt o[a]1

gtgtgt oa = 2gtgtgt print o[a]2

gtgtgt del oa

(continues on next page)

107

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt print oaNone

getfirst(key default=None)Returns the first value of a list or the value itself when given a requestvars style key

If the value is a list its first item will be returned otherwise the value will be returned as-is

Example output for a query string of x=abcampy=abcampy=def

gtgtgt request = Storage()gtgtgt requestvars = Storage()gtgtgt requestvarsx = abcgtgtgt requestvarsy = [abc def]gtgtgt requestvarsgetfirst(x)abcgtgtgt requestvarsgetfirst(y)abcgtgtgt requestvarsgetfirst(z)

getlast(key default=None)Returns the last value of a list or value itself when given a requestvars style key

If the value is a list the last item will be returned otherwise the value will be returned as-is

Simulated output with a query string of x=abcampy=abcampy=def

gtgtgt request = Storage()gtgtgt requestvars = Storage()gtgtgt requestvarsx = abcgtgtgt requestvarsy = [abc def]gtgtgt requestvarsgetlast(x)abcgtgtgt requestvarsgetlast(y)defgtgtgt requestvarsgetlast(z)

getlist(key)Returns a Storage value as a list

If the value is a list it will be returned as-is If object is None an empty list will be returned Otherwise[value] will be returned

Example output for a query string of x=abcampy=abcampy=def

gtgtgt request = Storage()gtgtgt requestvars = Storage()gtgtgt requestvarsx = abcgtgtgt requestvarsy = [abc def]gtgtgt requestvarsgetlist(x)[abc]gtgtgt requestvarsgetlist(y)[abc def]gtgtgt requestvarsgetlist(z)[]

class gluonstorageSettingsBases gluonstorageStorage

108 Chapter 31 storage Module

web2py Documentation Release 2146-stable

class gluonstorageMessages(T)Bases gluonstorageSettings

class gluonstorageStorageListBases gluonstorageStorage

Behaves like Storage but missing elements defaults to [] instead of None

gluonstorageload_storage(filename)

gluonstoragesave_storage(storage filename)

109

web2py Documentation Release 2146-stable

110 Chapter 31 storage Module

CHAPTER 32

streamer Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

321 Facilities to handle file streaming

gluonstreamerstream_file_or_304_or_206(static_file chunk_size=65536 request=Noneheaders= status=200 error_message=None)

gluonstreamerstreamer(stream chunk_size=65536 bytes=None)

111

web2py Documentation Release 2146-stable

112 Chapter 32 streamer Module

CHAPTER 33

template Module

This file is part of the web2py Web FrameworkLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)Author Thadeus BurgessContributors- Massimo Di Pierro for creating the original gluontemplatepy- Jonathan Lundell for extensively testing the regex on Jython- Limodou (creater of uliweb) who inspired the block-element support for web2py

331 Templating syntax

class gluontemplateBlockNode(name=rdquo pre_extend=False delimiters=(rsquorsquo rsquorsquo))Bases gluontemplateNode

Block Container

This Node can contain other Nodes and will render in a hierarchical order of when nodes were added

ie

block test This is default block test

end

append(node)Adds an element to the nodes

Parameters node ndash Node object or string to append

extend(other)Extends the list of nodes with another BlockNode class

Parameters other ndash BlockNode or Content object to extend from

113

web2py Documentation Release 2146-stable

output(blocks)Merges all nodes into a single string

Parameters blocks ndash Dictionary of blocks that are extending from this template

class gluontemplateContent(name=rsquoContentBlockrsquo pre_extend=False)Bases gluontemplateBlockNode

Parent Container ndash Used as the root level BlockNode

Contains functions that operate as such

Parameters name ndash Unique name for this BlockNode

append(node)Adds a node to list If it is a BlockNode then we assign a block for it

clear_content()

extend(other)Extends the objects list of nodes with another objects nodes

insert(other index=0)Inserts object at index

You may pass a list of objects and have them inserted

class gluontemplateDummyResponse

write(data escape=True)

class gluontemplateNOESCAPE(text)A little helper to avoid escaping

xml()

class gluontemplateNode(value=None pre_extend=False)Bases object

Basic Container Object

class gluontemplateSuperNode(name=rdquo pre_extend=False)Bases gluontemplateNode

class gluontemplateTemplateParser(text name=rsquoParserContainerrsquo context=path=rsquoviewsrsquo writer=rsquoresponsewritersquo lexers=delimiters=(rsquorsquo rsquorsquo) _super_nodes=[])

Bases object

Parse all blocks

Parameters

bull text ndash text to parse

bull context ndash context to parse in

bull path ndash folder path to templates

bull writer ndash string of writer class to use

bull lexers ndash dict of custom lexers to use

bull delimiters ndash for example (lsquolsquorsquorsquo)

114 Chapter 33 template Module

web2py Documentation Release 2146-stable

bull _super_nodes ndash a list of nodes to check for inclusion this should only be set byldquoselfextendrdquo It contains a list of SuperNodes from a child template that need to be han-dled

default_delimiters = ( )

extend(filename)Extends filename Anything not declared in a block defined by the parent will be placed in the parenttemplates include block

include(content filename)Includes filename here

parse(text)

r_multiline = lt_sreSRE_Pattern objectgt

r_tag = lt_sreSRE_Pattern objectgt

re_block = lt_sreSRE_Pattern objectgt

re_pass = lt_sreSRE_Pattern objectgt

re_unblock = lt_sreSRE_Pattern objectgt

reindent(text)Reindents a string of unindented python code

to_string()Returns the parsed template with correct indentation

Used to make it easier to port to python3

gluontemplateget_parsed(text)Returns the indented python code of text Useful for unit testing

gluontemplateoutput_aux(node blocks)

gluontemplateparse_template(filename path=rsquoviewsrsquo context= lexers= delimiters=(rsquorsquorsquorsquo))

Parameters

bull filename ndash can be a view filename in the views folder or an input stream

bull path ndash is the path of a views folder

bull context ndash is a dictionary of symbols used to render the template

bull lexers ndash dict of custom lexers to use

bull delimiters ndash opening and closing tags

gluontemplaterender(content=rsquohello worldrsquo stream=None filename=None path=None con-text= lexers= delimiters=(rsquorsquo rsquorsquo) writer=rsquoresponsewritersquo)

Generic render function

Parameters

bull content ndash default content

bull stream ndash file-like obj to read template from

bull filename ndash where to find template

bull path ndash base path for templates

bull context ndash env

331 Templating syntax 115

web2py Documentation Release 2146-stable

bull lexers ndash custom lexers to use

bull delimiters ndash opening and closing tags

bull writer ndash where to inject the resulting stream

Example

gtgtgt render()hello worldgtgtgt render(content=abc)abcgtgtgt render(content=abc)abcgtgtgt render(content=abc)abcgtgtgt render(content=anbc)anbcgtgtgt render(content=abcde)abcdegtgtgt render(content=anc)ancgtgtgt render(content=ac)acgtgtgt render(content=for i in range(a)=iltbr gtpassrarr˓context=dict(a=5))0ltbr gt1ltbr gt2ltbr gt3ltbr gt4ltbr gtgtgtgt render(content=for i in range(a)=iltbr gtpassrarr˓context=dict(a=5)delimiters=())0ltbr gt1ltbr gt2ltbr gt3ltbr gt4ltbr gtgtgtgt render(content==hellonworld)hellonworldgtgtgt render(content=for i in range(3)n=inpass)012

116 Chapter 33 template Module

CHAPTER 34

tools Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

341 Auth Mail PluginManager and various utilities

class gluontoolsMail(server=None sender=None login=None tls=True)Bases object

Class for configuring and sending emails with alternative text html body multiple attachments and encryptionsupport

Works with SMTP and Google App Engine

Parameters

bull server ndash SMTP server address in addressport notation

bull sender ndash sender email address

bull login ndash sender login name and password in loginpassword notation or None if no authen-tication is required

bull tls ndash enablesdisables encryption (True by default)

In Google App Engine use

server=gae

For sake of backward compatibility all fields are optional and default to None however to be able to send emailsat least server and sender must be specified They are available under following fields

117

web2py Documentation Release 2146-stable

mailsettingsservermailsettingssendermailsettingsloginmailsettingstimeout = 60 seconds (default)

When server is lsquologgingrsquo email is logged but not sent (debug mode)

Optionally you can use PGP encryption or X509

mailsettingscipher_type = Nonemailsettingsgpg_home = Nonemailsettingssign = Truemailsettingssign_passphrase = Nonemailsettingsencrypt = Truemailsettingsx509_sign_keyfile = Nonemailsettingsx509_sign_certfile = Nonemailsettingsx509_sign_chainfile = Nonemailsettingsx509_nocerts = Falsemailsettingsx509_crypt_certfiles = None

cipher_type Nonegpg - need a python-pyme package and gpgme libx509 - smime

gpg_home you can set a GNUPGHOME environment variableto specify home of gnupg

sign sign the message (True or False)sign_passphrase passphrase for key signingencrypt encrypt the message (True or False) It defaults

to True x509 only

x509_sign_keyfile the signers private key filename orstring containing the key (PEM format)

x509_sign_certfile the signers certificate filename orstring containing the cert (PEM format)

x509_sign_chainfile sets the optional all-in-one file where youcan assemble the certificates of CertificationAuthorities (CA) which form the certificatechain of email certificate It can be astring containing the certs to (PEM format)

x509_nocerts if True then no attached certificate in mailx509_crypt_certfiles the certificates file or strings to encrypt

the messages with can be a file name string or a list of file names strings (PEM format)

Examples

Create Mail object with authentication data for remote server

mail = Mail(examplecom25 meexamplecom mepassword)

Notice for GAE users attachments have an automatic content_id=rsquoattachment-irsquo where i is progressive num-ber in this way the can be referenced from the HTML as ltimg src=rdquocidattachment-0rdquo gt etc

118 Chapter 34 tools Module

web2py Documentation Release 2146-stable

class Attachment(payload filename=None content_id=None content_type=Noneencoding=rsquoutf-8rsquo)

Bases emailmimebaseMIMEBase

Email attachment

Parameters

bull payload ndash path to file or file-like object with read() method

bull filename ndash name of the attachment stored in message if set to None it will be fetchedfrom payload path file-like object payload must have explicit filename specified

bull content_id ndash id of the attachment automatically contained within lt and gt

bull content_type ndash content type of the attachment if set to None it will be fetched fromfilename using gluoncontenttype module

bull encoding ndash encoding of all strings passed to this function (except attachment body)

Content ID is used to identify attachments within the html body in example attached image with contentID lsquophotorsquo may be used in html message as a source of img tag ltimg src=rdquocidphotordquo gt

Example Create attachment from text file

attachment = MailAttachment(pathtofiletxt)

Content-Type textplainMIME-Version 10Content-Disposition attachment filename=filetxtContent-Transfer-Encoding base64

SOMEBASE64CONTENT=

Create attachment from image file with custom filename and cid

attachment = MailAttachment(pathtofilepngfilename=photopngcontent_id=photo)

Content-Type imagepngMIME-Version 10Content-Disposition attachment filename=photopngContent-Id ltphotogtContent-Transfer-Encoding base64

SOMEOTHERBASE64CONTENT=

send(to subject=rsquo[no subject]rsquo message=rsquo[no message]rsquo attachments=None cc=None bcc=Nonereply_to=None sender=None encoding=rsquoutf-8rsquo raw=False headers= from_address=Nonecipher_type=None sign=None sign_passphrase=None encrypt=None x509_sign_keyfile=Nonex509_sign_chainfile=None x509_sign_certfile=None x509_crypt_certfiles=Nonex509_nocerts=None)

Sends an email using data specified in constructor

Parameters

bull to ndash list or tuple of receiver addresses will also accept single object

bull subject ndash subject of the email

bull message ndash email body text depends on type of passed object

341 Auth Mail PluginManager and various utilities 119

web2py Documentation Release 2146-stable

ndash if 2-list or 2-tuple is passed first element will be source of plain text while second ofhtml text

ndash otherwise object will be the only source of plain text and html source will be set toNone

If text or html source is

ndash None content part will be ignored

ndash string content part will be set to it

ndash file-like object content part will be fetched from it using itrsquos read() method

bull attachments ndash list or tuple of MailAttachment objects will also accept single object

bull cc ndash list or tuple of carbon copy receiver addresses will also accept single object

bull bcc ndash list or tuple of blind carbon copy receiver addresses will also accept single object

bull reply_to ndash address to which reply should be composed

bull encoding ndash encoding of all strings passed to this method (including message bodies)

bull headers ndash dictionary of headers to refine the headers just before sending mail eg lsquoX-Mailerrsquo lsquoweb2py mailerrsquo

bull from_address ndash address to appear in the lsquoFromrsquo header this is not the envelopesender If not specified the sender will be used

bull cipher_type ndash gpg - need a python-pyme package and gpgme lib x509 - smime

bull gpg_home ndash you can set a GNUPGHOME environment variable to specify home ofgnupg

bull sign ndash sign the message (True or False)

bull sign_passphrase ndash passphrase for key signing

bull encrypt ndash encrypt the message (True or False) It defaults to True x509 only

bull x509_sign_keyfile ndash the signers private key filename or string containing the key(PEM format)

bull x509_sign_certfile ndash the signers certificate filename or string containing the cert(PEM format)

bull x509_sign_chainfile ndash sets the optional all-in-one file where you can assemblethe certificates of Certification Authorities (CA) which form the certificate chain of emailcertificate It can be a string containing the certs to (PEM format)

bull x509_nocerts ndash if True then no attached certificate in mail

bull x509_crypt_certfiles ndash the certificates file or strings to encrypt the messages withcan be a file name string or a list of file names strings (PEM format)

Examples

Send plain text message to single address

mailsend(youexamplecomMessage subjectPlain text body of the message)

120 Chapter 34 tools Module

web2py Documentation Release 2146-stable

Send html message to single address

mailsend(youexamplecomMessage subjectlthtmlgtPlain text body of the messagelthtmlgt)

Send text and html message to three addresses (two in cc)

mailsend(youexamplecomMessage subject(Plain text body lthtmlgthtml bodylthtmlgt)cc=[other1examplecom other2examplecom])

Send html only message with image attachment available from the message by lsquophotorsquo content id

mailsend(youexamplecomMessage subject(None lthtmlgtltimg src=cidphoto gtlthtmlgt)MailAttachment(pathtophotojpg

content_id=photo))

Send email with two attachments and no body text

mailsend(youexamplecomMessage subjectNone[MailAttachment(pathtofistfile)MailAttachment(pathtosecondfile)])

Returns True on success False on failure

Before return method updates two objectrsquos fields

bull selfresult return value of smtplibSMTPsendmail() or GAErsquos mailsend_mail() method

bull selferror Exception message or None if above was successful

class gluontoolsAuth(environment=None db=None mailer=True hmac_key=None con-troller=rsquodefaultrsquo function=rsquouserrsquo cas_provider=None signature=Truesecure=False csrf_prevention=True propagate_extension=Noneurl_index=None jwt=None host_names=None)

Bases object

accessible_query(name table user_id=None)Returns a query with all accessible records for user_id or the current logged in user this method does notwork on GAE because uses JOIN and IN

Example

Use as

db(authaccessible_query(read dbmytable))select(dbmytableALL)

add_group(role description=rdquo)Creates a group associated to a role

add_membership(group_id=None user_id=None role=None)Gives user_id membership of group_id or role if user is None than user_id is that of current logged in user

341 Auth Mail PluginManager and various utilities 121

web2py Documentation Release 2146-stable

add_permission(group_id name=rsquoanyrsquo table_name=rdquo record_id=0)Gives group_id lsquonamersquo access to lsquotable_namersquo and lsquorecord_idrsquo

allows_jwt(otherwise=None)

static archive(form archive_table=None current_record=rsquocurrent_recordrsquoarchive_current=False fields=None)

If you have a table (dbmytable) that needs full revision history you can just do

form = crudupdate(dbmytable myrecord onaccept=autharchive)

or

form = SQLFORM(dbmytable myrecord)process(onaccept=autharchive)

crudarchive will define a new table ldquomytable_archiverdquo and store a copy of the current record (ifarchive_current=True) or a copy of the previous record (if archive_current=False) in the newly createdtable including a reference to the current record

fields allows to specify extra fields that need to be archived

If you want to access such table you need to define it yourself in a model

dbdefine_table(mytable_archiveField(current_record dbmytable)dbmytable)

Notice such table includes all fields of dbmytable plus one current_record crudarchive does not times-tamp the stored record unless your original table has a fields like

dbdefine_table(Field(saved_on datetime

default=requestnow update=requestnow writable=False)Field(saved_by authuser

default=authuser_id update=authuser_id writable=False)

there is nothing special about these fields since they are filled before the record is archived

If you want to change the archive table name and the name of the reference field you can do for example

dbdefine_table(myhistoryField(parent_record dbmytable) dbmytable)

and use it as

form = crudupdate(dbmytable myrecordonaccept=lambda formcrudarchive(form

archive_table=dbrarr˓myhistory

current_record=parent_rarr˓record))

basic(basic_auth_realm=False)Performs basic login

Parameters basic_auth_realm ndash optional basic http authentication realm Can take str orunicode or function or callable or boolean

reads currentrequestenvhttp_authorization and returns basic_allowedbasic_accepteduser

122 Chapter 34 tools Module

web2py Documentation Release 2146-stable

if basic_auth_realm is defined is a callable itrsquos return value is used to set the basic authentication realm ifitrsquos a string its content is used instead Otherwise basic authentication realm is set to the application nameIf basic_auth_realm is None or False (the default) the behavior is to skip sending any challenge

bulk_register(max_emails=100)Creates a form for ther user to send invites to other users to join

cas_login(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt version=2)

cas_validate(version=2 proxy=False)

change_password(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form that lets the user change password

confirm_registration(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form to confirm user registration

default_messages = access_denied Insufficient privileges add_group_log Group (group_id)s created add_membership_log None add_permission_log None bulk_invite_body You have been invited to join (site)s click (link)s to complete the process bulk_invite_subject Invitation to join (site)s change_password_log User (id)s Password changed del_group_log Group (group_id)s deleted del_membership_log None del_permission_log None delete_label Check to delete email_sent Email sent email_taken This email already has an account email_verified Email verified function_disabled Function disabled group_description Group uniquely assigned to user (id)s has_membership_log None has_permission_log None impersonate_log User (id)s is impersonating (other_id)s invalid_email Invalid email invalid_login Invalid login invalid_password Invalid password invalid_reset_password Invalid reset password invalid_two_factor_code Incorrect code 0 more attempt(s) remaining invalid_user Invalid user invalid_username Invalid username is_empty Cannot be empty label_client_ip Client IP label_description Description label_email E-mail label_first_name First name label_group_id Group ID label_last_name Last name label_name Name label_origin Origin label_password Password label_record_id Record ID label_registration_id Registration identifier label_registration_key Registration key label_remember_me Remember me (for 30 days) label_reset_password_key Reset Password key label_role Role label_table_name Object or table name label_time_stamp Timestamp label_two_factor Authentication code label_user_id User ID label_username Username logged_in Logged in logged_out Logged out login_button Log In login_disabled Login disabled by administrator login_failed_log None login_log User (id)s Logged-in logout_log User (id)s Logged-out mismatched_password Password fields dont match new_password New password new_password_sent A new password was emailed to you old_password Old password password_change_button Change password password_changed Password changed password_reset_button Request reset password profile_log User (id)s Profile updated profile_save_button Apply changes profile_updated Profile updated register_button Sign Up register_log User (id)s Registered registration_pending Registration is pending approval registration_successful Registration successful registration_verifying Registration needs verification reset_password Click on the link (link)s to reset your password reset_password_log User (id)s Password reset reset_password_subject Password reset retrieve_password Your password is (password)s retrieve_password_log User (id)s Password retrieved retrieve_password_subject Password retrieve retrieve_two_factor_code Your temporary login code is 0 retrieve_two_factor_code_subject Two-step Login Authentication Code retrieve_username Your username is (username)s retrieve_username_log User (id)s Username retrieved retrieve_username_subject Username retrieve submit_button Submit two_factor_comment This code was emailed to you and is required for login unable_send_email Unable to send email unable_to_send_email Unable to send email username_sent Your username was emailed to you username_taken Username already taken verify_email Welcome (username)s Click on the link (link)s to verify your email verify_email_log User (id)s Verification email sent verify_email_subject Email verification verify_password Verify Password verify_password_comment please input your password againClass for authentication authorization role based access control

Includes

bull registration and profile

bull login and logout

bull username and password retrieval

bull event logging

bull role creation and assignment

bull user defined grouprole based permission

Parameters

bull environment ndash is there for legacy but unused (awful)

bull db ndash has to be the database where to create tables for authentication

bull mailer ndash Mail( ) or None (no mailer) or True (make a mailer)

bull hmac_key ndash can be a hmac_key or hmac_key=Authget_or_create_key()

bull controller ndash (where is the user action)

bull cas_provider ndash (delegate authentication to the URL CAS2)

Authentication Example

from gluoncontributils import mail=Mail()mailsettingsserver=smtpgmailcom587mailsettingssender=yousomewherecommailsettingslogin=usernamepasswordauth=Auth(db)authsettingsmailer=mail authsettings=authdefine_tables()def authentication()

return dict(form=auth())

341 Auth Mail PluginManager and various utilities 123

web2py Documentation Release 2146-stable

Exposes

bull http applicationcontrollerauthenticationlogin

bull http applicationcontrollerauthenticationlogout

bull http applicationcontrollerauthenticationregister

bull http applicationcontrollerauthenticationverify_email

bull http applicationcontrollerauthenticationretrieve_username

bull http applicationcontrollerauthenticationretrieve_password

bull http applicationcontrollerauthenticationreset_password

bull http applicationcontrollerauthenticationprofile

bull http applicationcontrollerauthenticationchange_password

On registration a group with role=new_userid is created and user is given membership of this group

You can create a group with

group_id=authadd_group(Manager can access the manage action)authadd_permission(group_id access to manage)

Here ldquoaccess to managerdquo is just a user defined string You can give access to a user

authadd_membership(group_id user_id)

If user id is omitted the logged in user is assumed

Then you can decorate any action

authrequires_permission(access to manage)def manage()

return dict()

You can restrict a permission to a specific table

authadd_permission(group_id edit dbsometable)authrequires_permission(edit dbsometable)

Or to a specific record

authadd_permission(group_id edit dbsometable 45)authrequires_permission(edit dbsometable 45)

If authorization is not granted calls

authsettingson_failed_authorization

Other options

authsettingsmailer=Noneauthsettingsexpiration=3600 seconds

these are messages that can be customized

124 Chapter 34 tools Module

web2py Documentation Release 2146-stable

default_settings = allow_basic_login False allow_basic_login_only False allow_delete_accounts False alternate_requires_registration False auth_manager_role None auth_two_factor_enabled False auth_two_factor_tries_left 3 bulk_register_enabled False captcha None cas_maps None client_side True create_user_groups user_(id)s email_case_sensitive True everybody_group_id None expiration 3600 formstyle None hideerror False keep_session_onlogin True keep_session_onlogout False label_separator None logging_enabled True login_after_password_change True login_after_registration False login_captcha None login_email_validate True login_userfield None logout_onlogout None long_expiration 2592000 manager_actions multi_login False on_failed_authentication ltfunction ltlambdagt at 0x7fcf0cf9f578gt ondelete CASCADE password_field password password_min_length 4 pre_registration_div None prevent_open_redirect_attacks True prevent_password_reset_attacks True profile_fields None register_captcha None register_fields None register_verify_password True registration_requires_approval False registration_requires_verification False remember_me_form True renew_session_onlogin True renew_session_onlogout True reset_password_requires_verification False retrieve_password_captcha None retrieve_username_captcha None showid False table_cas None table_cas_name auth_cas table_event None table_event_name auth_event table_group None table_group_name auth_group table_membership None table_membership_name auth_membership table_permission None table_permission_name auth_permission table_token_name auth_token table_user None table_user_name auth_user two_factor_authentication_group None update_fields [email] use_username False username_case_sensitive True wiki ltStorage gt

define_signature()

define_tables(username=None signature=None enable_tokens=False migrate=Nonefake_migrate=None)

To be called unless tables are defined manually

Examples

Use as

defines all needed tables and table files myprefix_auth_usertable authdefine_tables(migrate=myprefix_)

defines all needed tables without migrationtable filesauthdefine_tables(migrate=False)

del_group(group_id)Deletes a group

del_membership(group_id=None user_id=None role=None)Revokes membership from group_id to user_id if user_id is None than user_id is that of current logged inuser

del_permission(group_id name=rsquoanyrsquo table_name=rdquo record_id=0)Revokes group_id lsquonamersquo access to lsquotable_namersquo and lsquorecord_idrsquo

email_registration(subject body user)Sends and email invitation to a user informing they have been registered with the application

email_reset_password(user)

enable_record_versioning(tables archive_db=None archive_names=rsquo(tablename)s_archiversquocurrent_record=rsquocurrent_recordrsquo current_record_label=None)

Used to enable full record versioning (including auth tables)

auth = Auth(db)authdefine_tables(signature=True) define our own tablesdbdefine_table(mythingField(name)authsignature)authenable_record_versioning(tables=db)

tables can be the db (all table) or a list of tables only tables with modified_by and modified_on fiels (ascreated by authsignature) will have versioning Old record versions will be in table lsquomything_archiversquoautomatically defined

when you enable enable_record_versioning records are never deleted but marked with is_active=False

enable_record_versioning enables a common_filter for every table that filters out records with is_active =False

Note If you use authenable_record_versioning do not use autharchive or you will end up with dupli-cates autharchive does explicitly what enable_record_versioning does automatically

static get_or_create_key(filename=None alg=rsquosha512rsquo)

341 Auth Mail PluginManager and various utilities 125

web2py Documentation Release 2146-stable

get_or_create_user(keys update_fields=[rsquoemailrsquo] login=True get=True)Used for alternate login methods If the user exists already then password is updated If the user doesnrsquotyet exist then they are created

get_vars_next()

groups()Displays the groups and their roles for the logged in user

has_membership(group_id=None user_id=None role=None)Checks if user is member of group_id or role

has_permission(name=rsquoanyrsquo table_name=rdquo record_id=0 user_id=None group_id=None)Checks if user_id or current logged in user is member of a group that has lsquonamersquo permission on lsquota-ble_namersquo and lsquorecord_idrsquo if group_id is passed it checks whether the group has the permission

here()

id_group(role)Returns the group_id of the group specified by the role

impersonate(user_id=ltfunction ltlambdagtgt)To use this make a POST to http impersonate requestpost_varsuser_id=ltidgt

Set requestpost_varsuser_id to 0 to restore original user

requires impersonator is logged in and

has_permission(impersonate auth_user user_id)

is_impersonating()

is_logged_in()Checks if the user is logged in and returns TrueFalse If so user is in authuser as well as in ses-sionauthuser

jwt()To use JWT authentication 1) instantiate auth with

auth = Auth(db jwt = secret_keysecret)

where lsquosecretrsquo is your own secret string

2 Decorate functions that require login but should accept the JWT token credentials

authallows_jwt()authrequires_login()def myapi() return hello s authuseremail

Notice jwt is allowed but not required if user is logged in myapi is accessible

3 Use it

Now API users can obtain a token with

http appdefaultuserjwtusername= amppassword=

(returns json object with a token attribute) API users can refresh an existing token with

http appdefaultuserjwttoken=

they can authenticate themselves when calling http myapi by injecting a header

Authorization Bearer ltthe jwt tokengt

126 Chapter 34 tools Module

web2py Documentation Release 2146-stable

Any additional attributes in the jwt argument of Auth() below

auth = Auth(db jwt = )

are passed to the constructor of class AuthJWT Look there for documentation

log_event(description vars=None origin=rsquoauthrsquo)

Examples

Use as

authlog_event(description=this happened origin=auth)

login(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a login form

login_bare(username password)Logins user as specified by username (or email) and password

login_user(user)Logins the user = dbauth_user(id)

logout(next=ltfunction ltlambdagtgt onlogout=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)Logouts and redirects to login

logout_bare()

manage_tokens()

navbar(prefix=rsquoWelcomersquo action=None separators=(rsquo [ rsquo rsquo | rsquo rsquo ] rsquo) user_identifier=ltfunctionltlambdagtgt referrer_actions=ltfunction ltlambdagtgt mode=rsquodefaultrsquo)

Navbar with support for more templates This uses some code from the old navbar

Parameters mode ndash see options for list of

not_authorized()You can change the view for this page to make it look as you like

profile(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form that lets the user change hisher profile

random_password()

register(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a registration form

register_bare(fields)Registers a user as specified by username (or email) and a raw password

request_reset_password(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgtonaccept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form to reset the user password

requires(condition requires_login=True otherwise=None)Decorator that prevents access to action if not logged in

requires_login(otherwise=None)Decorator that prevents access to action if not logged in

341 Auth Mail PluginManager and various utilities 127

web2py Documentation Release 2146-stable

requires_login_or_token(otherwise=None)

requires_membership(role=None group_id=None otherwise=None)Decorator that prevents access to action if not logged in or if user logged in is not a member of group_idIf role is provided instead of group_id then the group_id is calculated

requires_permission(name table_name=rdquo record_id=0 otherwise=None)Decorator that prevents access to action if not logged in or if user logged in is not a member of any group(role) that has lsquonamersquo access to lsquotable_namersquo lsquorecord_idrsquo

requires_signature(otherwise=None hash_vars=True)Decorator that prevents access to action if not logged in or if user logged in is not a member of group_idIf role is provided instead of group_id then the group_id is calculated

reset_password(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form to reset the user password

reset_password_deprecated(next=ltfunction ltlambdagtgt onvalidation=ltfunctionltlambdagtgt onaccept=ltfunction ltlambdagtgt log=ltfunctionltlambdagtgt)

Returns a form to reset the user password (deprecated)

retrieve_password(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

retrieve_username(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form to retrieve the user username (only if there is a username field)

run_login_onaccept()

select_host(host host_names=None)checks that host is valid ie in the list of glob host_names if the host is missing then is it selects the firstentry from host_names read more here httpsgithubcomweb2pyweb2pyissues1196

table_cas()

table_event()

table_group()

table_membership()

table_permission()

table_token()

table_user()

update_groups()

url(f=None args=None vars=None scheme=False)

user_group(user_id=None)Returns the group_id of the group uniquely associated to this user ie role=user[user_id]

user_group_role(user_id=None)

user_iduserid or None

verify_email(next=ltfunction ltlambdagtgt onaccept=ltfunction ltlambdagtgt log=ltfunctionltlambdagtgt)

Action used to verify the registration email

128 Chapter 34 tools Module

web2py Documentation Release 2146-stable

when_is_logged_in_bypass_next_in_url(next session)This function should be use when someone want to avoid asking for user credentials when loaded pagecontains ldquouserlogin_next=NEXT_COMPONENTrdquo in the URL is refresh but user is already authenti-cated

wiki(slug=None env=None render=rsquomarkminrsquo manage_permissions=False force_prefix=rdquo re-strict_search=False resolve=True extra=None menu_groups=None templates=None mi-grate=True controller=None function=None force_render=False groups=None)

wikimenu()To be used in menupy for app wide wiki menus

class gluontoolsRecaptcha(request=None public_key=rdquo private_key=rdquo use_ssl=False er-ror=None error_message=rsquoinvalidrsquo label=rsquoVerifyrsquo options=rdquocomment=rdquo ajax=False)

Bases gluonhtmlDIV

Examples

Use as

form = FORM(Recaptcha(public_key= private_key=))

or

form = SQLFORM()formappend(Recaptcha(public_key= private_key=))

API_SERVER = httpwwwgooglecomrecaptchaapi

API_SSL_SERVER = httpswwwgooglecomrecaptchaapi

VERIFY_SERVER = httpwwwgooglecomrecaptchaapiverify

xml()generates the xml for this component

class gluontoolsRecaptcha2(request=None public_key=rdquo private_key=rdquo er-ror_message=rsquoinvalidrsquo label=rsquoVerifyrsquo options=None com-ment=rdquo)

Bases gluonhtmlDIV

Experimental Creates a DIV holding the newer Recaptcha from Google (v2)

Parameters

bull request ndash the request If not passed uses current request

bull public_key ndash the public key Google gave you

bull private_key ndash the private key Google gave you

bull error_message ndash the error message to show if verification fails

bull label ndash the label to use

bull options (dict) ndash takes these parameters

ndash hl

ndash theme

ndash type

341 Auth Mail PluginManager and various utilities 129

web2py Documentation Release 2146-stable

ndash tabindex

ndash callback

ndash expired-callback

see httpsdevelopersgooglecomrecaptchadocsdisplay for docs about those

bull comment ndash the comment

Examples

Use as

form = FORM(Recaptcha2(public_key= private_key=))

or

form = SQLFORM()formappend(Recaptcha2(public_key= private_key=))

to protect the login page instead use

from gluontools import Recaptcha2authsettingscaptcha = Recaptcha2(request public_key= private_key=)

API_URI = httpswwwgooglecomrecaptchaapijs

VERIFY_SERVER = httpswwwgooglecomrecaptchaapisiteverify

xml()generates the xml for this component

class gluontoolsCrud(environment db=None controller=rsquodefaultrsquo)Bases object

static archive(form archive_table=None current_record=rsquocurrent_recordrsquo)

create(table next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt message=ltfunction ltlambdagtgt form-name=ltfunction ltlambdagtgt attributes)

delete(table record_id next=ltfunction ltlambdagtgt message=ltfunction ltlambdagtgt)

get_format(field)

get_query(field op value refsearch=False)

has_permission(name table record=0)

log_event(message vars)

read(table record)

rows(table query=None fields=None orderby=None limitby=None)

search(tables args)Creates a search form and its results for a table rubric Examples

Use as

130 Chapter 34 tools Module

web2py Documentation Release 2146-stable

form results = crudsearch(dbtestqueries = [equals not equal contains]query_labels=equalsEquals

not equalNot equalfields = [idchildren]field_labels =

idIDchildrenChildrenzero=Please choosequery = (dbtestid gt 0)amp(dbtestid = 3) )

select(table query=None fields=None orderby=None limitby=None headers=None attr)

tables()

update(table record next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt ondelete=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgtmessage=ltfunction ltlambdagtgt deletable=ltfunction ltlambdagtgt formname=ltfunctionltlambdagtgt attributes)

url(f=None args=None vars=None)This should point to the controller that exposes download and crud

class gluontoolsService(environment=None)Bases object

exception JsonRpcException(code info)Bases exceptionsException

amfrpc(f)

Example

Use as

service = Service()serviceamfrpcdef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget httpappdefaultcallamfrpcmyfunctiona=helloampb=world

amfrpc3(domain=rsquodefaultrsquo)

Example

Use as

service = Service()serviceamfrpc3(domain)def myfunction(a b)

return a + bdef call()

return service()

341 Auth Mail PluginManager and various utilities 131

web2py Documentation Release 2146-stable

Then call it with

wget http appdefaultcallamfrpc3myfunctiona=helloampb=world

csv(f)

Example

Use as

service = Service()servicecsvdef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget httpappdefaultcallcsvmyfunctiona=3ampb=4

error()

json(f)

Example

Use as

service = Service()servicejsondef myfunction(a b)

return [a b]def call()

return service()

Then call it with

wget http appdefaultcalljsonmyfunctiona=helloampb=world

jsonrpc(f)

Example

Use as

service = Service()servicejsonrpcdef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget http appdefaultcalljsonrpcmyfunctiona=helloampb=world

132 Chapter 34 tools Module

web2py Documentation Release 2146-stable

jsonrpc2(f)

Example

Use as

service = Service()servicejsonrpc2def myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget ndashpost-data lsquoldquojsonrpcrdquo ldquo20rdquo ldquoidrdquo 1 ldquomethodrdquo ldquomyfunctionrdquo ldquoparamsrdquo ldquoardquo 1 ldquobrdquo2rsquo http appdefaultcalljsonrpc2

jsonrpc_errors = -32700 (Parse error Invalid JSON was received by the server An error occurred on the server while parsing the JSON text) -32603 (Internal error Internal JSON-RPC error) -32602 (Invalid params Invalid method parameter(s)) -32601 (Method not found The method does not exist is not available) -32600 (Invalid Request The JSON sent is not a valid Request object) -32099 (Server error Reserved for implementation-defined server-errors)

rss(f)

Example

Use as

service = Service()servicerssdef myfunction()

return dict(title= link= description=created_on= entries=[dict(title= link=

description= created_on=])def call()

return service()

Then call it with

wget http appdefaultcallrssmyfunction

run(f)

Example

Use as

service = Service()servicerundef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget httpappdefaultcallrunmyfunctiona=3ampb=4

341 Auth Mail PluginManager and various utilities 133

web2py Documentation Release 2146-stable

serve_amfrpc(version=0)

serve_csv(args=None)

serve_json(args=None)

serve_jsonrpc()

serve_jsonrpc2(data=None batch_element=False)

serve_rss(args=None)

serve_run(args=None)

serve_soap(version=rsquo11rsquo)

serve_xml(args=None)

serve_xmlrpc()

soap(name=None returns=None args=None doc=None)

Example

Use as

service = Service()servicesoap(MyFunctionreturns=resultintargs=aintbint)def myfunction(a b)

return a + bdef call()

return service()

Then call it with

from gluoncontribpysimplesoapclient import SoapClientclient = SoapClient(wsdl=httpappdefaultcallsoapWSDL)response = clientMyFunction(a=1b=2)return response[result]

It also exposes online generated documentation and xml example messages athttp appdefaultcallsoap

xml(f)

Example

Use as

service = Service()servicexmldef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget httpappdefaultcallxmlmyfunctiona=3ampb=4

134 Chapter 34 tools Module

web2py Documentation Release 2146-stable

xmlrpc(f)

Example

Use as

service = Service()servicexmlrpcdef myfunction(a b)

return a + bdef call()

return service()

The call it with

wget http appdefaultcallxmlrpcmyfunctiona=helloampb=world

class gluontoolsWiki(auth env=None render=rsquomarkminrsquo manage_permissions=Falseforce_prefix=rdquo restrict_search=False extra=None menu_groups=Nonetemplates=None migrate=True controller=None function=Nonegroups=None)

Bases object

automenu()adds the menu if not present

can_edit(page=None)

can_manage()

can_read(page)

can_search()

can_see_menu()

cloud()

static component(text)In wiki docs allows componentcontrollerfunctionargs which renders as a LOAD( ajax=True)

create()

edit(slug from_template=0)

editmedia(slug)

everybody = everybody

first_paragraph(page)

fix_hostname(body)

get_renderer()

html_render(page)

markmin_base(body)

markmin_render(page)

media(id)

menu(controller=rsquodefaultrsquo function=rsquoindexrsquo)

341 Auth Mail PluginManager and various utilities 135

web2py Documentation Release 2146-stable

not_authorized(page=None)

pages()

preview(render)

read(slug force_render=False)

render_tags(tags)

rows_page = 25

search(tags=None query=None cloud=True preview=True limitby=(0 100) orderby=None)

class gluontoolsPluginManager(plugin=None defaults)Bases object

Plugin Manager is similar to a storage object but it is a single level singleton This means that multiple instanceswithin the same thread share the same attributes Its constructor is also special The first argument is the nameof the plugin you are defining The named arguments are parameters needed by the plugin with default valuesIf the parameters were previous defined the old values are used

Example

in some general configuration file

plugins = PluginManager()pluginsmeparam1=3

within the plugin model

_ = PluginManager(meparam1=5param2=6param3=7)

where the plugin is used

gtgtgt print pluginsmeparam13gtgtgt print pluginsmeparam26gtgtgt pluginsmeparam3 = 8gtgtgt print pluginsmeparam38

Here are some tests

gtgtgt a=PluginManager()gtgtgt ax=6gtgtgt b=PluginManager(check)gtgtgt print bx6gtgtgt b=PluginManager() reset settingsgtgtgt print bxltStorage gtgtgtgt bx=7gtgtgt print ax7gtgtgt ayz=8gtgtgt print byz8

(continues on next page)

136 Chapter 34 tools Module

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt test_thread_separation()5gtgtgt plugins=PluginManager(medb=mydb)gtgtgt print pluginsmedbmydbgtgtgt print me in pluginsTruegtgtgt print pluginsmeinstalledTrue

instances =

keys()

gluontoolsfetch(url data=None headers=None cookie= user_agent=rsquoMozilla50rsquo)

gluontoolsgeocode(address)

gluontoolsreverse_geocode(lat lng lang=None)Try to get an approximate address for a given latitude longitude

gluontoolsprettydate(d T=ltfunction ltlambdagtgt utc=False)

341 Auth Mail PluginManager and various utilities 137

web2py Documentation Release 2146-stable

138 Chapter 34 tools Module

CHAPTER 35

utf8 Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)Created by Vladyslav Kozlovskyy (Ukraine) ltdbdevelopcopygmailcomgtfor Web2py project

351 Utilities and class for UTF8 strings managing

class gluonutf8Utf8Bases str

Class for utf8 string storing and manipulations

The base presupposition of this class usage is ldquoALL strings in the application are either of utf-8 or unicodetype even when simple str type is used UTF-8 is only a ldquopackedrdquo version of unicode so Utf-8 and unicodestrings are interchangeablerdquo

CAUTION This class is slower than strunicode Do NOT use it inside intensive loops Simply decode string(s)to unicode before loop and encode it back to utf-8 string(s) after intensive calculation

You can see the benefit of this class in doctests() below

capitalize()rarr stringReturn a copy of the string S with only its first character capitalized

center(width[ fillchar ])rarr stringReturn S centered in a string of length width Padding is done using the specified fill character (default isa space)

count(sub[ start[ end ]])rarr intReturn the number of non-overlapping occurrences of substring sub in string S[startend] Optional argu-ments start and end are interpreted as in slice notation

139

web2py Documentation Release 2146-stable

decode([encoding[ errors]])rarr objectDecodes S using the codec registered for encoding encoding defaults to the default encoding errors maybe given to set a different error handling scheme Default is lsquostrictrsquo meaning that encoding errors raise aUnicodeDecodeError Other possible values are lsquoignorersquo and lsquoreplacersquo as well as any other name registeredwith codecsregister_error that is able to handle UnicodeDecodeErrors

encode([encoding[ errors]])rarr objectEncodes S using the codec registered for encoding encoding defaults to the default encoding errors maybe given to set a different error handling scheme Default is lsquostrictrsquo meaning that encoding errors raise aUnicodeEncodeError Other possible values are lsquoignorersquo lsquoreplacersquo and lsquoxmlcharrefreplacersquo as well as anyother name registered with codecsregister_error that is able to handle UnicodeEncodeErrors

endswith(suffix[ start[ end ]])rarr boolReturn True if S ends with the specified suffix False otherwise With optional start test S beginning atthat position With optional end stop comparing S at that position suffix can also be a tuple of strings totry

expandtabs([tabsize])rarr stringReturn a copy of S where all tab characters are expanded using spaces If tabsize is not given a tab size of8 characters is assumed

find(sub[ start[ end ]])rarr intReturn the lowest index in S where substring sub is found such that sub is contained within S[startend]Optional arguments start and end are interpreted as in slice notation

Return -1 on failure

format(args kwargs)rarr stringReturn a formatted version of S using substitutions from args and kwargs The substitutions are identifiedby braces (lsquolsquo and lsquorsquo)

index(sub[ start[ end ]])rarr intLike Sfind() but raise ValueError when the substring is not found

isalnum()rarr boolReturn True if all characters in S are alphanumeric and there is at least one character in S False otherwise

isalpha()rarr boolReturn True if all characters in S are alphabetic and there is at least one character in S False otherwise

isdigit()rarr boolReturn True if all characters in S are digits and there is at least one character in S False otherwise

islower()rarr boolReturn True if all cased characters in S are lowercase and there is at least one cased character in S Falseotherwise

isspace()rarr boolReturn True if all characters in S are whitespace and there is at least one character in S False otherwise

istitle()rarr boolReturn True if S is a titlecased string and there is at least one character in S ie uppercase characters mayonly follow uncased characters and lowercase characters only cased ones Return False otherwise

isupper()rarr boolReturn True if all cased characters in S are uppercase and there is at least one cased character in S Falseotherwise

join(iterable)rarr stringReturn a string which is the concatenation of the strings in the iterable The separator between elements isS

140 Chapter 35 utf8 Module

web2py Documentation Release 2146-stable

ljust(width[ fillchar ])rarr stringReturn S left-justified in a string of length width Padding is done using the specified fill character (defaultis a space)

lower()rarr stringReturn a copy of the string S converted to lowercase

lstrip([chars])rarr string or unicodeReturn a copy of the string S with leading whitespace removed If chars is given and not None removecharacters in chars instead If chars is unicode S will be converted to unicode before stripping

partition(sep) -gt (head sep tail)Search for the separator sep in S and return the part before it the separator itself and the part after it Ifthe separator is not found return S and two empty strings

replace(old new[ count ])rarr stringReturn a copy of string S with all occurrences of substring old replaced by new If the optional argumentcount is given only the first count occurrences are replaced

rfind(sub[ start[ end ]])rarr intReturn the highest index in S where substring sub is found such that sub is contained within S[startend]Optional arguments start and end are interpreted as in slice notation

Return -1 on failure

rindex(sub[ start[ end ]])rarr intLike Srfind() but raise ValueError when the substring is not found

rjust(width[ fillchar ])rarr stringReturn S right-justified in a string of length width Padding is done using the specified fill character (defaultis a space)

rpartition(sep) -gt (head sep tail)Search for the separator sep in S starting at the end of S and return the part before it the separator itselfand the part after it If the separator is not found return two empty strings and S

rsplit([sep[ maxsplit ]])rarr list of stringsReturn a list of the words in the string S using sep as the delimiter string starting at the end of the stringand working to the front If maxsplit is given at most maxsplit splits are done If sep is not specified or isNone any whitespace string is a separator

rstrip([chars])rarr string or unicodeReturn a copy of the string S with trailing whitespace removed If chars is given and not None removecharacters in chars instead If chars is unicode S will be converted to unicode before stripping

split([sep[ maxsplit ]])rarr list of stringsReturn a list of the words in the string S using sep as the delimiter string If maxsplit is given at mostmaxsplit splits are done If sep is not specified or is None any whitespace string is a separator and emptystrings are removed from the result

splitlines(keepends=False)rarr list of stringsReturn a list of the lines in S breaking at line boundaries Line breaks are not included in the resulting listunless keepends is given and true

startswith(prefix[ start[ end ]])rarr boolReturn True if S starts with the specified prefix False otherwise With optional start test S beginning atthat position With optional end stop comparing S at that position prefix can also be a tuple of strings totry

strip([chars])rarr string or unicodeReturn a copy of the string S with leading and trailing whitespace removed If chars is given and not None

351 Utilities and class for UTF8 strings managing 141

web2py Documentation Release 2146-stable

remove characters in chars instead If chars is unicode S will be converted to unicode before stripping

swapcase()rarr stringReturn a copy of the string S with uppercase characters converted to lowercase and vice versa

title()rarr stringReturn a titlecased version of S ie words start with uppercase characters all remaining cased charactershave lowercase

translate(table[ deletechars])rarr stringReturn a copy of the string S where all characters occurring in the optional argument deletechars areremoved and the remaining characters have been mapped through the given translation table which mustbe a string of length 256 or None If the table argument is None no translation is applied and the operationsimply removes the characters in deletechars

upper()rarr stringReturn a copy of the string S converted to uppercase

zfill(width)rarr stringPad a numeric string S with zeros on the left to fill a field of the specified width The string S is nevertruncated

142 Chapter 35 utf8 Module

CHAPTER 36

utils Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

361 This file specifically includes utilities for security

gluonutilsAES_new(key IV=None)Returns an AES cipher object and random IV if None specified

gluonutilscompare(a b)Compares two strings and not vulnerable to timing attacks

gluonutilsfast_urandom16(urandom=[] locker=lt_RLock owner=None count=0gt)This is 4x faster than calling osurandom(16) and prevents the ldquotoo many files openrdquo issue with concurrent accessto osurandom()

gluonutilsget_callable_argspec(fn)

gluonutilsget_digest(value)Returns a hashlib digest algorithm from a string

gluonutilsgetipaddrinfo(host)Filter out non-IP and bad IP addresses from getaddrinfo

gluonutilsinitialize_urandom()This function and the web2py_uuid follow from the following discussionhttpgroupsgooglecomgroupweb2py-developersbrowse_threadthread7fd5789a7da3f09

At startup web2py compute a unique ID that identifies the machine by adding uuidgetnode() + int(timetime() 1e3)

This is a 48-bit number It converts the number into 16 8-bit tokens It uses this value to initialize the entropysource (lsquodevurandomrsquo) and to seed random

143

web2py Documentation Release 2146-stable

If osrandom() is not supported it falls back to using random and issues a warning

gluonutilsis_loopback_ip_address(ip=None addrinfo=None)Determines whether the address appears to be a loopback address This assumes that the IP is valid

gluonutilsis_valid_ip_address(address)

Examples

Better than a thousand words

gtgtgt is_valid_ip_address(1270)Falsegtgtgt is_valid_ip_address(127001)Truegtgtgt is_valid_ip_address(20016601)True

gluonutilsmd5_hash(text)Generates a md5 hash with the given text

gluonutilspad(s n=32 padchar=rsquo rsquo)

gluonutilspbkdf2_hex(data salt iterations=1000 keylen=24 hashfunc=None)

gluonutilssecure_dumps(data encryption_key hash_key=None compression_level=None)

gluonutilssecure_loads(data encryption_key hash_key=None compression_level=None)

gluonutilssimple_hash(text key=rdquo salt=rdquo digest_alg=rsquomd5rsquo)Generates hash with the given text using the specified digest hashing algorithm

gluonutilsweb2py_uuid(ctokens=(12807810588179607998L 787762416516532974))This function follows from the following discussion httpgroupsgooglecomgroupweb2py-developersbrowse_threadthread7fd5789a7da3f09

It works like uuiduuid4 except that tries to use osurandom() if possible and it XORs the output with the tokensuniquely associated with this machine

144 Chapter 36 utils Module

CHAPTER 37

validators Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)Thanks to ga2arch for help with IS_IN_DB and IS_NOT_IN_DB on GAE

371 Validators

class gluonvalidatorsANY_OF(subs)Bases gluonvalidatorsValidator

Tests if any of the validators in a list returns successfully

gtgtgt ANY_OF([IS_EMAIL()IS_ALPHANUMERIC()])(abco)(abco None)gtgtgt ANY_OF([IS_EMAIL()IS_ALPHANUMERIC()])(abco)(abco None)gtgtgt ANY_OF([IS_EMAIL()IS_ALPHANUMERIC()])(abco)(abco enter only letters numbers and underscore)gtgtgt ANY_OF([IS_ALPHANUMERIC()IS_EMAIL()])(abco)(abco enter a valid email address)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

class gluonvalidatorsCLEANUP(regex=None)Bases gluonvalidatorsValidator

Examples

Use as

145

web2py Documentation Release 2146-stable

INPUT(_type=text _name=name requires=CLEANUP())

removes special characters on validation

REGEX_CLEANUP = lt_sreSRE_Pattern objectgt

class gluonvalidatorsCRYPT(key=None digest_alg=rsquopbkdf2(1000 20 sha512)rsquo min_length=0error_message=rsquoToo shortrsquo salt=True max_length=1024)

Bases object

Examples

Use as

INPUT(_type=text _name=name requires=CRYPT())

encodes the value on validation with a digest

If no arguments are provided CRYPT uses the MD5 algorithm If the key argument is provided the HMAC+MD5algorithm is used If the digest_alg is specified this is used to replace the MD5 with for example SHA512 Thedigest_alg can be the name of a hashlib algorithm as a string or the algorithm itself

min_length is the minimal password length (default 4) - IS_STRONG for serious security error_message is themessage if password is too short

Notice that an empty password is accepted but invalid It will not allow login back Stores junk as hashedpassword

Specify an algorithm or by default we will use sha512

Typical available algorithms md5 sha1 sha224 sha256 sha384 sha512

If salt it hashes a password with a salt If salt is True this method will automatically generate one Either caseit returns an encrypted password string in the following format

ltalgorithmgt$ltsaltgt$lthashgt

Important hashed password is returned as a LazyCrypt object and computed only if needed The LasyCryptobject also knows how to compare itself with an existing salted password

Supports standard algorithms

gtgtgt for alg in (md5sha1sha256sha384sha512) print str(CRYPT(digest_alg=algsalt=True)(test)[0])md5$$sha1$$sha256$$sha384$$sha512$$

The syntax is always alg$salt$hash

Supports for pbkdf2

gtgtgt alg = pbkdf2(100020sha512)gtgtgt print str(CRYPT(digest_alg=algsalt=True)(test)[0])pbkdf2(100020sha512)$$

An optional hmac_key can be specified and it is used as salt prefix

146 Chapter 37 validators Module

web2py Documentation Release 2146-stable

gtgtgt a = str(CRYPT(digest_alg=md5key=mykeysalt=True)(test)[0])gtgtgt print amd5$$

Even if the algorithm changes the hash can still be validated

gtgtgt CRYPT(digest_alg=sha1key=mykeysalt=True)(test)[0] == aTrue

If no salt is specified CRYPT can guess the algorithms from length

gtgtgt a = str(CRYPT(digest_alg=sha1salt=False)(test)[0])gtgtgt asha1$$a94a8fe5ccb19ba61c4c0873d391e987982fbbd3gtgtgt CRYPT(digest_alg=sha1salt=False)(test)[0] == aTruegtgtgt CRYPT(digest_alg=sha1salt=False)(test)[0] == a[6]Truegtgtgt CRYPT(digest_alg=md5salt=False)(test)[0] == aTruegtgtgt CRYPT(digest_alg=md5salt=False)(test)[0] == a[6]True

class gluonvalidatorsIS_ALPHANUMERIC(error_message=rsquoEnter only letters numbers andunderscorersquo)

Bases gluonvalidatorsIS_MATCH

Example

Used as

INPUT(_type=text _name=name requires=IS_ALPHANUMERIC())

gtgtgt IS_ALPHANUMERIC()(1)(1 None)gtgtgt IS_ALPHANUMERIC()()( None)gtgtgt IS_ALPHANUMERIC()(A_a)(A_a None)gtgtgt IS_ALPHANUMERIC()()( enter only letters numbers and underscore)

class gluonvalidatorsIS_DATE_IN_RANGE(minimum=None maximum=None format=rsquoY-m-drsquo error_message=None)

Bases gluonvalidatorsIS_DATE

Examples

Use as

gtgtgt v = IS_DATE_IN_RANGE(minimum=datetimedate(200811)rarr˓ maximum=datetimedate(20091231)rarr˓ format=mdYerror_message=Oops)

(continues on next page)

371 Validators 147

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt v(03032008)(datetimedate(2008 3 3) None)

gtgtgt v(03032010)(03032010 oops)

gtgtgt v(datetimedate(200833))(datetimedate(2008 3 3) None)

gtgtgt v(datetimedate(201033))(datetimedate(2010 3 3) oops)

class gluonvalidatorsIS_DATE(format=rsquoY-m-drsquo error_message=rsquoEnter date as (for-mat)srsquo)

Bases gluonvalidatorsValidator

Examples

Use as

INPUT(_type=text _name=name requires=IS_DATE())

date has to be in the ISO8960 format YYYY-MM-DD

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

class gluonvalidatorsIS_DATETIME_IN_RANGE(minimum=None maximum=Noneformat=rsquoY-m-d HMSrsquo er-ror_message=None timezone=None)

Bases gluonvalidatorsIS_DATETIME

Examples

Use as

gtgtgt v = IS_DATETIME_IN_RANGE( minimum=datetimerarr˓datetime(2008111220) maximum=datetimerarr˓datetime(200912311220) format=mdY HMrarr˓error_message=Oops)gtgtgt v(03032008 1240)(datetimedatetime(2008 3 3 12 40) None)

gtgtgt v(03032010 1034)(03032010 1034 oops)

gtgtgt v(datetimedatetime(20083300))(datetimedatetime(2008 3 3 0 0) None)

gtgtgt v(datetimedatetime(20103300))(datetimedatetime(2010 3 3 0 0) oops)

148 Chapter 37 validators Module

web2py Documentation Release 2146-stable

class gluonvalidatorsIS_DATETIME(format=rsquoY-m-d HMSrsquo er-ror_message=rsquoEnter date and time as (format)srsquotimezone=None)

Bases gluonvalidatorsValidator

Examples

Use as

INPUT(_type=text _name=name requires=IS_DATETIME())

datetime has to be in the ISO8960 format YYYY-MM-DD hhmmss timezome must be None or apytztimezone(ldquoAmericaChicagordquo) object

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

isodatetime = Y-m-d HMS

static nice(format)

class gluonvalidatorsIS_DECIMAL_IN_RANGE(minimum=None maximum=None er-ror_message=None dot=rsquorsquo)

Bases gluonvalidatorsValidator

Determines that the argument is (or can be represented as) a Python Decimal and that it falls within the specifiedinclusive range The comparison is made with Python Decimal arithmetic

The minimum and maximum limits can be None meaning no lower or upper limit respectively

Example

Used as

INPUT(_type=text _name=name requires=IS_DECIMAL_IN_RANGE(0 10))

gtgtgt IS_DECIMAL_IN_RANGE(15)(4)(Decimal(4) None)gtgtgt IS_DECIMAL_IN_RANGE(15)(4)(Decimal(4) None)gtgtgt IS_DECIMAL_IN_RANGE(15)(1)(Decimal(1) None)gtgtgt IS_DECIMAL_IN_RANGE(15)(525)(525 enter a number between 1 and 5)gtgtgt IS_DECIMAL_IN_RANGE(5256)(525)(Decimal(525) None)gtgtgt IS_DECIMAL_IN_RANGE(5256)(525)(Decimal(525) None)gtgtgt IS_DECIMAL_IN_RANGE(15)(60)(60 enter a number between 1 and 5)gtgtgt IS_DECIMAL_IN_RANGE(15)(35)(Decimal(35) None)gtgtgt IS_DECIMAL_IN_RANGE(1555)(35)(Decimal(35) None)gtgtgt IS_DECIMAL_IN_RANGE(1555)(65)(65 enter a number between 15 and 55)

(continues on next page)

371 Validators 149

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_DECIMAL_IN_RANGE(15None)(65)(Decimal(65) None)gtgtgt IS_DECIMAL_IN_RANGE(15None)(05)(05 enter a number greater than or equal to 15)gtgtgt IS_DECIMAL_IN_RANGE(None55)(45)(Decimal(45) None)gtgtgt IS_DECIMAL_IN_RANGE(None55)(65)(65 enter a number less than or equal to 55)gtgtgt IS_DECIMAL_IN_RANGE()(65)(Decimal(65) None)gtgtgt IS_DECIMAL_IN_RANGE(099)(123123)(123123 enter a number between 0 and 99)gtgtgt IS_DECIMAL_IN_RANGE(099)(123123)(123123 enter a number between 0 and 99)gtgtgt IS_DECIMAL_IN_RANGE(099)(1234)(Decimal(1234) None)gtgtgt IS_DECIMAL_IN_RANGE()(abc)(abc enter a number)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

class gluonvalidatorsIS_EMAIL(banned=None forced=None error_message=rsquoEnter a validemail addressrsquo)

Bases gluonvalidatorsValidator

Checks if fieldrsquos value is a valid email address Can be set to disallow or force addresses from certain domain(s)

Email regex adapted from httphaackedcomarchive20070821i-knew-how-to-validate-an-email-address-until-iaspx generally following the RFCs except that we disallow quoted strings and permit underscores and leadingnumerics in subdomain labels

Parameters

bull banned ndash regex text for disallowed address domains

bull forced ndash regex text for required address domains

Both arguments can also be custom objects with a match(value) method

Example

Check for valid email address

INPUT(_type=text _name=namerequires=IS_EMAIL())

Check for valid email address that canrsquot be from a com domain

INPUT(_type=text _name=namerequires=IS_EMAIL(banned=^com(|)$))

Check for valid email address that must be from a edu domain

INPUT(_type=text _name=namerequires=IS_EMAIL(forced=^edu(|)$))

(continues on next page)

150 Chapter 37 validators Module

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_EMAIL()(abcom)(abcom None)gtgtgt IS_EMAIL()(abcdefcom)(abcdefcom None)gtgtgt IS_EMAIL()(abc3defcom)(abc3defcom None)gtgtgt IS_EMAIL()(abcdefus)(abcdefus None)gtgtgt IS_EMAIL()(abcd_-fus)(abcd_-fus None)gtgtgt IS_EMAIL()(defcom) missing name(defcom enter a valid email address)gtgtgt IS_EMAIL()(abcdefcom) quoted name(abcdefcom enter a valid email address)gtgtgt IS_EMAIL()(abc+defcom) no (abc+defcom enter a valid email address)gtgtgt IS_EMAIL()(abcdefx) one-char TLD(abcdefx enter a valid email address)gtgtgt IS_EMAIL()(abcdef12) numeric TLD(abcdef12 enter a valid email address)gtgtgt IS_EMAIL()(abcdefcom) double-dot in domain(abcdefcom enter a valid email address)gtgtgt IS_EMAIL()(abcdefcom) dot starts domain(abcdefcom enter a valid email address)gtgtgt IS_EMAIL()(abcdefc_m) underscore in TLD(abcdefc_m enter a valid email address)gtgtgt IS_EMAIL()(NotAnEmail) missing (NotAnEmail enter a valid email address)gtgtgt IS_EMAIL()(abcNotAnEmail) missing TLD(abcNotAnEmail enter a valid email address)gtgtgt IS_EMAIL()(customerdepartmentexamplecom)(customerdepartmentexamplecom None)gtgtgt IS_EMAIL()($A12345examplecom)($A12345examplecom None)gtgtgt IS_EMAIL()(defxyzabcexamplecom)(defxyzabcexamplecom None)gtgtgt IS_EMAIL()(_YosemiteSamexamplecom)(_YosemiteSamexamplecom None)gtgtgt IS_EMAIL()(~examplecom)(~examplecom None)gtgtgt IS_EMAIL()(woolyexamplecom) dot starts name(woolyexamplecom enter a valid email address)gtgtgt IS_EMAIL()(woolyexamplecom) adjacent dots in name(woolyexamplecom enter a valid email address)gtgtgt IS_EMAIL()(pootietangexamplecom) dot ends name(pootietangexamplecom enter a valid email address)gtgtgt IS_EMAIL()(examplecom) name is bare dot(examplecom enter a valid email address)gtgtgt IS_EMAIL()(ImaFoolexamplecom)(ImaFoolexamplecom None)gtgtgt IS_EMAIL()(Ima Foolexamplecom) space in name(Ima Foolexamplecom enter a valid email address)gtgtgt IS_EMAIL()(localguylocalhost) localhost as domain(localguylocalhost None)

regex = lt_sreSRE_Pattern object at 0x2e0e160gt

371 Validators 151

web2py Documentation Release 2146-stable

regex_proposed_but_failed = lt_sreSRE_Pattern object at 0x2e100d0gt

class gluonvalidatorsIS_LIST_OF_EMAILS(error_message=rsquoInvalid emails srsquo)Bases object

Example

Used as

Field(emailsliststringwidget=SQLFORMwidgetstextwidgetrequires=IS_LIST_OF_EMAILS()represent=lambda vr SPAN([A(x_href=mailto+x)

rarr˓for x in (v or [])]))

formatter(value row=None)

split_emails = lt_sreSRE_Pattern objectgt

class gluonvalidatorsIS_EMPTY_OR(other null=None empty_regex=None)Bases gluonvalidatorsValidator

Dummy class for testing IS_EMPTY_OR

gtgtgt IS_EMPTY_OR(IS_EMAIL())(abcdefcom)(abcdefcom None)gtgtgt IS_EMPTY_OR(IS_EMAIL())( )(None None)gtgtgt IS_EMPTY_OR(IS_EMAIL() null=abc)( )(abc None)gtgtgt IS_EMPTY_OR(IS_EMAIL() null=abc empty_regex=def)(def)(abc None)gtgtgt IS_EMPTY_OR(IS_EMAIL())(abc)(abc enter a valid email address)gtgtgt IS_EMPTY_OR(IS_EMAIL())( abc )(abc enter a valid email address)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

set_self_id(id)

class gluonvalidatorsIS_EXPR(expression error_message=rsquoInvalid expressionrsquo environ-ment=None)

Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=namerequires=IS_EXPR(5 lt int(value) lt 10))

The argument of IS_EXPR must be python condition

152 Chapter 37 validators Module

web2py Documentation Release 2146-stable

gtgtgt IS_EXPR(int(value) lt 2)(1)(1 None)

gtgtgt IS_EXPR(int(value) lt 2)(2)(2 invalid expression)

class gluonvalidatorsIS_FLOAT_IN_RANGE(minimum=None maximum=None er-ror_message=None dot=rsquorsquo)

Bases gluonvalidatorsValidator

Determines that the argument is (or can be represented as) a float and that it falls within the specified inclusiverange The comparison is made with native arithmetic

The minimum and maximum limits can be None meaning no lower or upper limit respectively

Example

Used as

INPUT(_type=text _name=name requires=IS_FLOAT_IN_RANGE(0 10))

gtgtgt IS_FLOAT_IN_RANGE(15)(4)(40 None)gtgtgt IS_FLOAT_IN_RANGE(15)(4)(40 None)gtgtgt IS_FLOAT_IN_RANGE(15)(1)(10 None)gtgtgt IS_FLOAT_IN_RANGE(15)(525)(525 enter a number between 1 and 5)gtgtgt IS_FLOAT_IN_RANGE(15)(60)(60 enter a number between 1 and 5)gtgtgt IS_FLOAT_IN_RANGE(15)(35)(35 None)gtgtgt IS_FLOAT_IN_RANGE(1None)(35)(35 None)gtgtgt IS_FLOAT_IN_RANGE(None5)(35)(35 None)gtgtgt IS_FLOAT_IN_RANGE(1None)(05)(05 enter a number greater than or equal to 1)gtgtgt IS_FLOAT_IN_RANGE(None5)(65)(65 enter a number less than or equal to 5)gtgtgt IS_FLOAT_IN_RANGE()(65)(65 None)gtgtgt IS_FLOAT_IN_RANGE()(abc)(abc enter a number)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

class gluonvalidatorsIS_IMAGE(extensions=(rsquobmprsquo rsquogifrsquo rsquojpegrsquo rsquopngrsquo) maxsize=(1000010000) minsize=(0 0) error_message=rsquoInvalid imagersquo)

Bases gluonvalidatorsValidator

Checks if file uploaded through file input was saved in one of selected image formats and has dimensions (widthand height) within given boundaries

371 Validators 153

web2py Documentation Release 2146-stable

Does not check for maximum file size (use IS_LENGTH for that) Returns validation failure if no data wasuploaded

Supported file formats BMP GIF JPEG PNG

Code parts taken from httpmailpythonorgpipermailpython-list2007-June617126html

Parameters

bull extensions ndash iterable containing allowed lowercase image file extensions

bull extension of uploaded file counts as jpeg) ((jpg) ndash

bull maxsize ndash iterable containing maximum width and height of the image

bull minsize ndash iterable containing minimum width and height of the image

Use (-1 -1) as minsize to pass image size check

Examples

Check if uploaded file is in any of supported image formats

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_IMAGE())

Check if uploaded file is either JPEG or PNG

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_IMAGE(extensions=(lsquojpegrsquo lsquopngrsquo)))

Check if uploaded file is PNG with maximum size of 200x200 pixels

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_IMAGE(extensions=(lsquopngrsquo) maxsize=(200200)))

class gluonvalidatorsIS_IN_DB(dbset field label=None error_message=rsquoValue not indatabasersquo orderby=None groupby=None distinct=Nonecache=None multiple=False zero=rdquo sort=False_and=None left=None delimiter=None auto_add=False)

Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=namerequires=IS_IN_DB(db dbmytablemyfield zero=))

used for reference fields rendered as a dropbox

build_set()

maybe_add(table fieldname value)

options(zero=True)

set_self_id(id)

class gluonvalidatorsIS_IN_SET(theset labels=None error_message=rsquoValue not allowedrsquomultiple=False zero=rdquo sort=False)

Bases gluonvalidatorsValidator

154 Chapter 37 validators Module

web2py Documentation Release 2146-stable

Example

Used as

INPUT(_type=text _name=namerequires=IS_IN_SET([max john]zero=))

The argument of IS_IN_SET must be a list or set

gtgtgt IS_IN_SET([max john])(max)(max None)gtgtgt IS_IN_SET([max john])(massimo)(massimo value not allowed)gtgtgt IS_IN_SET([max john] multiple=True)((max john))((max john) None)gtgtgt IS_IN_SET([max john] multiple=True)((bill john))((bill john) value not allowed)gtgtgt IS_IN_SET((id1id2) [first labelsecond label])(id1) Traditionalrarr˓way(id1 None)gtgtgt IS_IN_SET(id1first label id2second label)(id1)(id1 None)gtgtgt import itertoolsgtgtgt IS_IN_SET(itertoolschain([135][246]))(1)(1 None)gtgtgt IS_IN_SET([(id1first label) (id2second label)])(id1) Redundantrarr˓way(id1 None)

options(zero=True)

class gluonvalidatorsIS_INT_IN_RANGE(minimum=None maximum=None er-ror_message=None)

Bases gluonvalidatorsValidator

Determines that the argument is (or can be represented as) an int and that it falls within the specified range Therange is interpreted in the Pythonic way so the test is min lt= value lt max

The minimum and maximum limits can be None meaning no lower or upper limit respectively

Example

Used as

INPUT(_type=text _name=name requires=IS_INT_IN_RANGE(0 10))

gtgtgt IS_INT_IN_RANGE(15)(4)(4 None)gtgtgt IS_INT_IN_RANGE(15)(4)(4 None)gtgtgt IS_INT_IN_RANGE(15)(1)(1 None)gtgtgt IS_INT_IN_RANGE(15)(5)(5 enter an integer between 1 and 4)gtgtgt IS_INT_IN_RANGE(15)(5)(5 enter an integer between 1 and 4)gtgtgt IS_INT_IN_RANGE(15)(35)

(continues on next page)

371 Validators 155

web2py Documentation Release 2146-stable

(continued from previous page)

(35 enter an integer between 1 and 4)gtgtgt IS_INT_IN_RANGE(None5)(4)(4 None)gtgtgt IS_INT_IN_RANGE(None5)(6)(6 enter an integer less than or equal to 4)gtgtgt IS_INT_IN_RANGE(1None)(4)(4 None)gtgtgt IS_INT_IN_RANGE(1None)(0)(0 enter an integer greater than or equal to 1)gtgtgt IS_INT_IN_RANGE()(6)(6 None)gtgtgt IS_INT_IN_RANGE()(abc)(abc enter an integer)

class gluonvalidatorsIS_IPV4(minip=rsquo0000rsquo maxip=rsquo255255255255rsquo invert=Falseis_localhost=None is_private=None is_automatic=Noneerror_message=rsquoEnter valid IPv4 addressrsquo)

Bases gluonvalidatorsValidator

Checks if fieldrsquos value is an IP version 4 address in decimal form Can be set to force addresses from certainrange

IPv4 regex taken from httpregexlibcomREDetailsaspxregexp_id=1411

Parameters

bull minip ndash lowest allowed address accepts

ndash str eg 19216801

ndash list or tuple of octets eg [192 168 0 1]

bull maxip ndash highest allowed address same as above

bull invert ndash True to allow addresses only from outside of given range note that range bound-aries are not matched this way

bull is_localhost ndash localhost address treatment

ndash None (default) indifferent

ndash True (enforce) query address must match localhost address (127001)

ndash False (forbid) query address must not match localhost address

bull is_private ndash same as above except that query address is checked against two addressranges 1721600 - 17231255255 and 19216800 - 192168255255

bull is_automatic ndash same as above except that query address is checked against one addressrange 16925400 - 169254255255

Minip and maxip may also be lists or tuples of addresses in all above forms (str int list tuple) allowing setupof multiple address ranges

minip = (minip1 minip2 minipN)| | || | |

maxip = (maxip1 maxip2 maxipN)

Longer iterable will be truncated to match length of shorter one

156 Chapter 37 validators Module

web2py Documentation Release 2146-stable

Examples

Check for valid IPv4 address

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV4())

Check for valid IPv4 address belonging to specific range

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV4(minip=lsquo10020000rsquomaxip=lsquo100200255255rsquo))

Check for valid IPv4 address belonging to either 10011000 - 100110255255 or 2005000 - 200500255address range

INPUT(_type=rsquotextrsquo _name=rsquonamersquo

requires=IS_IPV4(minip=(lsquo10011000rsquo lsquo2005000rsquo) maxip=(lsquo100110255255rsquolsquo200500255rsquo)))

Check for valid IPv4 address belonging to private address space

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV4(is_private=True))

Check for valid IPv4 address that is not a localhost address

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV4(is_localhost=False))

gtgtgt IS_IPV4()(1234)(1234 None)gtgtgt IS_IPV4()(255255255255)(255255255255 None)gtgtgt IS_IPV4()(1234 )(1234 enter valid IPv4 address)gtgtgt IS_IPV4()(12345)(12345 enter valid IPv4 address)gtgtgt IS_IPV4()(123123)(123123 enter valid IPv4 address)gtgtgt IS_IPV4()(1111234)(1111234 enter valid IPv4 address)gtgtgt IS_IPV4()(0111234)(0111234 enter valid IPv4 address)gtgtgt IS_IPV4()(256234)(256234 enter valid IPv4 address)gtgtgt IS_IPV4()(300234)(300234 enter valid IPv4 address)gtgtgt IS_IPV4(minip=1234 maxip=1234)(1234)(1234 None)gtgtgt IS_IPV4(minip=1235 maxip=1239 error_message=Bad ip)(1rarr˓234)(1234 bad ip)gtgtgt IS_IPV4(maxip=1234 invert=True)(127001)(127001 None)gtgtgt IS_IPV4(maxip=1234 invert=True)(1234)(1234 enter valid IPv4 address)gtgtgt IS_IPV4(is_localhost=True)(127001)(127001 None)gtgtgt IS_IPV4(is_localhost=True)(1234)(1234 enter valid IPv4 address)gtgtgt IS_IPV4(is_localhost=False)(127001)(127001 enter valid IPv4 address)

(continues on next page)

371 Validators 157

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_IPV4(maxip=100000 is_localhost=True)(127001)(127001 enter valid IPv4 address)

automatic = (2851995648L 2852061183L)

localhost = 2130706433

numbers = (16777216 65536 256 1)

private = ((2886729728L 2886795263L) (3232235520L 3232301055L))

regex = lt_sreSRE_Pattern object at 0x2e26320gt

class gluonvalidatorsIS_IPV6(is_private=None is_link_local=None is_reserved=Noneis_multicast=None is_routeable=None is_6to4=Noneis_teredo=None subnets=None error_message=rsquoEnter validIPv6 addressrsquo)

Bases gluonvalidatorsValidator

Checks if fieldrsquos value is an IP version 6 address First attempts to use the ipaddress library and falls back tocontribipaddrpy from Google (httpscodegooglecompipaddr-py)

Parameters

bull is_private ndash None (default) indifferent True (enforce) address must be in fc007range False (forbid) address must NOT be in fc007 range

bull is_link_local ndash Same as above but uses fe8010 range

bull is_reserved ndash Same as above but uses IETF reserved range

bull is_mulicast ndash Same as above but uses ff008 range

bull is_routeable ndash Similar to above but enforces not private link_local reserved or multi-cast

bull is_6to4 ndash Same as above but uses 200216 range

bull is_teredo ndash Same as above but uses 200132 range

bull subnets ndash value must be a member of at least one from list of subnets

Examples

Check for valid IPv6 address

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV6())

Check for valid IPv6 address is a link_local address

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV6(is_link_local=True))

Check for valid IPv6 address that is Internet routeable

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV6(is_routeable=True))

Check for valid IPv6 address in specified subnet

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV6(subnets=[lsquo200132rsquo])

158 Chapter 37 validators Module

web2py Documentation Release 2146-stable

gtgtgt IS_IPV6()(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPV6()(19216811)(19216811 enter valid IPv6 address)gtgtgt IS_IPV6(error_message=Bad ip)(19216811)(19216811 bad ip)gtgtgt IS_IPV6(is_link_local=True)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPV6(is_link_local=False)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(is_link_local=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(is_multicast=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(is_multicast=True)(ff00126c8ffafe22b3af)(ff00126c8ffafe22b3af None)gtgtgt IS_IPV6(is_routeable=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af None)gtgtgt IS_IPV6(is_routeable=True)(ff00126c8ffafe22b3af)(ff00126c8ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(subnets=200132)(20018ffafe22b3af)(20018ffafe22b3af None)gtgtgt IS_IPV6(subnets=fb008)(20018ffafe22b3af)(20018ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(subnets=[fc008200132])(20018ffafe22b3af)(20018ffafe22b3af None)gtgtgt IS_IPV6(subnets=invalidsubnet)(20018ffafe22b3af)(20018ffafe22b3af invalid subnet provided)

class gluonvalidatorsIS_IPADDRESS(minip=rsquo0000rsquo maxip=rsquo255255255255rsquo in-vert=False is_localhost=None is_private=Noneis_automatic=None is_ipv4=None is_link_local=Noneis_reserved=None is_multicast=Noneis_routeable=None is_6to4=None is_teredo=Nonesubnets=None is_ipv6=None error_message=rsquoEntervalid IP addressrsquo)

Bases gluonvalidatorsValidator

Checks if fieldrsquos value is an IP Address (v4 or v6) Can be set to force addresses from within a specific rangeChecks are done with the correct IS_IPV4 and IS_IPV6 validators

Uses ipaddress library if found falls back to PEP-3144 ipaddrpy from Google (in contrib)

Parameters

bull minip ndash lowest allowed address accepts str eg 19216801 list or tuple of octets eg[192 168 0 1]

bull maxip ndash highest allowed address same as above

bull invert ndash True to allow addresses only from outside of given range note that range bound-aries are not matched this way

IPv4 specific arguments

bull is_localhost localhost address treatment

ndash None (default) indifferent

ndash True (enforce) query address must match localhost address (127001)

371 Validators 159

web2py Documentation Release 2146-stable

ndash False (forbid) query address must not match localhost address

bull is_private same as above except that query address is checked against two address ranges 1721600 -17231255255 and 19216800 - 192168255255

bull is_automatic same as above except that query address is checked against one address range 16925400- 169254255255

bull is_ipv4 either

ndash None (default) indifferent

ndash True (enforce) must be an IPv4 address

ndash False (forbid) must NOT be an IPv4 address

IPv6 specific arguments

bull is_link_local Same as above but uses fe8010 range

bull is_reserved Same as above but uses IETF reserved range

bull is_mulicast Same as above but uses ff008 range

bull is_routeable Similar to above but enforces not private link_local reserved or multicast

bull is_6to4 Same as above but uses 200216 range

bull is_teredo Same as above but uses 200132 range

bull subnets value must be a member of at least one from list of subnets

bull is_ipv6 either

ndash None (default) indifferent

ndash True (enforce) must be an IPv6 address

ndash False (forbid) must NOT be an IPv6 address

Minip and maxip may also be lists or tuples of addresses in all above forms (str int list tuple) allowing setupof multiple address ranges

minip = (minip1 minip2 minipN)| | || | |

maxip = (maxip1 maxip2 maxipN)

Longer iterable will be truncated to match length of shorter one

gtgtgt IS_IPADDRESS()(19216815)(19216815 None)gtgtgt IS_IPADDRESS(is_ipv6=False)(19216815)(19216815 None)gtgtgt IS_IPADDRESS()(255255255255)(255255255255 None)gtgtgt IS_IPADDRESS()(19216815 )(19216815 enter valid IP address)gtgtgt IS_IPADDRESS()(192168115)(192168115 enter valid IP address)gtgtgt IS_IPADDRESS()(123123)(123123 enter valid IP address)gtgtgt IS_IPADDRESS()(1111234)(1111234 enter valid IP address)gtgtgt IS_IPADDRESS()(0111234)

(continues on next page)

160 Chapter 37 validators Module

web2py Documentation Release 2146-stable

(continued from previous page)

(0111234 enter valid IP address)gtgtgt IS_IPADDRESS()(256234)(256234 enter valid IP address)gtgtgt IS_IPADDRESS()(300234)(300234 enter valid IP address)gtgtgt IS_IPADDRESS(minip=19216810 maxip=1921681255)(1921681100)(1921681100 None)gtgtgt IS_IPADDRESS(minip=1235 maxip=1239 error_message=Bad ip)(123rarr˓4)(1234 bad ip)gtgtgt IS_IPADDRESS(maxip=1234 invert=True)(127001)(127001 None)gtgtgt IS_IPADDRESS(maxip=19216814 invert=True)(19216814)(19216814 enter valid IP address)gtgtgt IS_IPADDRESS(is_localhost=True)(127001)(127001 None)gtgtgt IS_IPADDRESS(is_localhost=True)(192168110)(192168110 enter valid IP address)gtgtgt IS_IPADDRESS(is_localhost=False)(127001)(127001 enter valid IP address)gtgtgt IS_IPADDRESS(maxip=100000 is_localhost=True)(127001)(127001 enter valid IP address)

gtgtgt IS_IPADDRESS()(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPADDRESS(is_ipv4=False)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPADDRESS()(fe80126c8ffafe22b3af )(fe80126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_ipv4=True)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_ipv6=True)(19216811)(19216811 enter valid IP address)gtgtgt IS_IPADDRESS(is_ipv6=True error_message=Bad ip)(19216811)(19216811 bad ip)gtgtgt IS_IPADDRESS(is_link_local=True)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPADDRESS(is_link_local=False)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_link_local=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_multicast=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_multicast=True)(ff00126c8ffafe22b3af)(ff00126c8ffafe22b3af None)gtgtgt IS_IPADDRESS(is_routeable=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af None)gtgtgt IS_IPADDRESS(is_routeable=True)(ff00126c8ffafe22b3af)(ff00126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(subnets=200132)(20018ffafe22b3af)(20018ffafe22b3af None)gtgtgt IS_IPADDRESS(subnets=fb008)(20018ffafe22b3af)(20018ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(subnets=[fc008200132])(20018ffafe22b3af)(20018ffafe22b3af None)gtgtgt IS_IPADDRESS(subnets=invalidsubnet)(20018ffafe22b3af)(20018ffafe22b3af invalid subnet provided)

371 Validators 161

web2py Documentation Release 2146-stable

class gluonvalidatorsIS_LENGTH(maxsize=255 minsize=0 error_message=rsquoEnter from(min)g to (max)g charactersrsquo)

Bases gluonvalidatorsValidator

Checks if length of fieldrsquos value fits between given boundaries Works for both text and file inputs

Parameters

bull maxsize ndash maximum allowed length size

bull minsize ndash minimum allowed length size

Examples

Check if text string is shorter than 33 characters

INPUT(_type=text _name=name requires=IS_LENGTH(32))

Check if password string is longer than 5 characters

INPUT(_type=password _name=name requires=IS_LENGTH(minsize=6))

Check if uploaded file has size between 1KB and 1MB

INPUT(_type=file _name=name requires=IS_LENGTH(1048576 1024))

Other examples

gtgtgt IS_LENGTH()()( None)gtgtgt IS_LENGTH()(1234567890)(1234567890 None)gtgtgt IS_LENGTH(maxsize=5 minsize=0)(1234567890) too long(1234567890 enter from 0 to 5 characters)gtgtgt IS_LENGTH(maxsize=50 minsize=20)(1234567890) too short(1234567890 enter from 20 to 50 characters)

class gluonvalidatorsIS_LIST_OF(other=None minimum=0 maximum=100 er-ror_message=None)

Bases gluonvalidatorsValidator

class gluonvalidatorsIS_LOWERBases gluonvalidatorsValidator

Converts to lower case

gtgtgt IS_LOWER()(ABC)(abc None)gtgtgt IS_LOWER()(Ntilde)(xc3xb1 None)

class gluonvalidatorsIS_MATCH(expression error_message=rsquoInvalid expressionrsquo strict=Falsesearch=False extract=False is_unicode=False)

Bases gluonvalidatorsValidator

Example

Used as

162 Chapter 37 validators Module

web2py Documentation Release 2146-stable

INPUT(_type=text _name=name requires=IS_MATCH(+))

The argument of IS_MATCH is a regular expression

gtgtgt IS_MATCH(+)(hello)(hello None)

gtgtgt IS_MATCH(hell)(hello)(hello None)

gtgtgt IS_MATCH(hell strict=False)(hello)(hello None)

gtgtgt IS_MATCH(hello)(shello)(shello invalid expression)

gtgtgt IS_MATCH(hello search=True)(shello)(shello None)

gtgtgt IS_MATCH(hello search=True strict=False)(shellox)(shellox None)

gtgtgt IS_MATCH(hello search=True strict=False)(shellox)(shellox None)

gtgtgt IS_MATCH(+)()( invalid expression)

class gluonvalidatorsIS_EQUAL_TO(expression error_message=rsquoNo matchrsquo)Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=password)INPUT(_type=text _name=password2

requires=IS_EQUAL_TO(requestvarspassword))

The argument of IS_EQUAL_TO is a string

gtgtgt IS_EQUAL_TO(aaa)(aaa)(aaa None)

gtgtgt IS_EQUAL_TO(aaa)(aab)(aab no match)

class gluonvalidatorsIS_NOT_EMPTY(error_message=rsquoEnter a valuersquo empty_regex=None)Bases gluonvalidatorsValidator

Example

Used as

371 Validators 163

web2py Documentation Release 2146-stable

INPUT(_type=text _name=name requires=IS_NOT_EMPTY())

gtgtgt IS_NOT_EMPTY()(1)(1 None)gtgtgt IS_NOT_EMPTY()(0)(0 None)gtgtgt IS_NOT_EMPTY()(x)(x None)gtgtgt IS_NOT_EMPTY()( x )(x None)gtgtgt IS_NOT_EMPTY()(None)(None enter a value)gtgtgt IS_NOT_EMPTY()()( enter a value)gtgtgt IS_NOT_EMPTY()( )( enter a value)gtgtgt IS_NOT_EMPTY()( nt)( enter a value)gtgtgt IS_NOT_EMPTY()([])([] enter a value)gtgtgt IS_NOT_EMPTY(empty_regex=def)(def)( enter a value)gtgtgt IS_NOT_EMPTY(empty_regex=de[fg])(deg)( enter a value)gtgtgt IS_NOT_EMPTY(empty_regex=def)(abc)(abc None)

class gluonvalidatorsIS_NOT_IN_DB(dbset field error_message=rsquoValue already indatabase or emptyrsquo allowed_override=[] ig-nore_common_filters=False)

Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=name requires=IS_NOT_IN_DB(db dbtable))

makes the field unique

set_self_id(id)

gluonvalidatorsIS_NULL_ORalias of gluonvalidatorsIS_EMPTY_OR

class gluonvalidatorsIS_SLUG(maxlen=80 check=False error_message=rsquoMust be slugrsquokeep_underscores=False)

Bases gluonvalidatorsValidator

converts arbitrary text string to a slug

gtgtgt IS_SLUG()(abc123)(abc123 None)gtgtgt IS_SLUG()(ABC123)(abc123 None)gtgtgt IS_SLUG()(abc-123)(abc-123 None)

(continues on next page)

164 Chapter 37 validators Module

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_SLUG()(abc--123)(abc-123 None)gtgtgt IS_SLUG()(abc 123)(abc-123 None)gtgtgt IS_SLUG()(abc _123)(abc-123 None)gtgtgt IS_SLUG()(-abc-)(abc None)gtgtgt IS_SLUG()(--a--b--_ -c--)(a-b-c None)gtgtgt IS_SLUG()(abcampamp123)(abc123 None)gtgtgt IS_SLUG()(abcampamp123ampampdef)(abc123def None)gtgtgt IS_SLUG()(ntilde)(n None)gtgtgt IS_SLUG(maxlen=4)(abc123)(abc1 None)gtgtgt IS_SLUG()(abc_123)(abc-123 None)gtgtgt IS_SLUG(keep_underscores=False)(abc_123)(abc-123 None)gtgtgt IS_SLUG(keep_underscores=True)(abc_123)(abc_123 None)gtgtgt IS_SLUG(check=False)(abc)(abc None)gtgtgt IS_SLUG(check=True)(abc)(abc None)gtgtgt IS_SLUG(check=False)(a bc)(a-bc None)gtgtgt IS_SLUG(check=True)(a bc)(a bc must be slug)

static urlify(value maxlen=80 keep_underscores=False)

class gluonvalidatorsIS_STRONG(min=None max=None upper=None lower=Nonenumber=None entropy=None special=Nonespecials=rsquo~$^amp()_+-=ltgt []|rsquo invalid=rsquorsquo error_message=None es=False)

Bases object

Examples

Use as

INPUT(_type=password _name=passwdrequires=IS_STRONG(min=10 special=2 upper=2))

enforces complexity requirements on a field

gtgtgt IS_STRONG(es=True)(Abcd1234)(Abcd1234Must include at least 1 of the following ~$^amp()_+-=ltgt[]|)gtgtgt IS_STRONG(es=True)(Abcd1234)(Abcd1234 None)

(continues on next page)

371 Validators 165

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_STRONG(es=True entropy=1)(a)(a None)gtgtgt IS_STRONG(es=True entropy=1 min=2)(a)(a Minimum length is 2)gtgtgt IS_STRONG(es=True entropy=100)(abc123)(abc123 Entropy (3235) less than required (100))gtgtgt IS_STRONG(es=True entropy=100)(and)(and Entropy (1457) less than required (100))gtgtgt IS_STRONG(es=True entropy=100)(aaa)(aaa Entropy (1442) less than required (100))gtgtgt IS_STRONG(es=True entropy=100)(a1d)(a1d Entropy (1597) less than required (100))gtgtgt IS_STRONG(es=True entropy=100)(antilded)(axc3xb1d Entropy (1813) less than required (100))

class gluonvalidatorsIS_TIME(error_message=rsquoEnter time as hhmmss (seconds am pm op-tional)rsquo)

Bases gluonvalidatorsValidator

Example

Use as

INPUT(_type=text _name=name requires=IS_TIME())

understands the following formats hhmmss [ampm] hhmm [ampm] hh [ampm]

[ampm] is optional lsquorsquo can be replaced by any other non-space non-digit

gtgtgt IS_TIME()(2130)(datetimetime(21 30) None)gtgtgt IS_TIME()(21-30)(datetimetime(21 30) None)gtgtgt IS_TIME()(2130)(datetimetime(21 30) None)gtgtgt IS_TIME()(213059)(datetimetime(21 30 59) None)gtgtgt IS_TIME()(530)(datetimetime(5 30) None)gtgtgt IS_TIME()(530 am)(datetimetime(5 30) None)gtgtgt IS_TIME()(530 pm)(datetimetime(17 30) None)gtgtgt IS_TIME()(530 whatever)(530 whatever enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()(530 20)(530 20 enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()(2430)(2430 enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()(2160)(2160 enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()(2130)(2130 enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()()( enter time as hhmmss (seconds am pm optional))ugrave

166 Chapter 37 validators Module

web2py Documentation Release 2146-stable

class gluonvalidatorsIS_UPLOAD_FILENAME(filename=None extension=None lastdot=Truecase=1 error_message=rsquoEnter valid filenamersquo)

Bases gluonvalidatorsValidator

Checks if name and extension of file uploaded through file input matches given criteria

Does not ensure the file type in any way Returns validation failure if no data was uploaded

Parameters

bull filename ndash filename (before dot) regex

bull extension ndash extension (after dot) regex

bull lastdot ndash which dot should be used as a filename extension separator True means lastdot eg filepng -gt file png False means first dot eg filetargz -gt file targz

bull case ndash 0 - keep the case 1 - transform the string into lowercase (default) 2 - transform thestring into uppercase

If there is no dot present extension checks will be done against empty string and filename checks against wholevalue

Examples

Check if file has a pdf extension (case insensitive)

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_UPLOAD_FILENAME(extension=rsquopdfrsquo))

Check if file has a targz extension and name starting with backup

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_UPLOAD_FILENAME(filename=rsquobackuprsquo exten-sion=rsquotargzrsquo lastdot=False))

Check if file has no extension and name matching README (case sensitive)

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_UPLOAD_FILENAME(filename=rsquo^README$rsquoextension=rsquo^$rsquo case=0)

class gluonvalidatorsIS_UPPERBases gluonvalidatorsValidator

Converts to upper case

gtgtgt IS_UPPER()(abc)(ABC None)gtgtgt IS_UPPER()(ntilde)(xc3x91 None)

class gluonvalidatorsIS_URL(error_message=rsquoEnter a valid URLrsquo mode=rsquohttprsquo al-lowed_schemes=None prepend_scheme=rsquohttprsquo al-lowed_tlds=None)

Bases gluonvalidatorsValidator

Rejects a URL string if any of the following is true

bull The string is empty or None

bull The string uses characters that are not allowed in a URL

bull The string breaks any of the HTTP syntactic rules

bull The URL scheme specified (if one is specified) is not lsquohttprsquo or lsquohttpsrsquo

371 Validators 167

web2py Documentation Release 2146-stable

bull The top-level domain (if a host name is specified) does not exist

(These rules are based on RFC 2616 httpwwwfaqsorgrfcsrfc2616html)

This function only checks the URLrsquos syntax It does not check that the URL points to a real document forexample or that it otherwise makes sense semantically This function does automatically prepend lsquohttprsquo infront of a URL in the case of an abbreviated URL (eg lsquogooglecarsquo)

If the parameter mode=rsquogenericrsquo is used then this functionrsquos behavior changes It then rejects a URL string ifany of the following is true

bull The string is empty or None

bull The string uses characters that are not allowed in a URL

bull The URL scheme specified (if one is specified) is not valid

(These rules are based on RFC 2396 httpwwwfaqsorgrfcsrfc2396html)

The list of allowed schemes is customizable with the allowed_schemes parameter If you exclude None fromthe list then abbreviated URLs (lacking a scheme such as lsquohttprsquo) will be rejected

The default prepended scheme is customizable with the prepend_scheme parameter If you set prepend_schemeto None then prepending will be disabled URLs that require prepending to parse will still be accepted but thereturn value will not be modified

IS_URL is compatible with the Internationalized Domain Name (IDN) standard specified in RFC 3490 (httptoolsietforghtmlrfc3490) As a result URLs can be regular strings or unicode strings If the URLrsquos domaincomponent (eg googleca) contains non-US-ASCII letters then the domain will be converted into Punycode(defined in RFC 3492 httptoolsietforghtmlrfc3492) IS_URL goes a bit beyond the standards and allowsnon-US-ASCII characters to be present in the path and query components of the URL as well These non-US-ASCII characters will be escaped using the standard lsquo20rsquo type syntax eg the unicode character with hexcode 0x4e86 will become lsquo4e86rsquo

Parameters

bull error_message ndash a string the error message to give the end user if the URL does notvalidate

bull allowed_schemes ndash a list containing strings or None Each element is a scheme theinputed URL is allowed to use

bull prepend_scheme ndash a string this scheme is prepended if itrsquos necessary to make the URLvalid

Code Examples

INPUT(_type=text _name=name requires=IS_URL())gtgtgt IS_URL()(abccom)(httpabccom None)

INPUT(_type=text _name=name requires=IS_URL(mode=generic))gtgtgt IS_URL(mode=generic)(abccom)(abccom None)

INPUT(_type=text _name=namerequires=IS_URL(allowed_schemes=[https] prepend_scheme=https))

gtgtgt IS_URL(allowed_schemes=[https] prepend_scheme=https)(httpsabccom)(httpsabccom None)

INPUT(_type=text _name=namerequires=IS_URL(prepend_scheme=https))

(continues on next page)

168 Chapter 37 validators Module

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_URL(prepend_scheme=https)(abccom)(httpsabccom None)

INPUT(_type=text _name=namerequires=IS_URL(mode=generic allowed_schemes=[ftps https]

prepend_scheme=https))gtgtgt IS_URL(mode=generic allowed_schemes=[ftps https] prepend_scheme=rarr˓https)(httpsabccom)(httpsabccom None)gtgtgt IS_URL(mode=generic allowed_schemes=[ftps https None] prepend_rarr˓scheme=https)(abccom)(abccom None)

author Jonathan Benn

class gluonvalidatorsIS_JSON(error_message=rsquoInvalid jsonrsquo native_json=False)Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=namerequires=IS_JSON(error_message=This is not a valid json input)

gtgtgt IS_JSON()(a 100)(ua 100 None)

gtgtgt IS_JSON()(spam1234)(spam1234 invalid json)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

371 Validators 169

web2py Documentation Release 2146-stable

170 Chapter 37 validators Module

CHAPTER 38

widget Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

381 The widget is called from web2py

class gluonwidgetIOBases object

write(data)

gluonwidgetcheck_existent_app(options appname)

gluonwidgetconsole()Defines the behavior of the console web2py execution

gluonwidgetget_code_for_scheduler(app options)

gluonwidgetget_url(host path=rsquorsquo proto=rsquohttprsquo port=80)

gluonwidgetrun_system_tests(options)Runs unittests for gluontests

gluonwidgetstart(cron=True)Starts server

gluonwidgetstart_browser(url startup=False)

gluonwidgetstart_schedulers(options)

class gluonwidgetweb2pyDialog(root options)Bases object

Main window dialog

171

web2py Documentation Release 2146-stable

checkTaskBar()Checks taskbar status

connect_pages()Connects pages

error(message)Shows error message

quit(justHide=False)Finishes the program execution

server_ready()

start()Starts web2py server

start_schedulers(app)

stop()Stops web2py server

try_start_scheduler(app)

try_stop_scheduler(app)

update(text)Updates app text

update_canvas()Updates canvas

update_schedulers(start=False)

172 Chapter 38 widget Module

CHAPTER 39

xmlrpc Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

gluonxmlrpchandler(request response methods)

173

web2py Documentation Release 2146-stable

174 Chapter 39 xmlrpc Module

CHAPTER 40

Indices and tables

bull genindex

bull modindex

bull search

175

web2py Documentation Release 2146-stable

176 Chapter 40 Indices and tables

Python Module Index

ggluonadmin 3gluoncache 7gluoncfs 9gluoncompileapp 11gluoncontenttype 15gluoncustom_import 17gluondal 19gluondebug 21gluondecoder 23gluonfileutils 25gluonglobals 27gluonhighlight 33gluonhtml 35gluonhttp 51gluonlanguages 53gluonmain 57gluonmessageboxhandler 59gluonmyregex 61gluonnewcron 63gluonportalocker 65gluonrecfile 67gluonrestricted 69gluonrewrite 71gluonsanitizer 75gluonscheduler 77gluonserializers 83gluonsettings 85gluonshell 87gluonsql 89gluonsqlhtml 97gluonstorage 107gluonstreamer 111gluontemplate 113gluontools 117gluonutf8 139gluonutils 143gluonvalidators 145gluonwidget 171

gluonxmlrpc 173

177

web2py Documentation Release 2146-stable

178 Python Module Index

Index

AA (class in gluonhtml) 35absolute_path_link() (in module gluonnewcron) 63abspath() (in module gluonfileutils) 25accepts() (gluonhtmlFORM method) 41accepts() (gluonsqlhtmlSQLFORM method) 101accessible_query() (gluontoolsAuth method) 121acf() (gluonrewriteMapUrlOut method) 72acquire() (gluonnewcronToken method) 63action() (gluoncacheCache method) 7add_button() (gluonhtmlFORM method) 41add_class() (in module gluonsqlhtml) 104add_deps() (gluonschedulerJobGraph method) 77add_group() (gluontoolsAuth method) 121add_membership() (gluontoolsAuth method) 121add_path_first() (in module gluonadmin) 3add_permission() (gluontoolsAuth method) 122adj_hibernation() (gluonschedulerScheduler method)

79AES_new() (in module gluonutils) 143allows_jwt() (gluontoolsAuth method) 122amfrpc() (gluontoolsService method) 131amfrpc3() (gluontoolsService method) 131ANY_OF (class in gluonvalidators) 145apath() (in module gluonadmin) 3API_SERVER (gluontoolsRecaptcha attribute) 129API_SSL_SERVER (gluontoolsRecaptcha attribute)

129API_URI (gluontoolsRecaptcha2 attribute) 130app_cleanup() (in module gluonadmin) 3app_compile() (in module gluonadmin) 3app_create() (in module gluonadmin) 4app_install() (in module gluonadmin) 4app_pack() (in module gluonadmin) 4app_pack_compiled() (in module gluonadmin) 4app_uninstall() (in module gluonadmin) 4append() (gluonhtmlDIV method) 37append() (gluontemplateBlockNode method) 113append() (gluontemplateContent method) 114

appfactory() (in module gluonmain) 58apply_filter() (gluonlanguagestranslator method) 53archive() (gluontoolsAuth static method) 122archive() (gluontoolsCrud static method) 130arg0 (gluonrewriteMapUrlIn attribute) 71as_dict() (gluonhtmlFORM method) 41as_dict() (gluonsqlDAL method) 92as_dict() (gluonsqlDALField method) 91as_dict() (gluonsqlDALRow method) 91as_dict() (gluonsqlDALTable method) 92as_dict() (gluonsqlField method) 96as_json() (gluonhtmlFORM method) 41as_json() (gluonsqlDALRow method) 91as_xml() (gluonhtmlFORM method) 41as_xml() (gluonsqlDALRow method) 91as_yaml() (gluonhtmlFORM method) 41assert_status() (gluonhtmlFORM method) 41assert_status() (gluonsqlhtmlSQLFORM method) 101assign_tasks() (gluonschedulerScheduler method) 79ASSIGNJS() (in module gluonhtml) 35async() (gluonschedulerMetaScheduler method) 77Auth (class in gluontools) 121AutocompleteWidget (class in gluonsqlhtml) 97autoDetectXMLEncoding() (in module gluondecoder)

23autokey (gluoncacheCache attribute) 8automatic (gluonvalidatorsIS_IPV4 attribute) 158automenu() (gluontoolsWiki method) 135AUTOTYPES (gluonsqlhtmlSQLFORM attribute) 101

BB (class in gluonhtml) 36basic() (gluontoolsAuth method) 122BEAUTIFY (class in gluonhtml) 36being_a_ticker() (gluonschedulerScheduler method) 79BlockNode (class in gluontemplate) 113BODY (class in gluonhtml) 36body (gluonglobalsRequest attribute) 28BooleanWidget (class in gluonsqlhtml) 97BR (class in gluonhtml) 36

179

web2py Documentation Release 2146-stable

build_acf() (gluonrewriteMapUrlOut method) 72build_environment() (in module gluoncompileapp) 12build_query() (gluonsqlhtmlSQLFORM static method)

101build_set() (gluonvalidatorsIS_IN_DB method) 154bulk_insert() (gluonsqlDALTable method) 92bulk_register() (gluontoolsAuth method) 123BUTTON (class in gluonhtml) 36

CCache (class in gluoncache) 7CacheRepresenter (class in gluonsqlhtml) 97callback() (gluonsqlhtmlAutocompleteWidget method)

97can_edit() (gluontoolsWiki method) 135can_join() (gluonsqlDAL method) 92can_manage() (gluontoolsWiki method) 135can_read() (gluontoolsWiki method) 135can_search() (gluontoolsWiki method) 135can_see_menu() (gluontoolsWiki method) 135capitalize() (gluonutf8Utf8 method) 139cas_login() (gluontoolsAuth method) 123cas_validate() (gluontoolsAuth method) 123cast_keys() (in module gluonserializers) 83CAT (class in gluonhtml) 36CENTER (class in gluonhtml) 36center() (gluonutf8Utf8 method) 139change_password() (gluontoolsAuth method) 123check_credentials() (in module gluonfileutils) 26check_existent_app() (in module gluonwidget) 171check_interaction() (in module gluondebug) 22check_new_version() (in module gluonadmin) 4check_reserved_keyword() (gluonsqlDAL method) 92CheckboxesWidget (class in gluonsqlhtml) 97checkTaskBar() (gluonwidgetweb2pyDialog method)

171cleanpath() (in module gluonfileutils) 25CLEANUP (class in gluonvalidators) 145clear() (gluonglobalsSession method) 30clear_content() (gluontemplateContent method) 114clear_interaction() (gluondebugWebDebugger method)

21clear_session_cookies() (gluonglobalsSession method)

30clone() (gluonsqlDALField method) 91clone() (gluonsqlField method) 96close() (gluonportalockerLockedFile method) 65close() (gluonsqlDAL method) 92cloud() (gluontoolsWiki method) 135CODE (class in gluonhtml) 36COL (class in gluonhtml) 37COLGROUP (class in gluonhtml) 37commit() (gluonsqlDAL method) 92communicate() (in module gluondebug) 22

compare() (in module gluonutils) 143compile2() (in module gluonrestricted) 69compile_application() (in module gluoncompileapp) 12compile_controllers() (in module gluoncompileapp) 12compile_models() (in module gluoncompileapp) 12compile_regex() (in module gluonrewrite) 72compile_views() (in module gluoncompileapp) 12component() (gluontoolsWiki static method) 135compute_uuid() (gluonglobalsRequest method) 28confirm() (gluonhtmlFORM static method) 41confirm_registration() (gluontoolsAuth method) 123connect() (gluonglobalsSession method) 30connect_pages() (gluonwidgetweb2pyDialog method)

172console() (in module gluonwidget) 171Content (class in gluontemplate) 114content_type (gluonsqlhtmlExportClass attribute) 98content_type (gluonsqlhtmlExporterCSV attribute) 98content_type (gluonsqlhtmlExporterCSV_hidden

attribute) 98content_type (gluonsqlhtmlExporterHTML attribute)

98content_type (gluonsqlhtmlExporterJSON attribute) 98content_type (gluonsqlhtmlExporterTSV attribute) 99content_type (gluonsqlhtmlExporterXML attribute) 99contenttype() (in module gluoncontenttype) 15cookies2headers() (gluonhttpHTTP method) 51count() (gluonsqlDALField method) 91count() (gluonsqlField method) 96count() (gluonutf8Utf8 method) 139create() (gluontoolsCrud method) 130create() (gluontoolsWiki method) 135create_missing_app_folders() (in module gluonadmin) 5create_missing_folders() (in module gluonadmin) 5createform() (gluonsqlhtmlSQLFORM method) 102crondance() (in module gluonnewcron) 63cronlauncher (class in gluonnewcron) 63Crud (class in gluontools) 130CRYPT (class in gluonvalidators) 146csv() (gluontoolsService method) 132csv() (in module gluonserializers) 83custom_import_install() (in module

gluoncustom_import) 17custom_importer() (in module gluoncustom_import) 17custom_json() (in module gluonserializers) 83CustomImportException 17

DDAL (class in gluonsql) 89DALField (class in gluonsql) 91DALRow (class in gluonsql) 91DALTable (class in gluonsql) 92DatetimeWidget (class in gluonsqlhtml) 98DateWidget (class in gluonsqlhtml) 98

180 Index

web2py Documentation Release 2146-stable

DecimalWidget (class in gluonsqlhtml) 98decode() (gluonutf8Utf8 method) 139decoder() (in module gluondecoder) 23default_delimiters (gluontemplateTemplateParser

attribute) 115default_messages (gluontoolsAuth attribute) 123default_settings (gluontoolsAuth attribute) 124DEFAULT_WIDTH (gluonsqlhtmlUploadWidget

attribute) 104define_signature() (gluontoolsAuth method) 125define_table() (gluonsqlDAL method) 93define_tables() (gluonschedulerScheduler method) 79define_tables() (gluontoolsAuth method) 125del_group() (gluontoolsAuth method) 125del_membership() (gluontoolsAuth method) 125del_permission() (gluontoolsAuth method) 125delete() (gluontoolsCrud method) 130DELETE_FILE (gluonsqlhtmlUploadWidget attribute)

104dictform() (gluonsqlhtmlSQLFORM static method) 102die() (gluonschedulerMetaScheduler method) 78die() (in module gluonshell) 87disable() (gluonschedulerScheduler method) 79distributed_transaction_begin() (gluonsqlDAL static

method) 93distributed_transaction_commit() (gluonsqlDAL static

method) 93DIV (class in gluonhtml) 37do_continue() (gluondebugWebDebugger method) 21do_exec() (gluondebugWebDebugger method) 21do_next() (gluondebugWebDebugger method) 21do_quit() (gluondebugWebDebugger method) 21do_return() (gluondebugWebDebugger method) 21do_step() (gluondebugWebDebugger method) 21DoubleWidget (class in gluonsqlhtml) 98download() (gluonglobalsResponse method) 28drop() (gluonsqlDALTable method) 92DummyResponse (class in gluontemplate) 114

Eedit() (gluontoolsWiki method) 135editmedia() (gluontoolsWiki method) 135element() (gluonhtmlDIV method) 38elements() (gluonhtmlDIV method) 38elements() (gluonhtmlXML method) 49EM (class in gluonhtml) 40email_registration() (gluontoolsAuth method) 125email_reset_password() (gluontoolsAuth method) 125EMBED (class in gluonhtml) 40embed64() (in module gluonhtml) 50emit() (gluonmessageboxhandlerMessageBoxHandler

method) 59emit() (gluonmessageboxhandlerNotifySendHandler

method) 59

enable_autocomplete_and_history() (in modulegluonshell) 87

enable_record_versioning() (gluontoolsAuth method)125

encode() (gluonutf8Utf8 method) 140endswith() (gluonutf8Utf8 method) 140env() (in module gluonshell) 87error() (gluontoolsService method) 132error() (gluonwidgetweb2pyDialog method) 172everybody (gluontoolsWiki attribute) 135exception() (gluondebugWebDebugger method) 21exec_environment() (in module gluonshell) 87exec_pythonrc() (in module gluonshell) 87execute_from_command_line() (in module gluonshell)

87executesql() (gluonsqlDAL method) 93executor() (in module gluonscheduler) 82exists() (in module gluonrecfile) 67expandtabs() (gluonutf8Utf8 method) 140export() (gluonsqlhtmlExportClass method) 98export() (gluonsqlhtmlExporterCSV method) 98export() (gluonsqlhtmlExporterCSV_hidden method)

98export() (gluonsqlhtmlExporterHTML method) 98export() (gluonsqlhtmlExporterJSON method) 98export() (gluonsqlhtmlExporterTSV method) 99export() (gluonsqlhtmlExporterXML method) 99export_to_csv_file() (gluonsqlDAL method) 93ExportClass (class in gluonsqlhtml) 98ExporterCSV (class in gluonsqlhtml) 98ExporterCSV_hidden (class in gluonsqlhtml) 98ExporterHTML (class in gluonsqlhtml) 98ExporterJSON (class in gluonsqlhtml) 98ExporterTSV (class in gluonsqlhtml) 99ExporterXML (class in gluonsqlhtml) 99extcron (class in gluonnewcron) 63extend() (gluontemplateBlockNode method) 113extend() (gluontemplateContent method) 114extend() (gluontemplateTemplateParser method) 115

Ffactory() (gluonsqlhtmlSQLFORM static method) 102fast_urandom16() (in module gluonutils) 143fetch() (in module gluontools) 137Field (class in gluonsql) 95FIELDKEY_DELETE_RECORD

(gluonsqlhtmlSQLFORM attribute) 101FIELDNAME_REQUEST_DELETE

(gluonsqlhtmlSQLFORM attribute) 101fields (gluonsqlDALTable attribute) 92FIELDSET (class in gluonhtml) 40file_ext (gluonsqlhtmlExportClass attribute) 98file_ext (gluonsqlhtmlExporterCSV attribute) 98

Index 181

web2py Documentation Release 2146-stable

file_ext (gluonsqlhtmlExporterCSV_hidden attribute)98

file_ext (gluonsqlhtmlExporterHTML attribute) 98file_ext (gluonsqlhtmlExporterJSON attribute) 98file_ext (gluonsqlhtmlExporterTSV attribute) 99file_ext (gluonsqlhtmlExporterXML attribute) 99filter_err() (in module gluonrewrite) 72filter_url() (in module gluonrewrite) 72find() (gluonutf8Utf8 method) 140find_exposed_functions() (in module gluoncompileapp)

12findT() (in module gluonlanguages) 55first_paragraph() (gluontoolsWiki method) 135fix_hostname() (gluontoolsWiki method) 135fix_newlines() (in module gluonfileutils) 26fixup_missing_path_info() (in module gluonrewrite) 72flatten() (gluonhtmlDIV method) 39flatten() (gluonhtmlMARKMIN method) 44flatten() (gluonhtmlXML method) 49flush() (gluondebugPipe method) 21force() (gluonlanguagestranslator method) 53forget() (gluonglobalsSession method) 30FORM (class in gluonhtml) 40form_factory() (in module gluonsqlhtml) 104format() (gluonutf8Utf8 method) 140formatter() (gluonsqlDALField method) 91formatter() (gluonsqlField method) 96formatter() (gluonvalidatorsANY_OF method) 145formatter() (gluonvalidatorsIS_DATE method) 148formatter() (gluonvalidatorsIS_DATETIME method)

149formatter() (gluonvalidatorsIS_DECIMAL_IN_RANGE

method) 150formatter() (gluonvalidatorsIS_EMPTY_OR method)

152formatter() (gluonvalidatorsIS_FLOAT_IN_RANGE

method) 153formatter() (gluonvalidatorsIS_JSON method) 169formatter() (gluonvalidatorsIS_LIST_OF_EMAILS

method) 152formstyle_bootstrap() (in module gluonsqlhtml) 105formstyle_bootstrap3_inline_factory() (in module

gluonsqlhtml) 105formstyle_bootstrap3_stacked() (in module

gluonsqlhtml) 105formstyle_divs() (in module gluonsqlhtml) 105formstyle_inline() (in module gluonsqlhtml) 105formstyle_table2cols() (in module gluonsqlhtml) 105formstyle_table3cols() (in module gluonsqlhtml) 105formstyle_ul() (in module gluonsqlhtml) 105formstyles (gluonsqlhtmlSQLFORM attribute) 102FormWidget (class in gluonsqlhtml) 99frameset (gluonhtmlHTML attribute) 43frameset (gluonhtmlXHTML attribute) 49

Ggenerate() (in module gluonrecfile) 67GENERIC_DESCRIPTION

(gluonsqlhtmlUploadWidget attribute)104

geocode() (in module gluontools) 137get() (gluonhtmlDIV method) 39get() (gluonsqlDALRow method) 91get_callable_argspec() (in module gluonutils) 143get_code_for_scheduler() (in module gluonwidget) 171get_digest() (in module gluonutils) 143get_effective_router() (in module gluonrewrite) 72get_format() (gluontoolsCrud method) 130get_instances() (gluonsqlDAL static method) 93get_or_create_key() (gluontoolsAuth static method)

125get_or_create_user() (gluontoolsAuth method) 125get_parsed() (in module gluontemplate) 115get_possible_languages() (gluonlanguagestranslator

method) 54get_possible_languages_info()

(gluonlanguagestranslator method) 54get_query() (gluontoolsCrud method) 130get_renderer() (gluontoolsWiki method) 135get_session() (in module gluonfileutils) 26get_t() (gluonlanguagestranslator method) 54get_url() (in module gluonwidget) 171get_usage() (in module gluonshell) 87get_vars (gluonglobalsRequest attribute) 28get_vars_next() (gluontoolsAuth method) 126get_workers() (gluonschedulerScheduler method) 79getcfs() (in module gluoncfs) 9getfirst() (gluonstorageStorage method) 108getipaddrinfo() (in module gluonutils) 143getlast() (gluonstorageStorage method) 108getlist() (gluonstorageStorage method) 108give_up() (gluonschedulerMetaScheduler method) 78gluonadmin (module) 3gluoncache (module) 7gluoncfs (module) 9gluoncompileapp (module) 11gluoncontenttype (module) 15gluoncustom_import (module) 17gluondal (module) 19gluondebug (module) 21gluondecoder (module) 23gluonfileutils (module) 25gluonglobals (module) 27gluonhighlight (module) 33gluonhtml (module) 35gluonhttp (module) 51gluonlanguages (module) 53gluonmain (module) 57gluonmessageboxhandler (module) 59

182 Index

web2py Documentation Release 2146-stable

gluonmyregex (module) 61gluonnewcron (module) 63gluonportalocker (module) 65gluonrecfile (module) 67gluonrestricted (module) 69gluonrewrite (module) 71gluonsanitizer (module) 75gluonscheduler (module) 77gluonserializers (module) 83gluonsettings (module) 85gluonshell (module) 87gluonsql (module) 89gluonsqlhtml (module) 97gluonstorage (module) 107gluonstreamer (module) 111gluontemplate (module) 113gluontools (module) 117gluonutf8 (module) 139gluonutils (module) 143gluonvalidators (module) 145gluonwidget (module) 171gluonxmlrpc (module) 173grid() (gluonsqlhtmlSQLFORM static method) 102groups() (gluontoolsAuth method) 126

HH1 (class in gluonhtml) 42H2 (class in gluonhtml) 42H3 (class in gluonhtml) 42H4 (class in gluonhtml) 42H5 (class in gluonhtml) 42H6 (class in gluonhtml) 42handler() (in module gluonxmlrpc) 173hardcron (class in gluonnewcron) 64harg0 (gluonrewriteMapUrlIn attribute) 71has_membership() (gluontoolsAuth method) 126has_options() (gluonsqlhtmlOptionsWidget static

method) 100has_permission() (gluontoolsAuth method) 126has_permission() (gluontoolsCrud method) 130has_representer() (gluonsqlDAL method) 94HEAD (class in gluonhtml) 42here() (gluontoolsAuth method) 126hidden_fields() (gluonhtmlFORM method) 41highlight() (in module gluonhighlight) 33HR (class in gluonhtml) 42HTML (class in gluonhtml) 42html5 (gluonhtmlHTML attribute) 43html_render() (gluontoolsWiki method) 135HTTP 51HttpServer (class in gluonmain) 58

II (class in gluonhtml) 43

ics() (in module gluonserializers) 83ID_DELETE_SUFFIX (gluonsqlhtmlUploadWidget at-

tribute) 104id_group() (gluontoolsAuth method) 126ID_LABEL_SUFFIX (gluonsqlhtmlSQLFORM at-

tribute) 101ID_ROW_SUFFIX (gluonsqlhtmlSQLFORM attribute)

101IFRAME (class in gluonhtml) 43IMG (class in gluonhtml) 43impersonate() (gluontoolsAuth method) 126import_from_csv_file() (gluonsqlDAL method) 94import_from_csv_file() (gluonsqlDALTable method)

92import_table_definitions() (gluonsqlDAL method) 94include() (gluontemplateTemplateParser method) 115include_files() (gluonglobalsResponse method) 28include_meta() (gluonglobalsResponse method) 28index() (gluonutf8Utf8 method) 140initialize_urandom() (in module gluonutils) 143INPUT (class in gluonhtml) 43insert() (gluonhtmlDIV method) 40insert() (gluonsqlDALTable method) 92insert() (gluontemplateContent method) 114instances (gluontoolsPluginManager attribute) 137IntegerWidget (class in gluonsqlhtml) 99interaction() (gluondebugWebDebugger method) 22invalid_url() (in module gluonrewrite) 72IO (class in gluonwidget) 171IS_ALPHANUMERIC (class in gluonvalidators) 147IS_DATE (class in gluonvalidators) 148IS_DATE_IN_RANGE (class in gluonvalidators) 147IS_DATETIME (class in gluonvalidators) 148IS_DATETIME_IN_RANGE (class in gluonvalidators)

148IS_DECIMAL_IN_RANGE (class in gluonvalidators)

149IS_EMAIL (class in gluonvalidators) 150IS_EMPTY_OR (class in gluonvalidators) 152IS_EQUAL_TO (class in gluonvalidators) 163is_expired() (gluonglobalsSession method) 30IS_EXPR (class in gluonvalidators) 152IS_FLOAT_IN_RANGE (class in gluonvalidators) 153IS_IMAGE (class in gluonvalidators) 153is_image() (gluonsqlhtmlUploadWidget static method)

104is_impersonating() (gluontoolsAuth method) 126IS_IN_DB (class in gluonvalidators) 154IS_IN_SET (class in gluonvalidators) 154IS_INT_IN_RANGE (class in gluonvalidators) 155IS_IPADDRESS (class in gluonvalidators) 159IS_IPV4 (class in gluonvalidators) 156IS_IPV6 (class in gluonvalidators) 158IS_JSON (class in gluonvalidators) 169

Index 183

web2py Documentation Release 2146-stable

IS_LENGTH (class in gluonvalidators) 161IS_LIST_OF (class in gluonvalidators) 162IS_LIST_OF_EMAILS (class in gluonvalidators) 152is_logged_in() (gluontoolsAuth method) 126is_loopback_ip_address() (in module gluonutils) 144IS_LOWER (class in gluonvalidators) 162IS_MATCH (class in gluonvalidators) 162is_new() (gluonglobalsSession method) 30IS_NOT_EMPTY (class in gluonvalidators) 163IS_NOT_IN_DB (class in gluonvalidators) 164IS_NULL_OR (in module gluonvalidators) 164IS_SLUG (class in gluonvalidators) 164IS_STRONG (class in gluonvalidators) 165IS_TIME (class in gluonvalidators) 166is_tracking_changes() (in module gluoncustom_import)

17IS_UPLOAD_FILENAME (class in gluonvalidators)

166IS_UPPER (class in gluonvalidators) 167IS_URL (class in gluonvalidators) 167is_valid_ip_address() (in module gluonutils) 144isalnum() (gluonutf8Utf8 method) 140isalpha() (gluonutf8Utf8 method) 140isdigit() (gluonutf8Utf8 method) 140islower() (gluonutf8Utf8 method) 140isodatetime (gluonvalidatorsIS_DATETIME attribute)

149isspace() (gluonutf8Utf8 method) 140istitle() (gluonutf8Utf8 method) 140isupper() (gluonutf8Utf8 method) 140

JJobGraph (class in gluonscheduler) 77join() (gluonutf8Utf8 method) 140json() (gluonglobalsResponse method) 28json() (gluontoolsService method) 132json() (in module gluonserializers) 83jsonrpc() (gluontoolsService method) 132jsonrpc2() (gluontoolsService method) 132jsonrpc_errors (gluontoolsService attribute) 133JSONWidget (class in gluonsqlhtml) 99jwt() (gluontoolsAuth method) 126

Kkeys() (gluontoolsPluginManager method) 137kill() (gluonschedulerScheduler method) 79

LLABEL (class in gluonhtml) 44label (gluonsqlhtmlExportClass attribute) 98label (gluonsqlhtmlExporterCSV attribute) 98label (gluonsqlhtmlExporterCSV_hidden attribute) 98label (gluonsqlhtmlExporterHTML attribute) 98label (gluonsqlhtmlExporterJSON attribute) 98

label (gluonsqlhtmlExporterTSV attribute) 99label (gluonsqlhtmlExporterXML attribute) 99launch() (gluonnewcronhardcron method) 64Lazy (gluonsqlDALField attribute) 91Lazy (gluonsqlField attribute) 95lazy_cache() (in module gluoncache) 8lazy_define_table() (gluonsqlDAL method) 94LEGEND (class in gluonhtml) 44LI (class in gluonhtml) 44LINK (class in gluonhtml) 44List (class in gluonstorage) 107listdir() (in module gluonfileutils) 25ListWidget (class in gluonsqlhtml) 99ljust() (gluonutf8Utf8 method) 140load() (gluonrestrictedRestrictedError method) 69load() (gluonrestrictedTicketStorage method) 69LOAD() (in module gluoncompileapp) 11load() (in module gluonrewrite) 72load_routers() (in module gluonrewrite) 73load_storage() (in module gluonstorage) 109LoadFactory (class in gluoncompileapp) 12loads_json() (in module gluonserializers) 83loads_yaml() (in module gluonserializers) 83local_import_aux() (in module gluoncompileapp) 12localhost (gluonvalidatorsIS_IPV4 attribute) 158lock() (in module gluonportalocker) 66LockedFile (class in gluonportalocker) 65log() (gluonrestrictedRestrictedError method) 69log_event() (gluontoolsAuth method) 127log_event() (gluontoolsCrud method) 130log_rewrite() (in module gluonrewrite) 73logger (gluonsqlDAL attribute) 94login() (gluontoolsAuth method) 127login_bare() (gluontoolsAuth method) 127login_user() (gluontoolsAuth method) 127logout() (gluontoolsAuth method) 127logout_bare() (gluontoolsAuth method) 127loop() (gluonschedulerMetaScheduler method) 78loop() (gluonschedulerScheduler method) 79lower() (gluonutf8Utf8 method) 141lstrip() (gluonutf8Utf8 method) 141

MM() (gluonlanguagestranslator method) 53Mail (class in gluontools) 117MailAttachment (class in gluontools) 118main() (in module gluonscheduler) 82make_fake_file_like_object() (in module gluonfileutils)

26manage_tokens() (gluontoolsAuth method) 127map_app() (gluonrewriteMapUrlIn method) 71map_controller() (gluonrewriteMapUrlIn method) 71map_function() (gluonrewriteMapUrlIn method) 71map_language() (gluonrewriteMapUrlIn method) 71

184 Index

web2py Documentation Release 2146-stable

map_prefix() (gluonrewriteMapUrlIn method) 71map_root_static() (gluonrewriteMapUrlIn method) 72map_static() (gluonrewriteMapUrlIn method) 72map_url_in() (in module gluonrewrite) 73map_url_out() (in module gluonrewrite) 73MapUrlIn (class in gluonrewrite) 71MapUrlOut (class in gluonrewrite) 72MARKMIN (class in gluonhtml) 44markmin_base() (gluontoolsWiki method) 135markmin_render() (gluontoolsWiki method) 135maybe_add() (gluonvalidatorsIS_IN_DB method) 154md5_hash() (in module gluonutils) 144media() (gluontoolsWiki method) 135MENU (class in gluonhtml) 44menu() (gluontoolsWiki method) 135message (gluonhttpHTTP attribute) 51MessageBoxHandler (class in

gluonmessageboxhandler) 59Messages (class in gluonstorage) 108META (class in gluonhtml) 45MetaScheduler (class in gluonscheduler) 77Method (gluonsqlDALField attribute) 91Method (gluonsqlField attribute) 95mktree() (in module gluonfileutils) 25model_cmp() (in module gluoncompileapp) 12model_cmp_sep() (in module gluoncompileapp) 12MultipleOptionsWidget (class in gluonsqlhtml) 99mybuiltin (class in gluoncompileapp) 12

Nnavbar() (gluontoolsAuth method) 127nice() (gluonvalidatorsIS_DATETIME static method)

149no_underscore() (gluonhtmlBEAUTIFY static method)

36Node (class in gluontemplate) 114NOESCAPE (class in gluontemplate) 114not_authorized() (gluontoolsAuth method) 127not_authorized() (gluontoolsWiki method) 135NotifySendHandler (class in gluonmessageboxhandler)

59now() (gluonschedulerScheduler method) 79numbers (gluonvalidatorsIS_IPV4 attribute) 158

OOBJECT (class in gluonhtml) 45OL (class in gluonhtml) 44omit_acf() (gluonrewriteMapUrlOut method) 72omit_lang() (gluonrewriteMapUrlOut method) 72on() (gluonsqlDALTable method) 92open() (in module gluonrecfile) 67OPTGROUP (class in gluonhtml) 45OPTION (class in gluonhtml) 45options() (gluonvalidatorsIS_IN_DB method) 154

options() (gluonvalidatorsIS_IN_SET method) 155OptionsWidget (class in gluonsqlhtml) 100output() (gluontemplateBlockNode method) 113output_aux() (in module gluontemplate) 115

PP (class in gluonhtml) 45PACKAGE_PATH_SUFFIX

(gluoncustom_importTrackImporter at-tribute) 17

pad() (in module gluonutils) 144pages() (gluontoolsWiki method) 136params_substitution() (gluonlanguagestranslator

method) 54parse() (gluontemplateTemplateParser method) 115parse_all_vars() (gluonglobalsRequest method) 28parse_as_rest() (gluonsqlDAL method) 94parse_get_vars() (gluonglobalsRequest method) 28parse_path_info() (in module gluonshell) 87parse_post_vars() (gluonglobalsRequest method) 28parse_template() (in module gluontemplate) 115parse_version() (in module gluonfileutils) 25parsecronline() (in module gluonnewcron) 64partition() (gluonutf8Utf8 method) 141PasswordWidget (class in gluonsqlhtml) 100pbkdf2_hex() (in module gluonutils) 144Pipe (class in gluondebug) 21plugin_install() (in module gluonadmin) 5plugin_pack() (in module gluonadmin) 5PluginManager (class in gluontools) 136plural() (gluonlanguagestranslator method) 55pop_arg_if() (gluonrewriteMapUrlIn method) 72pop_task() (gluonschedulerMetaScheduler method) 78pop_task() (gluonschedulerScheduler method) 79post_vars (gluonglobalsRequest attribute) 28PRE (class in gluonhtml) 45prettydate() (in module gluontools) 137preview() (gluontoolsWiki method) 136private (gluonvalidatorsIS_IPV4 attribute) 158process() (gluonhtmlFORM method) 41profile() (gluontoolsAuth method) 127

Qqueue_task() (gluonschedulerScheduler method) 79quit() (gluonwidgetweb2pyDialog method) 172

Rr_multiline (gluontemplateTemplateParser attribute)

115r_tag (gluontemplateTemplateParser attribute) 115RadioWidget (class in gluonsqlhtml) 100random_password() (gluontoolsAuth method) 127rangetolist() (in module gluonnewcron) 64re_block (gluontemplateTemplateParser attribute) 115

Index 185

web2py Documentation Release 2146-stable

re_compile() (in module gluoncompileapp) 12re_pass (gluontemplateTemplateParser attribute) 115re_unblock (gluontemplateTemplateParser attribute)

115read() (gluondebugPipe method) 21read() (gluonportalockerLockedFile method) 66read() (gluontoolsCrud method) 130read() (gluontoolsWiki method) 136read_file() (in module gluonfileutils) 25read_locked() (in module gluonportalocker) 66read_pyc() (in module gluoncompileapp) 12readline() (gluondebugPipe method) 21readline() (gluonportalockerLockedFile method) 66readlines() (gluonportalockerLockedFile method) 66readlines_file() (in module gluonfileutils) 25Recaptcha (class in gluontools) 129Recaptcha2 (class in gluontools) 129recursive_unlink() (in module gluonfileutils) 25redirect() (in module gluonhttp) 51REDIRECT_JS (gluonhtmlFORM attribute) 41regex (gluonvalidatorsIS_EMAIL attribute) 151regex (gluonvalidatorsIS_IPV4 attribute) 158regex_attr (gluonhtmlDIV attribute) 40regex_class (gluonhtmlDIV attribute) 40REGEX_CLEANUP (gluonvalidatorsCLEANUP

attribute) 146regex_filter_in() (in module gluonrewrite) 73regex_filter_out() (in module gluonrewrite) 73regex_id (gluonhtmlDIV attribute) 40regex_proposed_but_failed (gluonvalidatorsIS_EMAIL

attribute) 151regex_select() (in module gluonrewrite) 73regex_tag (gluonhtmlDIV attribute) 40regex_uri() (in module gluonrewrite) 73regex_url_in() (in module gluonrewrite) 73register() (gluontoolsAuth method) 127register_bare() (gluontoolsAuth method) 127reindent() (gluontemplateTemplateParser method) 115release() (gluonnewcronToken method) 63remove() (in module gluonrecfile) 67remove_compiled_application() (in module

gluoncompileapp) 12render() (gluonglobalsResponse method) 28render() (in module gluontemplate) 115render_tags() (gluontoolsWiki method) 136renew() (gluonglobalsSession method) 30replace() (gluonutf8Utf8 method) 141report_task() (gluonschedulerMetaScheduler method)

78report_task() (gluonschedulerScheduler method) 80represent() (gluonsqlDAL method) 94represent() (gluonsqlhtmlUploadWidget class method)

104represent() (in module gluonsqlhtml) 105

represented() (gluonsqlhtmlExportClass method) 98representers (gluonsqlDAL attribute) 94Request (class in gluonglobals) 27request_reset_password() (gluontoolsAuth method) 127requires() (gluontoolsAuth method) 127requires_https() (gluonglobalsRequest method) 28requires_login() (gluontoolsAuth method) 127requires_login_or_token() (gluontoolsAuth method)

127requires_membership() (gluontoolsAuth method) 128requires_permission() (gluontoolsAuth method) 128requires_signature() (gluontoolsAuth method) 128reset_password() (gluontoolsAuth method) 128reset_password_deprecated() (gluontoolsAuth method)

128Response (class in gluonglobals) 28restful() (gluonglobalsRequest method) 28restricted() (in module gluonrestricted) 69RestrictedError 69resume() (gluonschedulerScheduler method) 80retrieve() (gluonsqlDALField method) 91retrieve() (gluonsqlField method) 96retrieve_file_properties() (gluonsqlDALField method)

91retrieve_file_properties() (gluonsqlField method) 96retrieve_password() (gluontoolsAuth method) 128retrieve_username() (gluontoolsAuth method) 128reverse_geocode() (in module gluontools) 137rfind() (gluonutf8Utf8 method) 141rindex() (gluonutf8Utf8 method) 141rjust() (gluonutf8Utf8 method) 141rollback() (gluonsqlDAL method) 94rows() (gluontoolsCrud method) 130rows_page (gluontoolsWiki attribute) 136rpartition() (gluonutf8Utf8 method) 141rsplit() (gluonutf8Utf8 method) 141rss() (gluontoolsService method) 133rss() (in module gluonserializers) 83rstrip() (gluonutf8Utf8 method) 141run() (gluondebugWebDebugger method) 22run() (gluonnewcroncronlauncher method) 63run() (gluonnewcronextcron method) 64run() (gluonnewcronhardcron method) 64run() (gluonnewcronsoftcron method) 64run() (gluonschedulerMetaScheduler method) 78run() (gluontoolsService method) 133run() (in module gluonshell) 88run_controller_in() (in module gluoncompileapp) 13run_login_onaccept() (gluontoolsAuth method) 128run_models_in() (in module gluoncompileapp) 13run_system_tests() (in module gluonwidget) 171run_view_in() (in module gluoncompileapp) 13

186 Index

web2py Documentation Release 2146-stable

Ssafe_encode() (in module gluonserializers) 83safe_float() (in module gluonsqlhtml) 105safe_int() (in module gluonsqlhtml) 105sanitize() (in module gluonsanitizer) 75save_password() (in module gluonmain) 58save_pyc() (in module gluoncompileapp) 13save_session_id_cookie() (gluonglobalsSession

method) 31save_storage() (in module gluonstorage) 109Scheduler (class in gluonscheduler) 78SCRIPT (class in gluonhtml) 45search() (gluontoolsCrud method) 130search() (gluontoolsWiki method) 136search_menu() (gluonsqlhtmlSQLFORM static

method) 102secure() (gluonglobalsSession method) 31secure_dumps() (in module gluonutils) 144secure_loads() (in module gluonutils) 144SELECT (class in gluonhtml) 45select() (gluontoolsCrud method) 131select_host() (gluontoolsAuth method) 128send() (gluontoolsMail method) 119send_heartbeat() (gluonschedulerMetaScheduler

method) 78send_heartbeat() (gluonschedulerScheduler method) 80serialize() (gluonhtmlMENU method) 45serialize_mobile() (gluonhtmlMENU method) 45serializers (gluonsqlDAL attribute) 95serve_amfrpc() (gluontoolsService method) 133serve_csv() (gluontoolsService method) 134serve_json() (gluontoolsService method) 134serve_jsonrpc() (gluontoolsService method) 134serve_jsonrpc2() (gluontoolsService method) 134serve_rss() (gluontoolsService method) 134serve_run() (gluontoolsService method) 134serve_soap() (gluontoolsService method) 134serve_xml() (gluontoolsService method) 134serve_xmlrpc() (gluontoolsService method) 134server_ready() (gluonwidgetweb2pyDialog method)

172Service (class in gluontools) 131ServiceJsonRpcException 131Session (class in gluonglobals) 29set_attributes() (gluonsqlDALField method) 91set_attributes() (gluonsqlField method) 96set_current_languages() (gluonlanguagestranslator

method) 55set_folder() (gluonsqlDAL static method) 95set_requirements() (gluonschedulerScheduler method)

80set_self_id() (gluonvalidatorsIS_EMPTY_OR method)

152set_self_id() (gluonvalidatorsIS_IN_DB method) 154

set_self_id() (gluonvalidatorsIS_NOT_IN_DB method)164

set_trace() (in module gluondebug) 22set_worker_status() (gluonschedulerScheduler method)

80Settings (class in gluonstorage) 108show_if() (in module gluonsqlhtml) 105sibling() (gluonhtmlDIV method) 40siblings() (gluonhtmlDIV method) 40simple_hash() (in module gluonutils) 144sleep() (gluonschedulerMetaScheduler method) 78sleep() (gluonschedulerScheduler method) 80sluggify() (gluonrewriteMapUrlIn method) 72sluggify() (in module gluonrewrite) 73smart_query() (gluonsqlDAL method) 95smartdictform() (gluonsqlhtmlSQLFORM static

method) 102smartgrid() (gluonsqlhtmlSQLFORM static method)

102soap() (gluontoolsService method) 134softcron (class in gluonnewcron) 64SPAN (class in gluonhtml) 46split() (gluonutf8Utf8 method) 141split_emails (gluonvalidatorsIS_LIST_OF_EMAILS at-

tribute) 152splitlines() (gluonutf8Utf8 method) 141SQLFORM (class in gluonsqlhtml) 100sqlsafe (gluonsqlDALField attribute) 91sqlsafe (gluonsqlDALTable attribute) 92sqlsafe (gluonsqlField attribute) 96sqlsafe_alias (gluonsqlDALTable attribute) 92sqlsafe_name (gluonsqlDALField attribute) 91sqlsafe_name (gluonsqlField attribute) 96SQLTABLE (class in gluonsqlhtml) 103start() (gluonmainHttpServer method) 58start() (gluonwidgetweb2pyDialog method) 172start() (in module gluonwidget) 171start_browser() (in module gluonwidget) 171start_heartbeats() (gluonschedulerMetaScheduler

method) 78start_schedulers() (gluonwidgetweb2pyDialog method)

172start_schedulers() (in module gluonwidget) 171startswith() (gluonutf8Utf8 method) 141stop() (gluonmainHttpServer method) 58stop() (gluonwidgetweb2pyDialog method) 172stop_task() (gluonschedulerScheduler method) 80stop_trace() (in module gluondebug) 22stopcron() (in module gluonnewcron) 64Storage (class in gluonstorage) 107StorageList (class in gluonstorage) 109store() (gluonrestrictedTicketStorage method) 69store() (gluonsqlDALField method) 91store() (gluonsqlField method) 96

Index 187

web2py Documentation Release 2146-stable

stream() (gluonglobalsResponse method) 28stream_file_or_304_or_206() (in module

gluonstreamer) 111streamer() (in module gluonstreamer) 111strict (gluonhtmlHTML attribute) 43strict (gluonhtmlXHTML attribute) 49StringWidget (class in gluonsqlhtml) 103strip() (gluonutf8Utf8 method) 141STRONG (class in gluonhtml) 46STYLE (class in gluonhtml) 46style() (gluonsqlhtmlSQLTABLE method) 103SuperNode (class in gluontemplate) 114swapcase() (gluonutf8Utf8 method) 142

TTABLE (class in gluonhtml) 46table_cas() (gluontoolsAuth method) 128table_event() (gluontoolsAuth method) 128table_group() (gluontoolsAuth method) 128table_membership() (gluontoolsAuth method) 128table_permission() (gluontoolsAuth method) 128table_token() (gluontoolsAuth method) 128table_user() (gluontoolsAuth method) 128tables (gluonsqlDAL attribute) 95tables() (gluontoolsCrud method) 131tag (gluonhtmlA attribute) 35tag (gluonhtmlB attribute) 36tag (gluonhtmlBEAUTIFY attribute) 36tag (gluonhtmlBODY attribute) 36tag (gluonhtmlBR attribute) 36tag (gluonhtmlBUTTON attribute) 36tag (gluonhtmlCAT attribute) 36tag (gluonhtmlCENTER attribute) 36tag (gluonhtmlCOL attribute) 37tag (gluonhtmlCOLGROUP attribute) 37tag (gluonhtmlDIV attribute) 40tag (gluonhtmlEM attribute) 40tag (gluonhtmlEMBED attribute) 40tag (gluonhtmlFIELDSET attribute) 40tag (gluonhtmlFORM attribute) 41tag (gluonhtmlH1 attribute) 42tag (gluonhtmlH2 attribute) 42tag (gluonhtmlH3 attribute) 42tag (gluonhtmlH4 attribute) 42tag (gluonhtmlH5 attribute) 42tag (gluonhtmlH6 attribute) 42tag (gluonhtmlHEAD attribute) 42tag (gluonhtmlHR attribute) 42tag (gluonhtmlHTML attribute) 43tag (gluonhtmlI attribute) 43tag (gluonhtmlIFRAME attribute) 43tag (gluonhtmlIMG attribute) 43tag (gluonhtmlINPUT attribute) 44tag (gluonhtmlLABEL attribute) 44

tag (gluonhtmlLEGEND attribute) 44tag (gluonhtmlLI attribute) 44tag (gluonhtmlLINK attribute) 44tag (gluonhtmlMENU attribute) 45tag (gluonhtmlMETA attribute) 45tag (gluonhtmlOBJECT attribute) 45tag (gluonhtmlOL attribute) 44tag (gluonhtmlOPTGROUP attribute) 45tag (gluonhtmlOPTION attribute) 45tag (gluonhtmlP attribute) 45tag (gluonhtmlPRE attribute) 45tag (gluonhtmlSCRIPT attribute) 45tag (gluonhtmlSELECT attribute) 46tag (gluonhtmlSPAN attribute) 46tag (gluonhtmlSTRONG attribute) 46tag (gluonhtmlSTYLE attribute) 46tag (gluonhtmlTABLE attribute) 46tag (gluonhtmlTBODY attribute) 47tag (gluonhtmlTD attribute) 46tag (gluonhtmlTEXTAREA attribute) 46tag (gluonhtmlTFOOT attribute) 47tag (gluonhtmlTH attribute) 47tag (gluonhtmlTHEAD attribute) 47tag (gluonhtmlTITLE attribute) 47tag (gluonhtmlTR attribute) 47tag (gluonhtmlTT attribute) 47tag (gluonhtmlUL attribute) 44tag (gluonhtmlXHTML attribute) 49TAG (in module gluonhtml) 46tar() (in module gluonfileutils) 26tar_compiled() (in module gluonfileutils) 26Task (class in gluonscheduler) 81task_status() (gluonschedulerScheduler method) 81TaskReport (class in gluonscheduler) 82TBODY (class in gluonhtml) 47TD (class in gluonhtml) 46TemplateParser (class in gluontemplate) 114terminate() (gluonschedulerScheduler method) 81terminate_process() (gluonschedulerMetaScheduler

method) 78test() (in module gluoncompileapp) 13test() (in module gluonshell) 88TEXTAREA (class in gluonhtml) 46TextWidget (class in gluonsqlhtml) 103TFOOT (class in gluonhtml) 47TH (class in gluonhtml) 46THEAD (class in gluonhtml) 47THREAD_LOCAL (gluoncustom_importTrackImporter

attribute) 17TicketStorage (class in gluonrestricted) 69TimeWidget (class in gluonsqlhtml) 104TITLE (class in gluonhtml) 47title() (gluonutf8Utf8 method) 142to() (gluonhttpHTTP method) 51

188 Index

web2py Documentation Release 2146-stable

to_string() (gluontemplateTemplateParser method) 115Token (class in gluonnewcron) 63toolbar() (gluonglobalsResponse method) 29total_seconds() (gluonschedulerScheduler static

method) 81TR (class in gluonhtml) 47track_changes() (in module gluoncustom_import) 17TrackImporter (class in gluoncustom_import) 17transitional (gluonhtmlHTML attribute) 43transitional (gluonhtmlXHTML attribute) 49translate() (gluonlanguagestranslator method) 55translate() (gluonutf8Utf8 method) 142translator (class in gluonlanguages) 53truncate() (gluonsqlDALTable method) 92try_redirect_on_error() (in module gluonrewrite) 73try_rewrite_on_error() (in module gluonrewrite) 73try_start_scheduler() (gluonwidgetweb2pyDialog

method) 172try_stop_scheduler() (gluonwidgetweb2pyDialog

method) 172TT (class in gluonhtml) 47TYPE (class in gluonscheduler) 81

UUL (class in gluonhtml) 44unlock() (in module gluonportalocker) 66untar() (in module gluonfileutils) 26unzip() (in module gluonadmin) 5up() (in module gluonfileutils) 25update() (gluonhtmlDIV method) 40update() (gluonsqlDALTable method) 92update() (gluontoolsCrud method) 131update() (gluonwidgetweb2pyDialog method) 172update_all_languages() (in module gluonlanguages) 55update_canvas() (gluonwidgetweb2pyDialog method)

172update_dependencies() (gluonschedulerScheduler

method) 81update_groups() (gluontoolsAuth method) 128update_or_insert() (gluonsqlDALTable method) 92update_request() (gluonrewriteMapUrlIn method) 72update_schedulers() (gluonwidgetweb2pyDialog

method) 172upgrade() (in module gluonadmin) 5UploadWidget (class in gluonsqlhtml) 104upper() (gluonutf8Utf8 method) 142url() (gluontoolsAuth method) 128url() (gluontoolsCrud method) 131URL() (in module gluonhtml) 47url_in() (in module gluonrewrite) 73url_out() (in module gluonrewrite) 73urlify() (gluonvalidatorsIS_SLUG static method) 165user_agent() (gluonglobalsRequest method) 28user_group() (gluontoolsAuth method) 128

user_group_role() (gluontoolsAuth method) 128user_id (gluontoolsAuth attribute) 128Utf8 (class in gluonutf8) 139uuid (gluonglobalsRequest attribute) 28uuid() (gluonsqlDAL method) 95

Vvalidate() (gluonhtmlFORM method) 41validate() (gluonschedulerJobGraph method) 77validate() (gluonsqlDALField method) 91validate() (gluonsqlField method) 96validate_and_insert() (gluonsqlDALTable method) 92validate_and_update() (gluonsqlDALTable method) 92validate_and_update_or_insert() (gluonsqlDALTable

method) 92validate_args() (gluonrewriteMapUrlIn method) 72validators (gluonsqlDAL attribute) 95validators_method() (gluonsqlDAL method) 95vars (gluonglobalsRequest attribute) 28verify_email() (gluontoolsAuth method) 128VERIFY_SERVER (gluontoolsRecaptcha attribute)

129VERIFY_SERVER (gluontoolsRecaptcha2 attribute)

130Virtual (gluonsqlDALField attribute) 91Virtual (gluonsqlField attribute) 96

Ww2p_pack() (in module gluonfileutils) 26w2p_pack_plugin() (in module gluonfileutils) 26w2p_unpack() (in module gluonfileutils) 26w2p_unpack_plugin() (in module gluonfileutils) 26web2py_uuid() (in module gluonutils) 144web2pyDialog (class in gluonwidget) 171WebDebugger (class in gluondebug) 21when_is_logged_in_bypass_next_in_url()

(gluontoolsAuth method) 128where() (gluonsqlDAL method) 95widget() (gluonsqlhtmlBooleanWidget class method)

97widget() (gluonsqlhtmlCheckboxesWidget class

method) 97widget() (gluonsqlhtmlFormWidget class method) 99widget() (gluonsqlhtmlJSONWidget class method) 99widget() (gluonsqlhtmlListWidget class method) 99widget() (gluonsqlhtmlMultipleOptionsWidget class

method) 100widget() (gluonsqlhtmlOptionsWidget class method)

100widget() (gluonsqlhtmlPasswordWidget class method)

100widget() (gluonsqlhtmlRadioWidget class method) 100widget() (gluonsqlhtmlStringWidget class method) 103widget() (gluonsqlhtmlTextWidget class method) 104

Index 189

web2py Documentation Release 2146-stable

widget() (gluonsqlhtmlUploadWidget class method)104

widgets (gluonsqlhtmlSQLFORM attribute) 103Wiki (class in gluontools) 135wiki() (gluontoolsAuth method) 129wikimenu() (gluontoolsAuth method) 129with_alias() (gluonsqlDALTable method) 92with_prefix() (gluoncacheCache static method) 8wrapped_assign_tasks() (gluonschedulerScheduler

method) 81wrapped_pop_task() (gluonschedulerScheduler

method) 81wrapped_report_task() (gluonschedulerScheduler

method) 81write() (gluondebugPipe method) 21write() (gluonglobalsResponse method) 29write() (gluonportalockerLockedFile method) 66write() (gluontemplateDummyResponse method) 114write() (gluonwidgetIO method) 171write_file() (in module gluonfileutils) 25write_locked() (in module gluonportalocker) 66wsgibase() (in module gluonmain) 57

XXHTML (class in gluonhtml) 49XML (class in gluonhtml) 49xml() (gluonhtmlA method) 35xml() (gluonhtmlCODE method) 37xml() (gluonhtmlDIV method) 40xml() (gluonhtmlFORM method) 42xml() (gluonhtmlHTML method) 43xml() (gluonhtmlINPUT method) 44xml() (gluonhtmlMARKMIN method) 44xml() (gluonhtmlMENU method) 45xml() (gluonhtmlP method) 45xml() (gluonhtmlSCRIPT method) 45xml() (gluonhtmlSTYLE method) 46xml() (gluonhtmlXHTML method) 49xml() (gluonhtmlXML method) 50xml() (gluontemplateNOESCAPE method) 114xml() (gluontoolsRecaptcha method) 129xml() (gluontoolsRecaptcha2 method) 130xml() (gluontoolsService method) 134xml() (in module gluonserializers) 83xml_rec() (in module gluonserializers) 83xmlescape() (in module gluonhtml) 50xmlns (gluonhtmlXHTML attribute) 49xmlrpc() (gluonglobalsResponse method) 29xmlrpc() (gluontoolsService method) 134

Yyaml() (in module gluonserializers) 83

Zzfill() (gluonutf8Utf8 method) 142

190 Index

  • admin Module
    • Utility functions for the Admin application
      • cache Module
        • Basic caching classes and methods
          • cfs Module
            • Functions required to execute app components
              • compileapp Module
                • Functions required to execute app components
                  • contenttype Module
                  • custom_import Module
                    • Support for smart import syntax for web2py applications
                      • dal Module
                        • Takes care of adapting pyDAL to web2pyrsquos needs
                          • debug Module
                            • Debugger support classes
                              • decoder Module
                              • fileutils Module
                                • File operations
                                  • globals Module
                                  • highlight Module
                                  • html Module
                                    • Template helpers
                                      • http Module
                                        • HTTP statuses helpers
                                          • languages Module
                                            • Translation system
                                              • main Module
                                                • The gluon wsgi application
                                                  • messageboxhandler Module
                                                  • myregex Module
                                                    • Useful regexes
                                                      • newcron Module
                                                      • portalocker Module
                                                      • recfile Module
                                                        • Generates names for cache and session files
                                                          • restricted Module
                                                            • Restricted environment to execute applicationrsquos code
                                                              • rewrite Module
                                                              • sanitizer Module
                                                                • Cross-site scripting (XSS) defense
                                                                  • scheduler Module
                                                                    • Background processes made simple
                                                                      • serializers Module
                                                                      • settings Module
                                                                      • shell Module
                                                                        • Web2py environment in the shell
                                                                          • sql Module
                                                                            • Just for backward compatibility
                                                                              • sqlhtml Module
                                                                              • storage Module
                                                                              • streamer Module
                                                                                • Facilities to handle file streaming
                                                                                  • template Module
                                                                                    • Templating syntax
                                                                                      • tools Module
                                                                                        • Auth Mail PluginManager and various utilities
                                                                                          • utf8 Module
                                                                                            • Utilities and class for UTF8 strings managing
                                                                                              • utils Module
                                                                                                • This file specifically includes utilities for security
                                                                                                  • validators Module
                                                                                                    • Validators
                                                                                                      • widget Module
                                                                                                        • The widget is called from web2py
                                                                                                          • xmlrpc Module
                                                                                                          • Indices and tables
                                                                                                          • Python Module Index
Page 6: web2py Documentation - Read the Docs

web2py Documentation Release 2146-stable

Contents

Contents 1

web2py Documentation Release 2146-stable

2 Contents

CHAPTER 1

admin Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

11 Utility functions for the Admin application

gluonadminadd_path_first(path)

gluonadminapath(path=rdquo r=None)Builds a path inside an application folder

Parameters

bull path (str) ndash path within the application folder

bull r ndash the global request object

gluonadminapp_cleanup(app request)Removes session cache and error files

Parameters

bull app (str) ndash application name

bull request ndash the global request object

Returns True if everything went ok False otherwise

gluonadminapp_compile(app request skip_failed_views=False)Compiles the application

Parameters

bull app (str) ndash application name

bull request ndash the global request object

3

web2py Documentation Release 2146-stable

Returns None if everything went ok traceback text if errors are found

gluonadminapp_create(app request force=False key=None info=False)Create a copy of welcomew2p (scaffolding) app

Parameters

bull app (str) ndash application name

bull request ndash the global request object

gluonadminapp_install(app fobj request filename overwrite=None)Installs an application

bull Identifies file type by filename

bull Writes fobj contents to the deposit folder

bull Calls w2p_unpack() to do the job

Parameters

bull app (str) ndash new application name

bull fobj (obj) ndash file object containing the application to be installed

bull request ndash the global request object

bull filename (str) ndash original filename of the fobj required to determine extension

bull overwrite (bool) ndash force overwrite of existing application

Returns name of the file where app is temporarily stored or None on failure

gluonadminapp_pack(app request raise_ex=False filenames=None)Builds a w2p package for the application

Parameters

bull app (str) ndash application name

bull request ndash the global request object

Returns filename of the w2p file or None on error

gluonadminapp_pack_compiled(app request raise_ex=False)Builds a w2p bytecode-compiled package for the application

Parameters

bull app (str) ndash application name

bull request ndash the global request object

Returns filename of the w2p file or None on error

gluonadminapp_uninstall(app request)Uninstalls the application

Parameters

bull app (str) ndash application name

bull request ndash the global request object

Returns True on success False on failure

4 Chapter 1 admin Module

web2py Documentation Release 2146-stable

gluonadmincheck_new_version(myversion version_url)Compares current web2pyrsquos version with the latest stable web2py version

Parameters

bull myversion ndash the current version as stored in file web2pyVERSION

bull version_URL ndash the URL that contains the version of the latest stable release

Returns

state version

bull state True if upgrade available False if current version is up-to-date -1 on error

bull version the most up-to-version available

Return type tuple

gluonadmincreate_missing_app_folders(request)

gluonadmincreate_missing_folders()

gluonadminplugin_install(app fobj request filename)Installs a plugin

bull Identifies file type by filename

bull Writes fobj contents to the deposit folder

bull Calls w2p_unpack_plugin() to do the job

Parameters

bull app (str) ndash new application name

bull fobj ndash file object containing the application to be installed

bull request ndash the global request object

bull filename ndash original filename of the fobj required to determine extension

Returns name of the file where plugin is temporarily stored or False on failure

gluonadminplugin_pack(app plugin_name request)Builds a w2p package for the plugin

Parameters

bull app (str) ndash application name

bull plugin_name (str) ndash the name of the plugin without plugin_ prefix

bull request ndash the current request app

Returns filename of the w2p file or False on error

gluonadminunzip(filename dir subfolder=rdquo)Unzips filename into dir (zip only no gz etc)

Parameters

bull filename (str) ndash archive

bull dir (str) ndash destination

bull subfolder (str) ndash if = lsquorsquo unzips only files in subfolder

11 Utility functions for the Admin application 5

web2py Documentation Release 2146-stable

gluonadminupgrade(request url=rsquohttpweb2pycomrsquo)Upgrades web2py (src osx win) if a new version is posted It detects whether src osx or win is running anddownloads the right one

Parameters

bull request ndash the current request object (required to determine version and path)

bull url ndash the incomplete url where to locate the latest web2py (actual url isurl+rsquoexamplesstaticweb2py_(src|osx|win)ziprsquo)

Returns tuple completed traceback

bull completed True on success False on failure (network problem or old version)

bull traceback None on success raised exception details on failure

6 Chapter 1 admin Module

CHAPTER 2

cache Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

21 Basic caching classes and methods

bull Cache - The generic caching object interfacing with the others

bull CacheInRam - providing caching in ram

bull CacheOnDisk - provides caches on disk

Memcache is also available via a different module (see gluoncontribmemcache)

When web2py is running on Google App Engine caching will be provided by the GAE memcache (seegluoncontribgae_memcache)

class gluoncacheCache(request)Bases object

Sets up generic caching creating an instance of both CacheInRam and CacheOnDisk In case of GAE will makeuse of gluoncontribgae_memcache

bull selfram is an instance of CacheInRam

bull selfdisk is an instance of CacheOnDisk

action(time_expire=300 cache_model=None prefix=None session=False vars=True lang=Trueuser_agent=False public=True valid_statuses=None quick=None)

Better fit for caching an action

Warning Experimental

7

web2py Documentation Release 2146-stable

Currently only HTTP 11 compliant reference httpcodegooglecompdoctype-mirrorwikiArticleHttpCaching

Parameters

bull time_expire (int) ndash same as cache

bull cache_model (str) ndash same as cache

bull prefix (str) ndash add a prefix to the calculated key

bull session (bool) ndash adds responsesession_id to the key

bull vars (bool) ndash adds requestenvquery_string

bull lang (bool) ndash adds Taccepted_language

bull user_agent (bool or dict) ndash if True adds is_mobile and is_tablet tothe key Pass a dict to use all the needed values (uses str(items())) (eguser_agent=requestuser_agent()) Used only if session is not True

bull public (bool) ndash if False forces the Cache-Control to be lsquoprivatersquo

bull valid_statuses ndash by default only status codes starting with 123 will be cached passan explicit list of statuses on which turn the cache on

bull quick ndash SessionVarsLangUser-agentPublic fast overrides with initials eg lsquoSVLPrsquoor lsquoVLPrsquo or lsquoVLPrsquo

autokey = (name)s(args)s(vars)s

static with_prefix(cache_model prefix)allow replacing cacheram with cachewith_prefix(cacheramrsquoprefixrsquo) it will add prefix to all the cachekeys used

gluoncachelazy_cache(key=None time_expire=None cache_model=rsquoramrsquo)Can be used to cache any function including ones in modules as long as the cached function is only calledwithin a web2py request

If a key is not provided one is generated from the function name time_expire defaults to None (no cacheexpiration)

If cache_model is ldquoramrdquo then the model is currentcacheram etc

8 Chapter 2 cache Module

CHAPTER 3

cfs Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

31 Functions required to execute app components

Note FOR INTERNAL USE ONLY

gluoncfsgetcfs(key filename filter=None)Caches the filtered file filename with key until the file is modified

Parameters

bull key (str) ndash the cache key

bull filename ndash the file to cache

bull filter ndash is the function used for filtering Normally filename is a py file and filter is afunction that bytecode compiles the file In this way the bytecode compiled file is cached(Default = None)

This is used on Google App Engine since pyc files cannot be saved

9

web2py Documentation Release 2146-stable

10 Chapter 3 cfs Module

CHAPTER 4

compileapp Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

41 Functions required to execute app components

Note FOR INTERNAL USE ONLY

gluoncompileappLOAD(c=None f=rsquoindexrsquo args=None vars=None extension=None target=Noneajax=False ajax_trap=False url=None user_signature=False time-out=None times=1 content=rsquoloadingrsquo post_vars= attr)

LOADs a component into the actionrsquos document

Parameters

bull c (str) ndash controller

bull f (str) ndash function

bull args (tuple or list) ndash arguments

bull vars (dict) ndash vars

bull extension (str) ndash extension

bull target (str) ndash id of the target

bull ajax (bool) ndash True to enable AJAX bahaviour

bull ajax_trap (bool) ndash True if ajax is set to True traps both links and forms ldquoinsiderdquo thetarget

bull url (str) ndash overrides clsquoflsquolsquoargslsquo and vars

11

web2py Documentation Release 2146-stable

bull user_signature (bool) ndash adds hmac signature to all links with a key that is differentfor every user

bull timeout (int) ndash in milliseconds specifies the time to wait before starting the request orthe frequency if times is greater than 1 or ldquoinfinityrdquo

bull times (integer or str) ndash how many times the component will be requested ldquoinfin-ityrdquo or ldquocontinuousrdquo are accepted to reload indefinitely the component

class gluoncompileappLoadFactory(environment)Bases object

Attention this helper is new and experimental

gluoncompileappbuild_environment(request response session store_current=True)Build the environment dictionary into which web2py files are executed

gluoncompileappcompile_application(folder skip_failed_views=False)Compiles all models views controller for the application in folder

gluoncompileappcompile_controllers(folder)Compiles all the controllers in the application specified by folder

gluoncompileappcompile_models(folder)Compiles all the models in the application specified by folder

gluoncompileappcompile_views(folder skip_failed_views=False)Compiles all the views in the application specified by folder

gluoncompileappfind_exposed_functions(data)

gluoncompileapplocal_import_aux(name reload_force=False app=rsquowelcomersquo)In apps instead of importing a local module (in applicationsappmodules) with

import abc as d

you should do

d = local_import(abc)

or (to force a reload)

d = local_import(lsquoabcrsquo reload=True)

This prevents conflict between applications and un-necessary execs It can be used to import any moduleincluding regular Python modules

gluoncompileappmodel_cmp(a b sep=rsquorsquo)

gluoncompileappmodel_cmp_sep(a b sep=rsquorsquo)

class gluoncompileappmybuiltinBases object

NOTE could simple use a dict and populate it NOTE not sure if this changes things though if monkey patchingimport

gluoncompileappre_compile(regex)

gluoncompileappread_pyc(filename)Read the code inside a bytecode compiled file if the MAGIC number is compatible

Returns a code object

12 Chapter 4 compileapp Module

web2py Documentation Release 2146-stable

gluoncompileappremove_compiled_application(folder)Deletes the folder compiled containing the compiled application

gluoncompileapprun_controller_in(controller function environment)Runs the controllerfunction() (for the app specified by the current folder) It tries pre-compiled con-troller_functionpyc first before compiling it

gluoncompileapprun_models_in(environment)Runs all models (in the app specified by the current folder) It tries pre-compiled models first before compilingthem

gluoncompileapprun_view_in(environment)Executes the view for the requested action The view is the one specified in responseview or determined by theurl or viewgenericextension It tries the pre-compiled views_controller_functionpyc before compiling it

gluoncompileappsave_pyc(filename)Bytecode compiles the file filename

gluoncompileapptest()Example

gtgtgt import traceback typesgtgtgt environment=x1gtgtgt open(apy w)write(print 1x)gtgtgt save_pyc(apy)gtgtgt osunlink(apy)gtgtgt if type(read_pyc(apyc))==typesCodeType print codecodegtgtgt exec read_pyc(apyc) in environment1

41 Functions required to execute app components 13

web2py Documentation Release 2146-stable

14 Chapter 4 compileapp Module

CHAPTER 5

contenttype Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

CONTENT_TYPE dictionary created against freedesktoporgrsquos shared mime info database version 11

Deviations from official standards

bull md applicationx-genesis-rom ndashgt textx-markdown

bull png imagex-apple-ios-png ndashgt imagepng

Additions

bull load texthtml

bull json applicationjson

bull jsonp applicationjsonp

bull pickle applicationpython-pickle

bull w2prsquo applicationw2p

gluoncontenttypecontenttype(filename default=rsquotextplainrsquo)Returns the Content-Type string matching extension of the given filename

15

web2py Documentation Release 2146-stable

16 Chapter 5 contenttype Module

CHAPTER 6

custom_import Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

61 Support for smart import syntax for web2py applications

exception gluoncustom_importCustomImportExceptionBases exceptionsImportError

class gluoncustom_importTrackImporterBases object

An importer tracking the date of the module files and reloading them when they are changed

PACKAGE_PATH_SUFFIX = __init__py

THREAD_LOCAL = ltthread_local objectgt

gluoncustom_importcustom_import_install()

gluoncustom_importcustom_importer(name globals=None locals=None fromlist=Nonelevel=-1)

web2pyrsquos custom importer It behaves like the standard Python importer but it tries to transform importstatements as something like ldquoimport applicationsapp_namemodulesxrdquo If the import fails it falls back onnaive_importer

gluoncustom_importis_tracking_changes()

gluoncustom_importtrack_changes(track=True)

17

web2py Documentation Release 2146-stable

18 Chapter 6 custom_import Module

CHAPTER 7

dal Module

Go to httppydalreadthedocsorgenlatest for docs on pyDAL

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

71 Takes care of adapting pyDAL to web2pyrsquos needs

19

web2py Documentation Release 2146-stable

20 Chapter 7 dal Module

CHAPTER 8

debug Module

This file is part of the web2py Web FrameworkDeveloped by Massimo Di Pierro ltmdipierrocsdepauledugtlimodou ltlimodougmailcomgt and srackham ltsrackhamgmailcomgtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

81 Debugger support classes

class gluondebugPipe(name mode=rsquorrsquo args kwargs)Bases QueueQueue

flush()

read(count=None timeout=None)

readline()

write(data)

class gluondebugWebDebugger(pipe completekey=rsquotabrsquo stdin=None stdout=None)Bases gluoncontribqdbFrontend

Qdb web2py interface

clear_interaction()

do_continue(args kwargs)

do_exec(statement)

do_next(args kwargs)

do_quit(args kwargs)

do_return(args kwargs)

do_step(args kwargs)

21

web2py Documentation Release 2146-stable

exception(title extype exvalue trace request)Show a user_exception

interaction(filename lineno line context)

run()Main method dispatcher (infinite loop)

gluondebugcheck_interaction(fn)Decorator to clean and prevent interaction when not available

gluondebugcommunicate(command=None)send command to debbuger wait result

gluondebugset_trace()breakpoint shortcut (like pdb)

gluondebugstop_trace()stop waiting for the debugger (called atexit)

22 Chapter 8 debug Module

CHAPTER 9

decoder Module

Caller will hand this library a buffer and ask it to either convert it or auto-detect the type

Based on httpcodeactivestatecomrecipes52257

Licensed under the PSF License

gluondecoderautoDetectXMLEncoding(buffer)buffer -gt encoding_name The buffer should be at least 4 bytes long Returns None if encoding cannot bedetected Note that encoding_name might not have an installed decoder (eg EBCDIC)

gluondecoderdecoder(buffer)

23

web2py Documentation Release 2146-stable

24 Chapter 9 decoder Module

CHAPTER 10

fileutils Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

101 File operations

gluonfileutilsparse_version(version)Attempts to parse SemVer fallbacks on legacy

gluonfileutilsread_file(filename mode=rsquorrsquo)Returns content from filename making sure to close the file explicitly on exit

gluonfileutilswrite_file(filename value mode=rsquowrsquo)Writes ltvaluegt to filename making sure to close the file explicitly on exit

gluonfileutilsreadlines_file(filename mode=rsquorrsquo)Applies split(lsquo lsquo) to the output of read_file()

gluonfileutilsup(path)

gluonfileutilsabspath(relpath base)Converts relative path to absolute path based (by default) on applications_parent

gluonfileutilsmktree(path)

gluonfileutilslistdir(path expression=rsquo^+$rsquo drop=True add_dirs=False sort=Truemaxnum=None exclude_content_from=None)

Like oslistdir() but you can specify a regex pattern to filter files If add_dirs is True the returned items willhave the full path

gluonfileutilsrecursive_unlink(f)Deletes f If itrsquos a folder also its contents will be deleted

gluonfileutilscleanpath(path)Turns any expressionpath into a valid filename replaces with _ and removes special characters

25

web2py Documentation Release 2146-stable

gluonfileutilstar(file dir expression=rsquo^+$rsquo filenames=None exclude_content_from=None)Tars dir into file only tars file that match expression

gluonfileutilsuntar(file dir)Untar file into dir

gluonfileutilstar_compiled(file dir expression=rsquo^+$rsquo exclude_content_from=None)Used to tar a compiled application The content of models views controllers is not stored in the tar file

gluonfileutilsget_session(request other_application=rsquoadminrsquo)Checks that user is authorized to access other_application

gluonfileutilscheck_credentials(request other_application=rsquoadminrsquo expiration=3600gae_login=True)

Checks that user is authorized to access other_application

gluonfileutilsw2p_pack(filename path compiled=False filenames=None)Packs a web2py application

Parameters

bull filename (str) ndash path to the resulting archive

bull path (str) ndash path to the application

bull compiled (bool) ndash if True packs the compiled version

bull filenames (list) ndash adds filenames to the archive

gluonfileutilsw2p_unpack(filename path delete_tar=True)

gluonfileutilsw2p_pack_plugin(filename path plugin_name)Packs the given plugin into a w2p file Will match files at

ltpathgtplugin_[name]ltpathgtplugin_[name]

gluonfileutilsw2p_unpack_plugin(filename path delete_tar=True)

gluonfileutilsfix_newlines(path)

gluonfileutilsmake_fake_file_like_object()

26 Chapter 10 fileutils Module

CHAPTER 11

globals Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

Contains the classes for the global used variables

bull Request

bull Response

bull Session

class gluonglobalsRequest(env)Bases gluonstorageStorage

Defines the request object and the default values of its members

bull env environment variables by gluonmainwsgibase()

bull cookies

bull get_vars

bull post_vars

bull vars

bull folder

bull application

bull function

bull args

bull extension

bull now datetimedatetimenow()

27

web2py Documentation Release 2146-stable

bull utcnow datetimedatetimeutcnow()

bull is_local

bull is_https

bull restful()

body

compute_uuid()

get_varsLazily parses the query string into get_vars

parse_all_vars()Merges get_vars and post_vars to vars

parse_get_vars()Takes the QUERY_STRING and unpacks it to get_vars

parse_post_vars()Takes the body of the request and unpacks it into post_vars applicationjson is also automatically parsed

post_varsLazily parse the body into post_vars

requires_https()If request comes in over HTTP redirects it to HTTPS and secures the session

restful()

user_agent()

uuidLazily uuid

varsLazily parses all get_vars and post_vars to fill vars

class gluonglobalsResponseBases gluonstorageStorage

Defines the response object and the default values of its members responsewrite( ) can be used to write in theoutput html

download(request db chunk_size=65536 attachment=True download_filename=None)Example of usage in controller

def download()return responsedownload(request db)

Downloads from http downloadfilename

include_files(extensions=None)Includes files (usually in the head) Can minify and cache local files By default caches in ram for 5minutes To change responsecache_includes = (cache_method time_expire) Example (cachedisk 60) caches to disk for 1 minute

include_meta()

json(data default=None)

render(a b)

28 Chapter 11 globals Module

web2py Documentation Release 2146-stable

stream(stream chunk_size=65536 request=None attachment=False filename=None)If in a controller function

return responsestream(file 100)

the file content will be streamed at 100 bytes at the time

Parameters

bull stream ndash filename or read()able content

bull chunk_size (int) ndash Buffer size

bull request ndash the request object

bull attachment (bool) ndash prepares the correct headers to download the file as an attach-ment Usually creates a pop-up download window on browsers

bull filename (str) ndash the name for the attachment

Note for using the stream name (filename) with attachments the option must be explicitly set as functionparameter (will default to the last request argument otherwise)

toolbar()

write(data escape=True)

xmlrpc(request methods)assuming

def add(a b)return a+b

if a controller function ldquofuncrdquo

return responsexmlrpc(request [add])

the controller will be able to handle xmlrpc requests for the add function Example

import xmlrpclibconnection = xmlrpclibServerProxy(

httphostnameappcontrfunc)print connectionadd(3 4)

class gluonglobalsSessionBases gluonstorageStorage

Defines the session object and the default values of its members (None)

bull session_storage_type lsquofilersquo lsquodbrsquo or lsquocookiersquo

bull session_cookie_compression_level

bull session_cookie_expires cookie expiration

bull session_cookie_key for encrypted sessions in cookies

bull session_id a number or None if no session

bull session_id_name

bull session_locked

29

web2py Documentation Release 2146-stable

bull session_masterapp

bull session_new a new session obj is being created

bull session_hash hash of the pickled loaded session

bull session_pickled picked session

if session in cookie

bull session_data_name name of the cookie for session data

if session in db

bull session_db_record_id

bull session_db_table

bull session_db_unique_key

if session in file

bull session_file

bull session_filename

clear()rarr None Remove all items from D

clear_session_cookies()

connect(request=None response=None db=None tablename=rsquoweb2py_sessionrsquo master-app=None migrate=True separate=None check_client=False cookie_key=Nonecookie_expires=None compression_level=None)

Used in models allows to customize Session handling

Parameters

bull request ndash the request object

bull response ndash the response object

bull db ndash to storeretrieve sessions in db (a table is created)

bull tablename (str) ndash table name

bull masterapp (str) ndash points to anotherrsquos app sessions This enables a ldquoSSOrdquo environmentamong apps

bull migrate ndash passed to the underlying db

bull separate ndash with True creates a folder with the 2 initials of the session id Can also bea function eg

separate=lambda(session_name) session_name[-2]

bull check_client ndash if True sessions can only come from the same ip

bull cookie_key (str) ndash secret for cookie encryption

bull cookie_expires ndash sets the expiration of the cookie

bull compression_level (int) ndash 0-9 sets zlib compression on the data before the en-cryption

forget(response=None)

is_expired(seconds=3600)

is_new()

30 Chapter 11 globals Module

web2py Documentation Release 2146-stable

renew(clear_session=False)

save_session_id_cookie()

secure()

31

web2py Documentation Release 2146-stable

32 Chapter 11 globals Module

CHAPTER 12

highlight Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

gluonhighlighthighlight(code language link=rsquoexamplesglobalsvarsrsquo counter=1styles=None highlight_line=None context_lines=None at-tributes=None)

33

web2py Documentation Release 2146-stable

34 Chapter 12 highlight Module

CHAPTER 13

html Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

131 Template helpers

class gluonhtmlA(components attributes)Bases gluonhtmlDIV

Generates an A() link A() in web2py is really important and with the included web2pyjs allows lots of Ajaxinteractions in the page

On top of ldquousualrdquo _attributes it takes

Parameters

bull callback ndash an url to call but not redirect to

bull cid ndash if you want to load the _href into an element of the page (component) pass its id(without the ) here

bull delete ndash element to delete after calling callback

bull target ndash same thing as cid

bull confirm ndash text to display upon a callback with a delete

bull noconfirm ndash donrsquot display alert upon a callback with delete

tag = a

xml()generates the xml for this component

gluonhtmlASSIGNJS(kargs)

35

web2py Documentation Release 2146-stable

Example

ASSIGNJS(var1=lsquo1rsquo var2=lsquo2rsquo) will return the following javascript variables assignations

var var1 = ldquo1rdquo var var2 = ldquo2rdquo

Parameters kargs ndash Any keywords arguments and assigned values

Returns Javascript vars assignations for the keyvalue passed

class gluonhtmlB(components attributes)Bases gluonhtmlDIV

tag = b

class gluonhtmlBEAUTIFY(component attributes)Bases gluonhtmlDIV

Turns any list dictionary etc into decent looking html

Two special attributes are

bull sorted a function that takes the dict and returned sorted keys

bull keyfilter a function that takes a key and returns its representation or None if the key is to be skipped Bydefault key[1]==rsquo_rsquo is skipped

Examples

gtgtgt BEAUTIFY([a b hello world])xml()ltdivgtlttablegtlttrgtlttdgtltdivgtaltdivgtlttdgtlttrgtlttrgtlttdgtltdivgtbltdivgtlttdgtlttrgtlttrgtlttdgtrarr˓ltdivgtlttablegtlttrgtlttd style=font-weightboldvertical-aligntopgthellolttdgtlttdrarr˓style=vertical-aligntopgtlttdgtlttdgtltdivgtworldltdivgtlttdgtlttrgtlttablegtltdivgtltrarr˓tdgtlttrgtlttablegtltdivgt

static no_underscore(key)

tag = div

class gluonhtmlBODY(components attributes)Bases gluonhtmlDIV

tag = body

class gluonhtmlBR(components attributes)Bases gluonhtmlDIV

tag = br

class gluonhtmlBUTTON(components attributes)Bases gluonhtmlDIV

tag = button

class gluonhtmlCENTER(components attributes)Bases gluonhtmlDIV

tag = center

class gluonhtmlCAT(components attributes)Bases gluonhtmlDIV

tag =

36 Chapter 13 html Module

web2py Documentation Release 2146-stable

class gluonhtmlCODE(components attributes)Bases gluonhtmlDIV

Displays code in HTML with syntax highlighting

Parameters

bull language ndash indicates the language otherwise PYTHON is assumed

bull link ndash can provide a link

bull styles ndash for styles

Examples

=CODE(ldquoprint lsquohello worldrsquordquo language=rsquopythonrsquo link=None counter=1 styles= high-light_line=None)

supported languages are

ldquopythonrdquo ldquohtml_plainrdquo ldquocrdquo ldquocpprdquo ldquoweb2pyrdquo ldquohtmlrdquo

The ldquohtmlrdquo language interprets and tags as ldquoweb2pyrdquo code ldquohtml_plainrdquo doesnrsquot

if a link=rsquoexamplesglobalvarsrsquo is provided web2py keywords are linked to the online docs

the counter is used for line numbering counter can be None or a prompt string

xml()generates the xml for this component

class gluonhtmlCOL(components attributes)Bases gluonhtmlDIV

tag = col

class gluonhtmlCOLGROUP(components attributes)Bases gluonhtmlDIV

tag = colgroup

class gluonhtmlDIV(components attributes)Bases gluonhtmlXmlComponent

HTML helper for easy generating and manipulating a DOM structure Little or no validation is done

Behaves like a dictionary regarding updating of attributes Behaves like a list regarding insertingappendingcomponents

Examples

gtgtgt DIV(hello world _style=colorred)xml()ltdiv style=colorredgthelloworldltdivgt

All other HTML helpers are derived from DIV

_something=rdquovaluerdquo attributes are transparently translated into something=rdquovaluerdquo HTML attributes

append(value)list style appending of components

Examples

131 Template helpers 37

web2py Documentation Release 2146-stable

gtgtgt a=DIV()gtgtgt aappend(SPAN(x))gtgtgt print altdivgtltspangtxltspangtltdivgt

element(args kargs)Finds the first component that matches the supplied attribute dictionary or None if nothing could be found

Also the components of the components are searched

elements(args kargs)Find all components that match the supplied attribute dictionary or None if nothing could be found

All components of the components are searched

Examples

gtgtgt a = DIV(DIV(SPAN(x)3DIV(SPAN(y))))gtgtgt for c in aelements(span first_only=True) c[0]=zgtgtgt print altdivgtltdivgtltspangtzltspangt3ltdivgtltspangtyltspangtltdivgtltdivgtltdivgtgtgtgt for c in aelements(span) c[0]=zgtgtgt print altdivgtltdivgtltspangtzltspangt3ltdivgtltspangtzltspangtltdivgtltdivgtltdivgt

It also supports a syntax compatible with jQuery

Examples

gtgtgt a=TAG(ltdivgtltspangtlta id=1-1 uv=$gthelloltagtltspangtltp class=this is ararr˓testgtworldltpgtltdivgt)gtgtgt for e in aelements(div a1-1 pis) print eflatten()helloworldgtgtgt for e in aelements(1-1) print eflatten()hellogtgtgt aelements(a[uv=$])[0]xml()lta id=1-1 uv=$gthelloltagtgtgtgt a=FORM( INPUT(_type=text) SELECT(range(1)) TEXTAREA() )gtgtgt for c in aelements(input select textarea) c[_disabled] = disabledrarr˓gtgtgt axml()ltform action= enctype=multipartform-data method=postgtltinput disabled=rarr˓disabled type=text gtltselect disabled=disabledgtltoption value=0gt0ltrarr˓optiongtltselectgtlttextarea cols=40 disabled=disabled rows=10gtltrarr˓textareagtltformgt

Elements that are matched can also be replaced or removed by specifying a ldquoreplacerdquo argument (note alist of the original matching elements is still returned as usual)

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=abc) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(spanabc replace=P(x _class=xyz))gtgtgt print a We should xml() here instead of printltdivgtltdivgtltp class=xyzgtxltpgtltdivgtltp class=xyzgtxltpgtltp class=xyzgtxltpgtltrarr˓divgtltdivgtltdivgt

38 Chapter 13 html Module

web2py Documentation Release 2146-stable

ldquoreplacerdquo can be a callable which will be passed the original element and should return a new element toreplace it

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=abc) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(spanabc replace=lambda el P(el[0] _class=xyz))gtgtgt print altdivgtltdivgtltp class=xyzgtxltpgtltdivgtltp class=xyzgtyltpgtltp class=xyzgtzltpgtltrarr˓divgtltdivgtltdivgt

If replace=None matching elements will be removed completely

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=abc) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(span find=y replace=None)gtgtgt print altdivgtltdivgtltspan class=abcgtxltspangtltdivgtltspan class=abcgtzltspangtltdivgtltrarr˓divgtltdivgt

If a ldquofind_textrdquo argument is specified elements will be searched for text components that match find_textand any matching text components will be replaced (find_text is ignored if ldquoreplacerdquo is not also specified)Like the ldquofindrdquo argument ldquofind_textrdquo can be a string or a compiled regex

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=abc) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(find_text=recompile(x|y|z) replace=hello)gtgtgt print altdivgtltdivgtltspan class=abcgthelloltspangtltdivgtltspan class=abcgthelloltspangtrarr˓ltspan class=abcgthelloltspangtltdivgtltdivgtltdivgt

If other attributes are specified along with find_text then only components that match the specified at-tributes will be searched for find_text

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=efg) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(spanefg find_text=recompile(x|y|z) replace=hello)gtgtgt print altdivgtltdivgtltspan class=abcgtxltspangtltdivgtltspan class=efggthelloltspangtltspanrarr˓class=abcgtzltspangtltdivgtltdivgtltdivgt

flatten(render=None)Returns the text stored by the DIV object rendered by the render function the render function must taketext tagname and attributes render=None is equivalent to render=lambda text tag attr text

Examples

gtgtgt markdown = lambda text tag=None attributes=rarr˓None resub(s+ text) h1+text+nnrarr˓ ptext+nget(tagtext)gtgtgt a=TAG(lth1gtHeaderlth1gtltpgtthis is a testltpgt)gtgtgt aflatten(markdown)Headernnthis is a testn

131 Template helpers 39

web2py Documentation Release 2146-stable

get(i)

insert(i value)List-style inserting of components

Examples

gtgtgt a=DIV()gtgtgt ainsert(0 SPAN(x))gtgtgt print altdivgtltspangtxltspangtltdivgt

regex_attr = lt_sreSRE_Pattern objectgt

regex_class = lt_sreSRE_Pattern objectgt

regex_id = lt_sreSRE_Pattern objectgt

regex_tag = lt_sreSRE_Pattern objectgt

sibling(args kargs)Finds the first sibling component that match the supplied argument list and attribute dictionary or None ifnothing could be found

siblings(args kargs)Finds all sibling components that match the supplied argument list and attribute dictionary or None ifnothing could be found

tag = div

update(kargs)dictionary like updating of the tag attributes

xml()generates the xml for this component

class gluonhtmlEM(components attributes)Bases gluonhtmlDIV

tag = em

class gluonhtmlEMBED(components attributes)Bases gluonhtmlDIV

tag = embed

class gluonhtmlFIELDSET(components attributes)Bases gluonhtmlDIV

tag = fieldset

class gluonhtmlFORM(components attributes)Bases gluonhtmlDIV

Examples

gtgtgt from validators import IS_NOT_EMPTYgtgtgt form=FORM(INPUT(_name=test requires=IS_NOT_EMPTY()))gtgtgt formxml()ltform action= enctype=multipartform-data method=postgtltinput name=testrarr˓type=text gtltformgt

a FORM is container for INPUT TEXTAREA SELECT and other helpers

form has one important method

40 Chapter 13 html Module

web2py Documentation Release 2146-stable

formaccepts(requestvars session)

if form is accepted (and all validators pass) formvars contains the accepted vars otherwise formerrors containsthe errors in case of errors the form is modified to present the errors to the user

REDIRECT_JS = windowlocation=sreturn false

accepts(request_vars session=None formname=rsquodefaultrsquo keepvalues=False onvalidation=Nonehideerror=False kwargs)

kwargs is not used but allows to specify the same interface for FORM and SQLFORM

add_button(value url _class=None)

as_dict(flat=False sanitize=True)EXPERIMENTAL

Sanitize is naive It should catch any unsafe value for client retrieval

as_json(sanitize=True)

as_xml(sanitize=True)

as_yaml(sanitize=True)

assert_status(status request_vars)

static confirm(text=rsquoOKrsquo buttons=None hidden=None)

hidden_fields()

process(kwargs)Perform the validate() method but returns the form

Usage in controllers

directly on returndef action()

some code herereturn dict(form=FORM()process())

You can use it with FORM SQLFORM or FORM based plugins

responseflash messagesdef action()

form = SQLFORM(dbtable)process(message_onsuccess=Sucess)return dict(form=form)

callback function callback receives True or False as first arg and a list of argsdef my_callback(status msg)

responseflash = Success +msg if status else Errors occured

after argument can be flash to responseflash messages or a function name to use as callback or None to do nothingdef action()

return dict(form=SQLFORM(dbtable)process(onsuccess=my_callback)

tag = form

validate(kwargs)This function validates the form you can use it instead of directly formaccepts

Usage In controller

131 Template helpers 41

web2py Documentation Release 2146-stable

def action()form=FORM(INPUT(_name=test requires=IS_NOT_EMPTY()))formvalidate() you can pass some args here - see belowreturn dict(form=form)

This can receive a bunch of arguments

onsuccess = lsquoflashrsquo - will show message_onsuccess in responseflash None - will do nothing can be afunction (lambda form pass)

onfailure = lsquoflashrsquo - will show message_onfailure in responseflash None - will do nothing can be afunction (lambda form pass)

onchange = lsquoflashrsquo - will show message_onchange in responseflash None - will do nothing can be afunction (lambda form pass)

message_onsuccess message_onfailure message_onchange next = where to redirect in case of success anyother kwargs will be passed for formaccepts( )

xml()generates the xml for this component

class gluonhtmlH1(components attributes)Bases gluonhtmlDIV

tag = h1

class gluonhtmlH2(components attributes)Bases gluonhtmlDIV

tag = h2

class gluonhtmlH3(components attributes)Bases gluonhtmlDIV

tag = h3

class gluonhtmlH4(components attributes)Bases gluonhtmlDIV

tag = h4

class gluonhtmlH5(components attributes)Bases gluonhtmlDIV

tag = h5

class gluonhtmlH6(components attributes)Bases gluonhtmlDIV

tag = h6

class gluonhtmlHEAD(components attributes)Bases gluonhtmlDIV

tag = head

class gluonhtmlHR(components attributes)Bases gluonhtmlDIV

tag = hr

class gluonhtmlHTML(components attributes)Bases gluonhtmlDIV

42 Chapter 13 html Module

web2py Documentation Release 2146-stable

There are four predefined document type definitions They can be specified in the lsquodoctypersquo parameter

bull lsquostrictrsquo enables strict doctype

bull lsquotransitionalrsquo enables transitional doctype (default)

bull lsquoframesetrsquo enables frameset doctype

bull lsquohtml5rsquo enables HTML 5 doctype

bull any other string will be treated as userrsquos own doctype

lsquolangrsquo parameter specifies the language of the document Defaults to lsquoenrsquo

See also DIV

frameset = ltDOCTYPE HTML PUBLIC -W3CDTD HTML 401 FramesetEN httpwwww3orgTRhtml4framesetdtdgtn

html5 = ltDOCTYPE HTMLgtn

strict = ltDOCTYPE HTML PUBLIC -W3CDTD HTML 401EN httpwwww3orgTRhtml4strictdtdgtn

tag = html

transitional = ltDOCTYPE HTML PUBLIC -W3CDTD HTML 401 TransitionalEN httpwwww3orgTRhtml4loosedtdgtn

xml()generates the xml for this component

class gluonhtmlI(components attributes)Bases gluonhtmlDIV

tag = i

class gluonhtmlIFRAME(components attributes)Bases gluonhtmlDIV

tag = iframe

class gluonhtmlIMG(components attributes)Bases gluonhtmlDIV

tag = img

class gluonhtmlINPUT(components attributes)Bases gluonhtmlDIV

INPUT Component

Takes two special attributes value= and requires=

Parameters

bull value ndash used to pass the initial value for the input field value differs from _value becauseit works for checkboxes radio textarea and selectoption too For a checkbox value shouldbe lsquorsquo or lsquoonrsquo For a radio or selectoption value should be the _value of the checkedselecteditem

bull requires ndash should be None or a validator or a list of validators for the value of the field

Examples

gtgtgt INPUT(_type=text _name=name value=Max)xml()ltinput name=name type=text value=Max gt

gtgtgt INPUT(_type=checkbox _name=checkbox value=on)xml()ltinput checked=checked name=checkbox type=checkbox value=on gt

131 Template helpers 43

web2py Documentation Release 2146-stable

gtgtgt INPUT(_type=radio _name=radio _value=yes value=yes)xml()ltinput checked=checked name=radio type=radio value=yes gt

gtgtgt INPUT(_type=radio _name=radio _value=no value=yes)xml()ltinput name=radio type=radio value=no gt

tag = input

xml()generates the xml for this component

class gluonhtmlLABEL(components attributes)Bases gluonhtmlDIV

tag = label

class gluonhtmlLEGEND(components attributes)Bases gluonhtmlDIV

tag = legend

class gluonhtmlLI(components attributes)Bases gluonhtmlDIV

tag = li

class gluonhtmlLINK(components attributes)Bases gluonhtmlDIV

tag = link

class gluonhtmlOL(components attributes)Bases gluonhtmlUL

tag = ol

class gluonhtmlUL(components attributes)Bases gluonhtmlDIV

UL Component

If subcomponents are not LI-components they will be wrapped in a LI

tag = ul

class gluonhtmlMARKMIN(text extra=None allowed=None sep=rsquoprsquo url=None environ-ment=None latex=rsquogooglersquo autolinks=rsquodefaultrsquo protolinks=rsquodefaultrsquoclass_prefix=rdquo id_prefix=rsquomarkmin_rsquo kwargs)

Bases gluonhtmlXmlComponent

For documentation httpweb2pycomexamplesstaticmarkminhtml

flatten()

xml()

class gluonhtmlMENU(data args)Bases gluonhtmlDIV

Used to build menus

Parameters

bull _class ndash defaults to lsquoweb2py-menu web2py-menu-verticalrsquo

bull ul_class ndash defaults to lsquoweb2py-menu-verticalrsquo

44 Chapter 13 html Module

web2py Documentation Release 2146-stable

bull li_class ndash defaults to lsquoweb2py-menu-expandrsquo

bull li_first ndash defaults to lsquoweb2py-menu-firstrsquo

bull li_last ndash defaults to lsquoweb2py-menu-lastrsquo

Use like

menu = MENU([[name False URL() [submenu]] ])=menu

serialize(data level=0)

serialize_mobile(data select=None prefix=rdquo)

tag = ul

xml()generates the xml for this component

class gluonhtmlMETA(components attributes)Bases gluonhtmlDIV

tag = meta

class gluonhtmlOBJECT(components attributes)Bases gluonhtmlDIV

tag = object

class gluonhtmlOPTION(components attributes)Bases gluonhtmlDIV

tag = option

class gluonhtmlP(components attributes)Bases gluonhtmlDIV

Will replace n by ltbr gt if the cr2br attribute is provided

see also DIV

tag = p

xml()generates the xml for this component

class gluonhtmlPRE(components attributes)Bases gluonhtmlDIV

tag = pre

class gluonhtmlSCRIPT(components attributes)Bases gluonhtmlDIV

tag = script

xml()generates the xml for this component

class gluonhtmlOPTGROUP(components attributes)Bases gluonhtmlDIV

tag = optgroup

131 Template helpers 45

web2py Documentation Release 2146-stable

class gluonhtmlSELECT(components attributes)Bases gluonhtmlINPUT

Examples

gtgtgt from validators import IS_IN_SETgtgtgt SELECT(yes no _name=selector value=yes requires=IS_IN_SET([yes no]))xml()ltselect name=selectorgtltoption selected=selected value=yesgtyesltoptiongtrarr˓ltoption value=nogtnoltoptiongtltselectgt

tag = select

class gluonhtmlSPAN(components attributes)Bases gluonhtmlDIV

tag = span

class gluonhtmlSTRONG(components attributes)Bases gluonhtmlDIV

tag = strong

class gluonhtmlSTYLE(components attributes)Bases gluonhtmlDIV

tag = style

xml()generates the xml for this component

class gluonhtmlTABLE(components attributes)Bases gluonhtmlDIV

TABLE Component

If subcomponents are not TRTBODYTHEADTFOOT-components they will be wrapped in a TR

tag = table

gluonhtmlTAGTAG factory

Examples

gtgtgt print TAGfirst(TAGsecond(test) _key = 3)ltfirst key=3gtltsecondgttestltsecondgtltfirstgt

class gluonhtmlTD(components attributes)Bases gluonhtmlDIV

tag = td

class gluonhtmlTEXTAREA(components attributes)Bases gluonhtmlINPUT

Examples

TEXTAREA(_name=sometext value=blah 100 requires=IS_NOT_EMPTY())

lsquoblah blah blah rsquo will be the content of the textarea field

tag = textarea

46 Chapter 13 html Module

web2py Documentation Release 2146-stable

class gluonhtmlTH(components attributes)Bases gluonhtmlDIV

tag = th

class gluonhtmlTHEAD(components attributes)Bases gluonhtmlDIV

tag = thead

class gluonhtmlTBODY(components attributes)Bases gluonhtmlDIV

tag = tbody

class gluonhtmlTFOOT(components attributes)Bases gluonhtmlDIV

tag = tfoot

class gluonhtmlTITLE(components attributes)Bases gluonhtmlDIV

tag = title

class gluonhtmlTR(components attributes)Bases gluonhtmlDIV

TR Component

If subcomponents are not TDTH-components they will be wrapped in a TD

tag = tr

class gluonhtmlTT(components attributes)Bases gluonhtmlDIV

tag = tt

gluonhtmlURL(a=None c=None f=None r=None args=None vars=None an-chor=rdquo extension=None env=None hmac_key=None hash_vars=Truesalt=None user_signature=None scheme=None host=None port=None en-code_embedded_slash=False url_encode=True language=None)

generates a url lsquoacfrsquo corresponding to application a controller c and function f If r=request is passed a c fare set respectively to rapplication rcontroller rfunction

The more typical usage is

URL(lsquoindexrsquo)

that generates a url for the index function within the present application and controller

Parameters

bull a ndash application (default to current if r is given)

bull c ndash controller (default to current if r is given)

bull f ndash function (default to current if r is given)

bull r ndash request (optional)

bull args ndash any arguments (optional) Additional ldquopathrdquo elements

bull vars ndash any variables (optional) Querystring elements

bull anchor ndash anchorname without (optional)

131 Template helpers 47

web2py Documentation Release 2146-stable

bull extension ndash force an extension

bull hmac_key ndash key to use when generating hmac signature (optional)

bull hash_vars ndash which of the vars to include in our hmac signature True (default) - hash allvars False - hash none of the vars iterable - hash only the included vars [lsquokey1rsquorsquokey2rsquo]

bull salt ndash salt hashing with this string

bull user_signature ndash signs automatically the URL in such way that only the user canaccess the URL (use with URLverify or authrequires_signature())

bull scheme ndash URI scheme (True lsquohttprsquo or lsquohttpsrsquo etc) forces absolute URL (optional)

bull host ndash string to force absolute URL with host (True means http_host)

bull port ndash optional port number (forces absolute URL)

bull encode_embedded_slash ndash encode slash characters included in args

bull url_encode ndash encode characters included in vars

Raises SyntaxError ndash when no application controller or function is available or when a CRLFis found in the generated url

Examples

gtgtgt str(URL(a=a c=c f=f args=[x y z] vars=p1 q2 anchor=1))acfxyzp=1ampq=21

gtgtgt str(URL(a=a c=c f=f args=[x y z] vars=p(13) q2 anchor=1))acfxyzp=1ampp=3ampq=21

gtgtgt str(URL(a=a c=c f=f args=[x y z] vars=p(31) q2 anchor=1))acfxyzp=3ampp=1ampq=21

gtgtgt str(URL(a=a c=c f=f anchor=1+2))acf12B2

gtgtgt str(URL(a=a c=c f=f args=[x y z] vars=p(13) q2 anchor=1 hmac_key=key))acfxyzp=1ampp=3ampq=2amp_signature=a32530f0d0caa80964bb92aad2bedf8a4486a31f1

gtgtgt str(URL(a=a c=c f=f args=[wx yz]))acfwxyz

gtgtgt str(URL(a=a c=c f=f args=[wx yz] encode_embedded_slash=True))acfw2Fxy2Fz

gtgtgt str(URL(a=a c=c f=f args=[(id)d] url_encode=False))acf(id)d

gtgtgt str(URL(a=a c=c f=f args=[(id)d] url_encode=True))acf2528id29d

48 Chapter 13 html Module

web2py Documentation Release 2146-stable

gtgtgt str(URL(a=a c=c f=f vars=id (id)d url_encode=False))acfid=(id)d

gtgtgt str(URL(a=a c=c f=f vars=id (id)d url_encode=True))acfid=2528id29d

gtgtgt str(URL(a=a c=c f=f anchor=(id)d url_encode=False))acf(id)d

gtgtgt str(URL(a=a c=c f=f anchor=(id)d url_encode=True))acf2528id29d

class gluonhtmlXHTML(components attributes)Bases gluonhtmlDIV

This is XHTML version of the HTML helper

There are three predefined document type definitions They can be specified in the lsquodoctypersquo parameter

bull lsquostrictrsquo enables strict doctype

bull lsquotransitionalrsquo enables transitional doctype (default)

bull lsquoframesetrsquo enables frameset doctype

bull any other string will be treated as userrsquos own doctype

lsquolangrsquo parameter specifies the language of the document and the xml document Defaults to lsquoenrsquo

lsquoxmlnsrsquo parameter specifies the xml namespace Defaults to lsquohttpwwww3org1999xhtmlrsquo

See also DIV

frameset = ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 FramesetEN httpwwww3orgTRxhtml1DTDxhtml1-framesetdtdgtn

strict = ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgtn

tag = html

transitional = ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 TransitionalEN httpwwww3orgTRxhtml1DTDxhtml1-transitionaldtdgtn

xml()generates the xml for this component

xmlns = httpwwww3org1999xhtml

class gluonhtmlXML(text sanitize=False permitted_tags=[rsquoarsquo rsquobrsquo rsquoblockquotersquo rsquobrrsquo rsquoirsquo rsquolirsquo rsquoolrsquorsquoulrsquo rsquoprsquo rsquocitersquo rsquocodersquo rsquoprersquo rsquoimgrsquo rsquoh1rsquo rsquoh2rsquo rsquoh3rsquo rsquoh4rsquo rsquoh5rsquo rsquoh6rsquo rsquotablersquo rsquotrrsquorsquotdrsquo rsquodivrsquo rsquostrongrsquo rsquospanrsquo] allowed_attributes=rsquoarsquo [rsquohrefrsquo rsquotitlersquo rsquotargetrsquo]rsquoblockquotersquo [rsquotypersquo] rsquoimgrsquo [rsquosrcrsquo rsquoaltrsquo] rsquotdrsquo [rsquocolspanrsquo])

Bases gluonhtmlXmlComponent

use it to wrap a string that contains XMLHTML so that it will not be escaped by the template

Examples

gtgtgt XML(lth1gtHellolth1gt)xml()lth1gtHellolth1gt

elements(args kargs)to be considered experimental since the behavior of this method is questionable another option could beTAG(selftext)elements(args kwargs)

131 Template helpers 49

web2py Documentation Release 2146-stable

flatten(render=None)returns the text stored by the XML object rendered by the render function

xml()

gluonhtmlxmlescape(data quote=True)Returns an escaped string of the provided data

Parameters

bull data ndash the data to be escaped

bull quote ndash optional (default False)

gluonhtmlembed64(filename=None file=None data=None extension=rsquoimagegifrsquo)helper to encode the provided (binary) data into base64

Parameters

bull filename ndash if provided opens and reads this file in lsquorbrsquo mode

bull file ndash if provided reads this file

bull data ndash if provided uses the provided data

50 Chapter 13 html Module

CHAPTER 14

http Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

141 HTTP statuses helpers

exception gluonhttpHTTP(status body=rdquo cookies=None headers)Bases exceptionsException

Raises an HTTP response

Parameters

bull status ndash usually an integer If itrsquos a well known status code the ERROR message will beautomatically added A string can also be passed as 510 Foo Bar and in that case the statuscode and the error message will be parsed accordingly

bull body ndash what to return as body If left as is will return the error code and the status messagein the body itself

bull cookies ndash pass cookies along (usually not needed)

bull headers ndash pass headers as usual dict mapping

cookies2headers(cookies)

messagecompose a message describing this exception

ldquostatus defined_status [web2py_error]rdquo

message elements that are not defined are omitted

to(responder env=None)

51

web2py Documentation Release 2146-stable

gluonhttpredirect(location=rdquo how=303 client_side=False headers=None)Raises a redirect (303)

Parameters

bull location ndash the url where to redirect

bull how ndash what HTTP status code to use when redirecting

bull client_side ndash if set to True it triggers a reload of the entire page when the fragmenthas been loaded as a component

52 Chapter 14 http Module

CHAPTER 15

languages Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)Plural subsystem is created by Vladyslav Kozlovskyy (Ukraine) ltdbdevelopgmailcomgt

151 Translation system

class gluonlanguagestranslator(langpath http_accept_language)Bases object

This class is instantiated by gluoncompileappbuild_environment as the T object

Example

Tforce(None) turns off translation Tforce(lsquofr itrsquo) forces web2py to translate using frpy or itpy

T(ldquoHello Worldrdquo) translates ldquoHello Worldrdquo using the selected file

Note

bull there is no need to force since by default T uses http_accept_language to determine a translation file

bull en and en-en are considered different languages

bull if language xx-yy is not found force() probes other similar languages using such algorithm xx-yypy -gtxxpy -gt xx-yypy -gt xxpy

M(message symbols= language=None lazy=None filter=None ftag=None ns=None)Gets cached translated markmin-message with inserted parametes if lazy==True lazyT object is returned

apply_filter(message symbols= filter=None ftag=None)

53

web2py Documentation Release 2146-stable

force(languages)Selects language(s) for translation

if a list of languages is passed as a parameter the first language from this list that matches the ones fromthe possible_languages dictionary will be selected

default language will be selected if none of them matches possible_languages

get_possible_languages()Gets list of all possible languages for current application

get_possible_languages_info(lang=None)Returns info for selected language or dictionary with all possible languages info from APPlanguagespyIt Returns

bull a tuple containing

langcode langname langfile_mtimepluraldict_fname pluraldict_mtimeprules_langcode npluralsget_plural_id construct_plural_form

or None

bull if lang is NOT defined a dictionary with all possible languages

langcode(from filename)( langcode language code from langcodelangname

language name in national spelling from langnamelangfile_mtime m_time of language filepluraldict_fname name of plural dictionary file or None (when

rarr˓defaultpy is not exist)pluraldict_mtime m_time of plural dictionary file or 0 if file is

rarr˓not existprules_langcode code of plural rules language or defaultnplurals nplurals for current languageget_plural_id get_plural_id() for current languageconstruct_plural_form) construct_plural_form() for current

rarr˓language

Parameters lang (str) ndash language

get_t(message prefix=rdquo)Use to add a comment into a translation string the comment can be useful do discriminate differentpossible translations for the same string (for example different locations)

T( hello world ) -gt hello world T( hello world token) -gt hello world T(hello world token) -gt hello world

the notation is ignored in multiline strings and strings that start with This is needed to allow markminsyntax to be translated

params_substitution(message symbols)Substitutes parameters from symbols into message using also parse placeholders for plural-formsprocessing

Returns string with parameters

54 Chapter 15 languages Module

web2py Documentation Release 2146-stable

Note symbols MUST BE OR tuple OR dict of parameters

plural(word n)Gets plural form of word for number n invoked from T()TM() in tag

Note ldquowordrdquo MUST be defined in current language (Taccepted_language)

Parameters

bull word (str) ndash word in singular

bull n (numeric) ndash number plural form created for

Returns word in appropriate singularplural form

Return type word (str)

set_current_languages(languages)Sets current AKA ldquodefaultrdquo languages Setting one of this languages makes the force() function to turntranslation off

translate(message symbols)Gets cached translated message with inserted parameters(symbols)

gluonlanguagesfindT(path language=rsquoenrsquo)

Note Must be run by the admin app

gluonlanguagesupdate_all_languages(application_path)

Note Must be run by the admin app

151 Translation system 55

web2py Documentation Release 2146-stable

56 Chapter 15 languages Module

CHAPTER 16

main Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

161 The gluon wsgi application

gluonmainwsgibase(environ responder)The gluon wsgi application The first function called when a page is requested (static or dynamic) It can becalled by pastehttpserver or by apache mod_wsgi (or any WSGI-compatible server)

bull fills request with info

bull the environment variables replacing lsquorsquo with lsquo_rsquo

bull adds web2py path and version info

bull compensates for fcgi missing path_info and query_string

bull validates the path in url

The url path must be either

1 for static pages

bull ltapplicationgtstaticltfilegt

2 for dynamic pages

bull ltapplicationgt[ltcontrollergt[ltfunctiongt[ltsubgt]]][ltextensiongt]

The naming conventions are

bull application controller function and extension may only contain [a-zA-Z0-9_]

57

web2py Documentation Release 2146-stable

bull file and sub may also contain lsquo-lsquo lsquo=rsquo lsquorsquo and lsquorsquo

gluonmainsave_password(password port)Used by main() to save the password in the parameters_portpy file

gluonmainappfactory(wsgiapp=ltfunction wsgibasegt logfilename=rsquohttpserverlogrsquo pro-filer_dir=None profilerfilename=None)

generates a wsgi application that does logging and profiling and calls wsgibase

Parameters

bull wsgiapp ndash the base application

bull logfilename ndash where to store apache-compatible requests log

bull profiler_dir ndash where to store profile files

class gluonmainHttpServer(ip=rsquo127001rsquo port=8000 password=rdquopid_filename=rsquohttpserverpidrsquo log_filename=rsquohttpserverlogrsquoprofiler_dir=None ssl_certificate=None ssl_private_key=Nonessl_ca_certificate=None min_threads=None max_threads=Noneserver_name=None request_queue_size=5 timeout=10socket_timeout=1 shutdown_timeout=None path=None inter-faces=None)

Bases object

the web2py web server (Rocket)

start()start the web server

stop(stoplogging=False)stop cron and the web server

58 Chapter 16 main Module

CHAPTER 17

messageboxhandler Module

class gluonmessageboxhandlerMessageBoxHandlerBases loggingHandler

emit(record)Do whatever it takes to actually log the specified logging record

This version is intended to be implemented by subclasses and so raises a NotImplementedError

class gluonmessageboxhandlerNotifySendHandlerBases loggingHandler

emit(record)Do whatever it takes to actually log the specified logging record

This version is intended to be implemented by subclasses and so raises a NotImplementedError

59

web2py Documentation Release 2146-stable

60 Chapter 17 messageboxhandler Module

CHAPTER 18

myregex Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

181 Useful regexes

61

web2py Documentation Release 2146-stable

62 Chapter 18 myregex Module

CHAPTER 19

newcron Module

This file is part of the web2py Web FrameworkCreated by Attila Csipa ltweb2pycsipainrsgtModified by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

Cron-style interface

class gluonnewcronToken(path)Bases object

acquire(startup=False)Returns the time when the lock is acquired or None if cron already running

lock is implemented by writing a pickle (start stop) in cronmaster start is time when cron job starts andstop is time when cron completed stop == 0 if job started but did not yet complete if a cron job startedwithin less than 60 seconds acquire returns None if a cron job started before 60 seconds and did not stopa warning is issue ldquoStale cronmaster detectedrdquo

release()Writes into cronmaster the time when cron job was completed

gluonnewcronabsolute_path_link(path)Returns an absolute path for the destination of a symlink

gluonnewcroncrondance(applications_parent ctype=rsquosoftrsquo startup=False apps=None)

class gluonnewcroncronlauncher(cmd shell=True)Bases threadingThread

run()Method representing the threadrsquos activity

You may override this method in a subclass The standard run() method invokes the callable object passedto the objectrsquos constructor as the target argument if any with sequential and keyword arguments takenfrom the args and kwargs arguments respectively

63

web2py Documentation Release 2146-stable

class gluonnewcronextcron(applications_parent apps=None)Bases threadingThread

run()Method representing the threadrsquos activity

You may override this method in a subclass The standard run() method invokes the callable object passedto the objectrsquos constructor as the target argument if any with sequential and keyword arguments takenfrom the args and kwargs arguments respectively

class gluonnewcronhardcron(applications_parent)Bases threadingThread

launch()

run()Method representing the threadrsquos activity

You may override this method in a subclass The standard run() method invokes the callable object passedto the objectrsquos constructor as the target argument if any with sequential and keyword arguments takenfrom the args and kwargs arguments respectively

gluonnewcronparsecronline(line)

gluonnewcronrangetolist(s period=rsquominrsquo)

class gluonnewcronsoftcron(applications_parent)Bases threadingThread

run()Method representing the threadrsquos activity

You may override this method in a subclass The standard run() method invokes the callable object passedto the objectrsquos constructor as the target argument if any with sequential and keyword arguments takenfrom the args and kwargs arguments respectively

gluonnewcronstopcron()Graceful shutdown of cron

64 Chapter 19 newcron Module

CHAPTER 20

portalocker Module

Cross-platform (posixnt) API for flock-style file locking

Synopsis

import portalockerfile = open(somefile r+)portalockerlock(file portalockerLOCK_EX)fileseek(12)filewrite(foo)fileclose()

If you know what yoursquore doing you may choose to

portalockerunlock(file)

before closing the file but why

Methods

lock( file flags )unlock( file )

Constants

LOCK_EXLOCK_SHLOCK_NB

I learned the win32 technique for locking files from sample code provided by John Nielsen ltnielsenjfmy-dejacomgtin the documentation that accompanies the win32 modules

Author Jonathan Feinberg ltjdfpoboxcomgt Version $Id portalockerpyv 13 20010529 184755 AdministratorExp $

class gluonportalockerLockedFile(filename mode=rsquorbrsquo)Bases object

65

web2py Documentation Release 2146-stable

close()

read(size=None)

readline()

readlines()

write(data)

gluonportalockerlock(file flags)

gluonportalockerread_locked(filename)

gluonportalockerunlock(file)

gluonportalockerwrite_locked(filename data)

66 Chapter 20 portalocker Module

CHAPTER 21

recfile Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

211 Generates names for cache and session files

gluonrecfileexists(filename path=None)

gluonrecfilegenerate(filename depth=2 base=512)

gluonrecfileopen(filename mode=rsquorrsquo path=None)

gluonrecfileremove(filename path=None)

67

web2py Documentation Release 2146-stable

68 Chapter 21 recfile Module

CHAPTER 22

restricted Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

221 Restricted environment to execute applicationrsquos code

exception gluonrestrictedRestrictedError(layer=rdquo code=rdquo output=rdquo environ-ment=None)

Bases exceptionsException

Class used to wrap an exception that occurs in the restricted environment below The traceback is used to logthe exception and generate a ticket

load(request app ticket_id)Loads a logged exception

log(request)Logs the exception

gluonrestrictedrestricted(code environment=None layer=rsquoUnknownrsquo)Runs code in environment and returns the output If an exception occurs in code it raises a RestrictedErrorcontaining the traceback Layer is passed to RestrictedError to identify where the error occurred

class gluonrestrictedTicketStorage(db=None tablename=rsquoweb2py_ticketrsquo)Bases gluonstorageStorage

Defines the ticket object and the default values of its members (None)

load(request app ticket_id)

store(request ticket_id ticket_data)Stores the ticket It will figure out if this must be on disk or in db

gluonrestrictedcompile2(code layer)The +n is necessary else compile fails when code ends in a comment

69

web2py Documentation Release 2146-stable

70 Chapter 22 restricted Module

CHAPTER 23

rewrite Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

gluonrewrite parses incoming URLs and formats outgoing URLs for gluonhtmlURL

In addition it rewrites both incoming and outgoing URLs based on the (optional) user-supplied routespy which alsoallows for rewriting of certain error messages

routespy supports two styles of URL rewriting depending on whether lsquoroutersrsquo is defined Refer to routerexamplepyand routesexamplepy for additional documentation

class gluonrewriteMapUrlIn(request=None env=None)Bases object

Logic for mapping incoming URLs

arg0Returns first arg

harg0Returns first arg with optional hyphen mapping

map_app()Determines application name

map_controller()Identifies controller

map_function()Handles functionextension

map_language()Handles language (no hyphen mapping)

71

web2py Documentation Release 2146-stable

map_prefix()Strips path prefix if present in its entirety

map_root_static()Handles root-static files (no hyphen mapping)

a root-static file is one whose incoming URL expects it to be at the root typically robotstxt amp faviconico

map_static()Handles static files file_match but no hyphen mapping

pop_arg_if(dopop)Conditionally removes first arg and returns new first arg

sluggify()

update_request()Updates request from self Builds envrequest_uri Makes lower-case versions of http headers in env

validate_args()Checks args against validation pattern

class gluonrewriteMapUrlOut(request env application controller function args other schemehost port language)

Bases object

Logic for mapping outgoing URLs

acf()Converts components to applangcontrollerfunction

build_acf()Builds acf from components

omit_acf()Omits what we can of acf

omit_lang()Omits language if possible

gluonrewritecompile_regex(k v env=None)Preprocess and compile the regular expressions in routes_appinout The resulting regex will match a pattern ofthe form

[remote address][protocol][host][method] [path]

We allow abbreviated regexes on input here we try to complete them

gluonrewritefilter_err(status application=rsquoapprsquo ticket=rsquotktrsquo)doctestunittest interface to routes_onerror

gluonrewritefilter_url(url method=rsquogetrsquo remote=rsquo0000rsquo out=False app=False lang=Nonedomain=(None None) env=False scheme=None host=Noneport=None language=None)

doctestunittest interface to regex_filter_in() and regex_filter_out()

gluonrewritefixup_missing_path_info(environ)

gluonrewriteget_effective_router(appname)Returns a private copy of the effective router for the specified application

gluonrewriteinvalid_url(routes)

72 Chapter 23 rewrite Module

web2py Documentation Release 2146-stable

gluonrewriteload(routes=rsquoroutespyrsquo app=None data=None rdict=None)load read (if file) and parse routes store results in params (called from mainpy at web2py initialization time)If data is present itrsquos used instead of the routespy contents If rdict is present it must be a dict to be used forrouters (unit test)

gluonrewriteload_routers(all_apps)Load-time post-processing of routers

gluonrewritelog_rewrite(string)Log rewrite activity under control of routespy

gluonrewritemap_url_in(request env app=False)Routes incoming URL

gluonrewritemap_url_out(request env application controller function args other scheme hostport language=None)

Supply acf (or alangcf) portion of outgoing url

The basic rule is that we can only make transformations that map_url_in can reverse

Suppose that the incoming arguments are acfargslang and that the router defaults are da dc df dl

We can perform these transformations trivially if args=[] and lang=None or dl

dadcdf =gt adcdf =gt aacdf =gt ac

We would also like to be able to strip the default application or applicationcontroller from URLs with func-tionargs present thus

dacfargs =gt cfargsdadcfargs =gt fargs

We use [applications] and [controllers] and functions to suppress ambiguous omissions

We assume that language names do not collide with acf names

gluonrewriteregex_filter_in(e)Regex rewrite incoming URL

gluonrewriteregex_filter_out(url e=None)Regex rewrite outgoing URL

gluonrewriteregex_select(env=None app=None request=None)Selects a set of regex rewrite params for the current request

gluonrewriteregex_uri(e regexes tag default=None)Filters incoming URI against a list of regexes

gluonrewriteregex_url_in(request environ)Rewrites and parses incoming URL

gluonrewritesluggify(key)

gluonrewritetry_redirect_on_error(http_object request ticket=None)Called from mainwsgibase to rewrite the http response

gluonrewritetry_rewrite_on_error(http_response request environ ticket=None)Called from mainwsgibase to rewrite the http response

gluonrewriteurl_in(request environ)Parses and rewrites incoming URL

73

web2py Documentation Release 2146-stable

gluonrewriteurl_out(request environ application controller function args other scheme hostport language=None)

Assembles and rewrites outgoing URL

74 Chapter 23 rewrite Module

CHAPTER 24

sanitizer Module

From httpaspnactivestatecomASPNCookbookPythonRecipe496942Submitter Josh Goldfoot (other recipes)Last Updated 20060805Version 10

241 Cross-site scripting (XSS) defense

gluonsanitizersanitize(text permitted_tags=[rsquoarsquo rsquobrsquo rsquoblockquotersquo rsquobrrsquo rsquoirsquo rsquolirsquo rsquoolrsquo rsquoulrsquorsquoprsquo rsquocitersquo rsquocodersquo rsquoprersquo rsquoimgrsquo rsquoh1rsquo rsquoh2rsquo rsquoh3rsquo rsquoh4rsquo rsquoh5rsquo rsquoh6rsquo rsquota-blersquo rsquotbodyrsquo rsquotheadrsquo rsquotfootrsquo rsquotrrsquo rsquotdrsquo rsquodivrsquo rsquostrongrsquo rsquospanrsquo] al-lowed_attributes=rsquoarsquo [rsquohrefrsquo rsquotitlersquo] rsquoblockquotersquo [rsquotypersquo] rsquoimgrsquo[rsquosrcrsquo rsquoaltrsquo] rsquotdrsquo [rsquocolspanrsquo] escape=True)

75

web2py Documentation Release 2146-stable

76 Chapter 24 sanitizer Module

CHAPTER 25

scheduler Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

251 Background processes made simple

class gluonschedulerJobGraph(db job_name)Bases object

Experimental dependencies amongs tasks

add_deps(task_parent task_child)Create a dependency between task_parent and task_child

validate(job_name=None)Validate if all tasks job_name can be completed

Checks if there are no mutual dependencies among tasks Commits at the end if successfull or it rollbacksthe entire transaction Handle with care

class gluonschedulerMetaSchedulerBases threadingThread

Base class documenting schedulerrsquos base methods

async(task)Start the background process

Parameters task ndash a Task object

Returns

containing

77

web2py Documentation Release 2146-stable

(okresultoutput)(errorexceptionNone)(timeoutNoneNone)(terminatedNoneNone)

Return type tuple

die()Forces termination of the worker process along with any running task

give_up()Waits for any running task to be executed then exits the worker process

loop()Main loop fetching tasks and starting executorrsquos background processes

pop_task()Fetches a task ready to be executed

report_task(task task_report)Creates a task report

run()This is executed by the main thread to send heartbeats

send_heartbeat(counter)

sleep()

start_heartbeats()

terminate_process()Terminates any running tasks (internal use only)

class gluonschedulerScheduler(db tasks=None migrate=True worker_name=Nonegroup_names=None heartbeat=3 max_empty_runs=0discard_results=False utc_time=False)

Bases gluonschedulerMetaScheduler

Scheduler object

Parameters

bull db ndash DAL connection where Scheduler will create its tables

bull tasks (dict) ndash either a dict containing namendashgtfunc or None If None functions will besearched in the environment

bull migrate (bool) ndash turn migration onoff for the Schedulerrsquos tables

bull worker_name (str) ndash force worker_name to identify each process Leave it to None toautoassign a name (hostnamepid)

bull group_names (list) ndash process tasks belonging to this group defaults to [lsquomainrsquo] if noth-ing gets passed

bull heartbeat (int) ndash how many seconds the worker sleeps between one execution and thefollowing one Indirectly sets how many seconds will pass between checks for new tasks

bull max_empty_runs (int) ndash how many loops are allowed to pass without processing anytasks before exiting the process 0 to keep always the process alive

78 Chapter 25 scheduler Module

web2py Documentation Release 2146-stable

bull discard_results (bool) ndash Scheduler stores executionsrsquos details into the sched-uler_run table By default only if there is a result the details are kept Turning this toTrue means discarding results even for tasks that return something

bull utc_time (bool) ndash do all datetime calculations assuming UTC as the timezone Remem-ber to pass start_time and stop_time to tasks accordingly

adj_hibernation()Used to increase the ldquosleeprdquo interval for DISABLED workers

assign_tasks(db)Assign task to workers that can then pop them from the queue

Deals with group_name(s) logic in order to assign linearly tasks to available workers for those groups

being_a_ticker()Elect a TICKER process that assigns tasks to available workers

Does its best to elect a worker that is not busy processing other tasks to allow a proper distribution of tasksamong all active workers ASAP

define_tables(db migrate)Define Scheduler tables structure

disable(group_names=None limit=None worker_name=None)Set DISABLED on the workers processing group_names tasks

A DISABLED worker will be kept alive but it wonrsquot be able to process any waiting tasks essentiallyputting it to sleep By default all group_names of Schedulerrsquos instantation are selected

get_workers(only_ticker=False)Returns a dict holding worker_name columns representing all ldquoregisteredrdquo workers only_ticker re-turns only the workers running as a TICKER if there are any

kill(group_names=None limit=None worker_name=None)Sets KILL as worker status The worker will be killed even if itrsquos processing a task

loop(worker_name=None)Main loop

This works basically as a neverending loop that

bull checks if the worker is ready to process tasks (is not DISABLED)

bull pops a task from the queue

bull if there is a task

ndash spawns the executor background process

ndash waits for the process to be finished

ndash sleeps heartbeat seconds

bull if there is not a task

ndash checks for max_empty_runs

ndash sleeps heartbeat seconds

now()Shortcut that fetches current time based on UTC preferences

pop_task(db)Grab a task ready to be executed from the queue

251 Background processes made simple 79

web2py Documentation Release 2146-stable

queue_task(function pargs=[] pvars= kwargs)Queue tasks This takes care of handling the validation of all parameters

Parameters

bull function ndash the function (anything callable with a __name__)

bull pargs ndash ldquorawrdquo args to be passed to the function Automatically jsonified

bull pvars ndash ldquorawrdquo kwargs to be passed to the function Automatically jsonified

bull kwargs ndash all the parameters available (basically every scheduler_task column) If argsand vars are here they should be jsonified already and they will override pargs and pvars

Returns a dict just as a normal validate_and_insert() plus a uuid key holding the uuid of thequeued task If validation is not passed ( ie some parameters are invalid) both id and uuidwill be None and yoursquoll get an ldquoerrorrdquo dict holding the errors found

report_task(task task_report)Take care of storing the result according to preferences

Deals with logic for repeating tasks

resume(group_names=None limit=None worker_name=None)Wakes a worker up (it will be able to process queued tasks)

send_heartbeat(counter)Coordination among available workers

It - sends the heartbeat - elects a ticker among available workers (the only process that

effectively dispatch tasks to workers)

bull deals with workerrsquos statuses

bull does ldquohousecleaningrdquo for dead workers

bull triggers tasks assignment to workers

set_requirements(scheduler_task)Called to set defaults for lazy_tables connections

set_worker_status(group_names=None action=rsquoACTIVErsquo exclude=None limit=Noneworker_name=None)

Internal function to set workerrsquos status

sleep()Calculate the number of seconds to sleep

stop_task(ref)Shortcut for task termination

If the task is RUNNING it will terminate it meaning that status will be set as FAILED

If the task is QUEUED its stop_time will be set as to ldquonowrdquo the enabled flag will be set to False andthe status to STOPPED

Parameters ref ndash can be

bull an integer lookup will be done by scheduler_taskid

bull a string lookup will be done by scheduler_taskuuid

Returns

bull 1 if task was stopped (meaning an update has been done)

80 Chapter 25 scheduler Module

web2py Documentation Release 2146-stable

bull None if task was not found or if task was not RUNNING or QUEUED

Note Experimental

task_status(ref output=False)Retrieves task status and optionally the result of the task

Parameters

bull ref ndash can be

ndash an integer lookup will be done by scheduler_taskid

ndash a string lookup will be done by scheduler_taskuuid

ndash a Query lookup as you wish eg

dbscheduler_tasktask_name == test1

bull output (bool) ndash if True fetch also the scheduler_run record

Returns a single Row object for the last queued task If output == True returns also the lastscheduler_run record The scheduler_run record is fetched by a left join so it can have allfields == None

terminate(group_names=None limit=None worker_name=None)Sets TERMINATE as worker status The worker will wait for any currently running tasks to be executedand then it will exit gracefully

static total_seconds(td)Backport for py26

update_dependencies(db task_id)Unblock execution paths for Jobs

wrapped_assign_tasks(db)Commodity function to call assign_tasks and trap exceptions

If an exception is raised assume it happened because of database contention and retries assign_task after05 seconds

wrapped_pop_task()Commodity function to call pop_task and trap exceptions

If an exception is raised assume it happened because of database contention and retries pop_task after 05seconds

wrapped_report_task(task task_report)Commodity function to call report_task and trap exceptions

If an exception is raised assume it happened because of database contention and retries pop_task after 05seconds

class gluonschedulerTYPE(myclass=lttype rsquolistrsquogt parse=False)Bases object

Validator that checks whether field is valid json and validates its type Used for args and vars of the sched-uler_task table

class gluonschedulerTask(app function timeout args=rsquo[]rsquo vars=rsquorsquo kwargs)Bases object

251 Background processes made simple 81

web2py Documentation Release 2146-stable

Defines a ldquotaskrdquo object that gets passed from the main thread to the executorrsquos one

class gluonschedulerTaskReport(status result=None output=None tb=None)Bases object

Defines a ldquotask reportrdquo object that gets passed from the executorrsquos thread to the main one

gluonschedulerexecutor(queue task out)The function used to execute tasks in the background process

gluonschedulermain()allows to run worker without python web2pypy by simply

python gluonschedulerpy

82 Chapter 25 scheduler Module

CHAPTER 26

serializers Module

This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

gluonserializerscast_keys(o cast=lttype rsquostrrsquogt encoding=rsquoutf-8rsquo)Builds a new object with ltcastgt type keys Use this function if you are in Python lt 265 This avoids syntaxerrors when unpacking dictionary arguments

Parameters

bull o ndash is the object input

bull cast ndash (defaults to str) is an object type or function which supports conversion such as

converted = cast(o)

bull encoding ndash (defaults to utf-8) is the encoding for unicode keys This is not used forcustom cast functions

gluonserializerscsv(value)

gluonserializerscustom_json(o)

gluonserializersics(events title=None link=None timeshift=0 calname=True ignored)

gluonserializersjson(value default=ltfunction custom_jsongt)

gluonserializersloads_json(o unicode_keys=True kwargs)

gluonserializersloads_yaml(data)

gluonserializersrss(feed)

gluonserializerssafe_encode(text)

gluonserializersxml(value encoding=rsquoUTF-8rsquo key=rsquodocumentrsquo quote=True)

gluonserializersxml_rec(value key quote=True)

gluonserializersyaml(data)

83

web2py Documentation Release 2146-stable

84 Chapter 26 serializers Module

CHAPTER 27

settings Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

85

web2py Documentation Release 2146-stable

86 Chapter 27 settings Module

CHAPTER 28

shell Module

This file is part of the web2py Web FrameworkDeveloped by Massimo Di Pierro ltmdipierrocsdepauledugtlimodou ltlimodougmailcomgt and srackham ltsrackhamgmailcomgtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

281 Web2py environment in the shell

gluonshelldie(msg)

gluonshellenable_autocomplete_and_history(adir env)

gluonshellenv(a import_models=False c=None f=None dir=rdquo extra_request=)Returns web2py execution environment for application (a) controller (c) function (f) If import_models is Truethe exec all application models into the environment

extra_request allows you to pass along any extra variables to the request object before your models get executedThis was mainly done to support web2py_utilstest_runner however you can use it with any wrapper scripts thatneed access to the web2py environment

gluonshellexec_environment(pyfile=rdquo request=None response=None session=None)Environment builder and module loader

Builds a web2py environment and optionally executes a Python file into the environment

A Storage dictionary containing the resulting environment is returned The working directory must be web2pyroot ndash this is the web2py default

gluonshellexec_pythonrc()

gluonshellexecute_from_command_line(argv=None)

gluonshellget_usage()

87

web2py Documentation Release 2146-stable

gluonshellparse_path_info(path_info av=False)Parses path info formatted like acf where c and f are optional and a leading is accepted Return tuple (a c f)If invalid path_info a is set to None If c or f are omitted they are set to None If av=True parse args and vars

gluonshellrun(appname plain=False import_models=False startfile=None bpython=Falsepython_code=False cronjob=False)

Start interactive shell or run Python script (startfile) in web2py controller environment appname is formattedlike

bull a web2py application name

bull ac exec the controller c into the application environment

gluonshelltest(testpath import_models=True verbose=False)Run doctests in web2py environment testpath is formatted like

bull a tests all controllers in application a

bull ac tests controller c in application a

bull acf test function f in controller c application a

Where a c and f are application controller and function names respectively If the testpath is a file name the fileis tested If a controller is specified models are executed by default

88 Chapter 28 shell Module

CHAPTER 29

sql Module

This file is part of the web2py Web FrameworkDeveloped by Massimo Di Pierro ltmdipierrocsdepauledugtlimodou ltlimodougmailcomgt and srackham ltsrackhamgmailcomgtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

291 Just for backward compatibility

class gluonsqlDAL(uri=rsquosqlitedummydbrsquo pool_size=0 folder=None db_codec=rsquoUTF-8rsquo check_reserved=None migrate=True fake_migrate=False mi-grate_enabled=True fake_migrate_all=False decode_credentials=Falsedriver_args=None adapter_args=None attempts=5 auto_import=False big-int_id=False debug=False lazy_tables=False db_uid=None do_connect=Trueafter_connection=None tables=None ignore_field_case=True en-tity_quoting=False table_hash=None)

Bases pydalhelpersclassesSerializable pydalhelpersclassesBasicStorage

An instance of this class represents a database connection

Parameters

bull uri (str) ndash contains information for connecting to a database Defaults tolsquosqlitedummydbrsquo

Note experimental you can specify a dictionary as uri parameter ie with

db = DAL(uri sqlitestoragesqlitetables )

for an example of dict input you can check the output of the scaffolding db model with

dbas_dict()

89

web2py Documentation Release 2146-stable

Note that for compatibility with Python older than version 265 you should cast your dictinput keys to str due to a syntax limitation on kwarg names for proper DAL dictionary inputyou can use one of

obj = serializerscast_keys(dict [encoding=utf-8])or else (for parsing json input)obj = serializersloads_json(data unicode_keys=False)

bull pool_size ndash How many open connections to make to the database object

bull folder ndash where table files will be created Automatically set within web2py Use anexplicit path when using DAL outside web2py

bull db_codec ndash string encoding of the database (default lsquoUTF-8rsquo)

bull table_hash ndash database identifier with tables If your connection hash change you canstill using old tables if they have db_hash as prefix

bull check_reserved ndash list of adapters to check tablenames and column names againstsqlnosql reserved keywords Defaults to None

ndash rsquocommonrsquo List of sql keywords that are common to all database types such as ldquoSELECTINSERTrdquo (recommended)

ndash rsquoallrsquo Checks against all known SQL keywords

ndash rsquoltadapternamegtrdquo Checks against the specific adapters list of keywords

ndash rsquoltadapternamegt_nonreservedrsquo Checks against the specific adapters list of nonreservedkeywords (if available)

bull migrate ndash sets default migrate behavior for all tables

bull fake_migrate ndash sets default fake_migrate behavior for all tables

bull migrate_enabled ndash If set to False disables ALL migrations

bull fake_migrate_all ndash If set to True fake migrates ALL tables

bull attempts ndash Number of times to attempt connecting

bull auto_import ndash If set to True tries import automatically table definitions from thedatabases folder (works only for simple models)

bull bigint_id ndash If set turn on bigint instead of int for id and reference fields

bull lazy_tables ndash delays table definition until table access

bull after_connection ndash can a callable that will be executed after the connection

Example

Use as

db = DAL(sqlitetestdb)

or

90 Chapter 29 sql Module

web2py Documentation Release 2146-stable

db = DAL(uri tables []) experimental

dbdefine_table(tablename Field(fieldname1)Field(fieldname2))

class Field(fieldname type=rsquostringrsquo length=None default=ltfunction ltlambdagtgt re-quired=False requires=ltfunction ltlambdagtgt ondelete=rsquoCASCADErsquo not-null=False unique=False uploadfield=True widget=None label=None com-ment=None writable=True readable=True update=None authorize=Noneautodelete=False represent=None uploadfolder=None uploadseparate=Falseuploadfs=None compute=None custom_store=None custom_retrieve=Nonecustom_retrieve_file_properties=None custom_delete=None filter_in=None fil-ter_out=None custom_qualifier=None map_none=None rname=None)

Bases pydalobjectsExpression pydalhelpersclassesSerializable

Lazyalias of FieldMethod

Methodalias of FieldMethod

Virtualalias of FieldVirtual

as_dict(flat=False sanitize=True)

clone(point_self_references_to=False args)

count(distinct=None)

formatter(value)

retrieve(name path=None nameonly=False)If nameonly==True return (filename fullfilename) instead of (filename stream)

retrieve_file_properties(name path=None)

set_attributes(args attributes)

sqlsafe

sqlsafe_name

store(file filename=None path=None)

validate(value)

class Row(args kwargs)Bases pydalhelpersclassesBasicStorage

A dictionary that lets you do d[lsquoarsquo] as well as da this is only used to store a Row

as_dict(datetime_to_str=False custom_types=None)

as_json(mode=rsquoobjectrsquo default=None colnames=None serialize=True kwargs)serializes the row to a JSON object kwargs are passed to as_dict method only ldquoobjectrdquo mode sup-ported

serialize = False used by Rowsas_json

TODO return array mode with query column order

mode and colnames are not implemented

as_xml(row_name=rsquorowrsquo colnames=None indent=rsquo rsquo)

291 Just for backward compatibility 91

web2py Documentation Release 2146-stable

get(key default=None)

class Table(db tablename fields args)Bases pydalhelpersclassesSerializable pydalhelpersclassesBasicStorage

Represents a database table

Example

You can create a table as db = DAL( ) dbdefine_table(lsquousersrsquo Field(lsquonamersquo))

And then

dbusersinsert(name=me) print dbusers_insert() to see SQLdbusersdrop()

as_dict(flat=False sanitize=True)

bulk_insert(items)here items is a list of dictionaries

drop(mode=rdquo)

fields

import_from_csv_file(csvfile id_map=None null=rsquoltNULLgtrsquo unique=rsquouuidrsquoid_offset=None args kwargs)

Import records from csv file Column headers must have same names as table fields Field lsquoidrsquo isignored If column names read lsquotablefilersquo the lsquotablersquo prefix is ignored

bull lsquouniquersquo argument is a field which must be unique (typically a uuid field)bull lsquorestorersquo argument is default False if set True will remove old values in table firstbull lsquoid_maprsquo if set to None will not map ids

The import will keep the id numbers in the restored table This assumes that there is an field of typeid that is integer and in incrementing order Will keep the id numbers in restored table

insert(fields)

on(query)

sqlsafe

sqlsafe_alias

truncate(mode=None)

update(args kwargs)

update_or_insert(_key=ltfunction ltlambdagtgt values)

validate_and_insert(fields)

validate_and_update(_key=ltfunction ltlambdagtgt fields)

validate_and_update_or_insert(_key=ltfunction ltlambdagtgt fields)

with_alias(alias)

as_dict(flat=False sanitize=True)

can_join()

check_reserved_keyword(name)Validates name against SQL keywords Uses selfcheck_reserve which is a list of operators to use

close()

92 Chapter 29 sql Module

web2py Documentation Release 2146-stable

commit()

define_table(tablename fields args)

static distributed_transaction_begin(instances)

static distributed_transaction_commit(instances)

executesql(query placeholders=None as_dict=False fields=None colnames=Noneas_ordered_dict=False)

Executes an arbitrary query

Parameters

bull query (str) ndash the query to submit to the backend

bull placeholders ndash is optional and will always be None If using raw SQL with place-holders placeholders may be a sequence of values to be substituted in or (if supported bythe DB driver) a dictionary with keys matching named placeholders in your SQL

bull as_dict ndash will always be None when using DAL If using raw SQL can be set to Trueand the results cursor returned by the DB driver will be converted to a sequence of dic-tionaries keyed with the db field names Results returned with as_dict=True are the sameas those returned when applying to_list() to a DAL query If ldquoas_ordered_dictrdquo=True thebehaviour is the same as when ldquoas_dictrdquo=True with the keys (field names) guaranteed tobe in the same order as returned by the select name executed on the database

bull fields ndash list of DAL Fields that match the fields returned from the DB The Field objectsshould be part of one or more Table objects defined on the DAL object The ldquofieldsrdquo listcan include one or more DAL Table objects in addition to or instead of including Fieldobjects or it can be just a single table (not in a list) In that case the Field objects will beextracted from the table(s)

Note if either fields or colnames is provided the results will be converted to a DAL Rowsobject using the db_adapterparse() method

bull colnames ndash list of field names in tablenamefieldname format

Note It is also possible to specify both ldquofieldsrdquo and the associated ldquocolnamesrdquo In that case ldquofieldsrdquocan also include DAL Expression objects in addition to Field objects For Field objects in ldquofieldsrdquo theassociated ldquocolnamesrdquo must still be in tablenamefieldname format For Expression objects in ldquofieldsrdquo theassociated ldquocolnamesrdquo can be any arbitrary labels

DAL Table objects referred to by ldquofieldsrdquo or ldquocolnamesrdquo can be dummy tables and do not have to representany real tables in the database Also note that the ldquofieldsrdquo and ldquocolnamesrdquo must be in the same order asthe fields in the results cursor returned from the DB

export_to_csv_file(ofile args kwargs)

static get_instances()Returns a dictionary with uri as key with timings and defined tables

sqlitestoragesqlite dbstats [(select auth_useremail from auth_user 002009)]dbtables

defined [auth_cas auth_event auth_groupauth_membership auth_permission auth_user]

(continues on next page)

291 Just for backward compatibility 93

web2py Documentation Release 2146-stable

(continued from previous page)

lazy []

has_representer(name)

import_from_csv_file(ifile id_map=None null=rsquoltNULLgtrsquo unique=rsquouuidrsquomap_tablenames=None ignore_missing_tables=False args kwargs)

import_table_definitions(path migrate=False fake_migrate=False tables=None)

lazy_define_table(tablename fields args)

logger = ltloggingLogger objectgt

parse_as_rest(patterns args vars queries=None nested_select=True)

Example

Use as

dbdefine_table(personField(name)Field(info))dbdefine_table(pet

Field(ownedbydbperson)Field(name)Field(info)

)

requestrestful()def index()

def GET(argsvars)patterns = [

friends[person]personnamefieldpersonnamepets[petownedby]personnamepets[petownedby]petnamepersonnamepets[petownedby]petnamefield(dogs[pet] dbpetinfo==dog)(dogs[pet]petnamestartswith dbpetinfo==dog)]

parser = dbparse_as_rest(patternsargsvars)if parserstatus == 200

return dict(content=parserresponse)else

raise HTTP(parserstatusparsererror)

def POST(table_namevars)if table_name == person

return dbpersonvalidate_and_insert(vars)elif table_name == pet

return dbpetvalidate_and_insert(vars)else

raise HTTP(400)return locals()

represent(name args kwargs)

representers = rows_render ltfunction represent at 0x7fcf10dcdb18gt rows_xml ltclass gluonsqlhtmlSQLTABLEgt

94 Chapter 29 sql Module

web2py Documentation Release 2146-stable

rollback()

serializers = json ltfunction custom_json at 0x7fcf11069488gt xml ltfunction xml at 0x7fcf11069578gt

static set_folder(folder)

smart_query(fields text)

tables

uuid()

validators = None

validators_method(field)Field type validation using web2pyrsquos validators mechanism

makes sure the content of a field is in line with the declared fieldtype

where(query=None ignore_common_filters=None)

class gluonsqlField(fieldname type=rsquostringrsquo length=None default=ltfunction ltlambdagtgtrequired=False requires=ltfunction ltlambdagtgt ondelete=rsquoCASCADErsquonotnull=False unique=False uploadfield=True widget=None label=Nonecomment=None writable=True readable=True update=None autho-rize=None autodelete=False represent=None uploadfolder=None upload-separate=False uploadfs=None compute=None custom_store=Nonecustom_retrieve=None custom_retrieve_file_properties=None cus-tom_delete=None filter_in=None filter_out=None custom_qualifier=Nonemap_none=None rname=None)

Bases pydalobjectsExpression pydalhelpersclassesSerializable

LazyRepresents a database field

Example

Usage

a = Field(name string length=32 default=None required=Falserequires=IS_NOT_EMPTY() ondelete=CASCADEnotnull=False unique=Falseuploadfield=True widget=None label=None comment=Noneuploadfield=True True means store on disk

a_field_name means store in this field in db False means file content will be discarded

writable=True readable=True update=None authorize=Noneautodelete=False represent=None uploadfolder=Noneuploadseparate=False upload to separate directories by uuid_keys

first 2 character and tablenamefieldname False - old behavior True - put uploaded file in ltuploaddirgtlttablenamegtltfieldnamegtuuid_key[2] directory)

uploadfs=None a pyfilesystem where to store upload)

to be used as argument of DALdefine_table

alias of FieldMethod

291 Just for backward compatibility 95

web2py Documentation Release 2146-stable

Methodalias of FieldMethod

Virtualalias of FieldVirtual

as_dict(flat=False sanitize=True)

clone(point_self_references_to=False args)

count(distinct=None)

formatter(value)

retrieve(name path=None nameonly=False)If nameonly==True return (filename fullfilename) instead of (filename stream)

retrieve_file_properties(name path=None)

set_attributes(args attributes)

sqlsafe

sqlsafe_name

store(file filename=None path=None)

validate(value)

96 Chapter 29 sql Module

CHAPTER 30

sqlhtml Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

Holds

bull SQLFORM provide a form for a table (withwithout record)

bull SQLTABLE provides a table for a set of records

bull form_factory provides a SQLFORM for an non-db backed table

class gluonsqlhtmlAutocompleteWidget(request field id_field=None db=None or-derby=None limitby=(0 10) distinct=False key-word=rsquo_autocomplete_(tablename)s_(fieldname)srsquomin_length=2 help_fields=Nonehelp_string=None at_beginning=True)

Bases object

callback()

class gluonsqlhtmlBooleanWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates an INPUT checkbox tag

see also FormWidgetwidget

class gluonsqlhtmlCacheRepresenterBases object

class gluonsqlhtmlCheckboxesWidgetBases gluonsqlhtmlOptionsWidget

classmethod widget(field value attributes)Generates a TABLE tag including INPUT checkboxes (multiple allowed)

97

web2py Documentation Release 2146-stable

see also FormWidgetwidget

class gluonsqlhtmlDateWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlDatetimeWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlDecimalWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlDoubleWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlExportClass(rows)Bases object

content_type = None

export()

file_ext = None

label = None

represented()

class gluonsqlhtmlExporterCSV(rows)Bases gluonsqlhtmlExportClass

content_type = textcsv

export()

file_ext = csv

label = CSV

class gluonsqlhtmlExporterCSV_hidden(rows)Bases gluonsqlhtmlExportClass

content_type = textcsv

export()

file_ext = csv

label = CSV

class gluonsqlhtmlExporterHTML(rows)Bases gluonsqlhtmlExportClass

content_type = texthtml

export()

file_ext = html

label = HTML

class gluonsqlhtmlExporterJSON(rows)Bases gluonsqlhtmlExportClass

content_type = applicationjson

export()

file_ext = json

98 Chapter 30 sqlhtml Module

web2py Documentation Release 2146-stable

label = JSON

class gluonsqlhtmlExporterTSV(rows)Bases gluonsqlhtmlExportClass

content_type = texttab-separated-values

export()

file_ext = csv

label = TSV

class gluonsqlhtmlExporterXML(rows)Bases gluonsqlhtmlExportClass

content_type = textxml

export()

file_ext = xml

label = XML

class gluonsqlhtmlFormWidgetBases object

Helper for SQLFORM to generate form input fields (widget) related to the fieldtype

classmethod widget(field value attributes)Generates the widget for the field

When serialized will provide an INPUT tag

bull id = tablename_fieldname

bull class = fieldtype

bull name = fieldname

Parameters

bull field ndash the field needing the widget

bull value ndash value

bull attributes ndash any other attributes to be applied

class gluonsqlhtmlIntegerWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlJSONWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates a TEXTAREA for JSON notation

see also FormWidgetwidget

class gluonsqlhtmlListWidgetBases gluonsqlhtmlStringWidget

classmethod widget(field value attributes)Generates an INPUT text tag

see also FormWidgetwidget

99

web2py Documentation Release 2146-stable

class gluonsqlhtmlMultipleOptionsWidgetBases gluonsqlhtmlOptionsWidget

classmethod widget(field value size=5 attributes)Generates a SELECT tag including OPTIONs (multiple options allowed)

see also FormWidgetwidget

Parameters size ndash optional param (default=5) to indicate how many rows must be shown

class gluonsqlhtmlOptionsWidgetBases gluonsqlhtmlFormWidget

static has_options(field)Checks if the field has selectable options

Parameters field ndash the field needing checking

Returns True if the field has options

classmethod widget(field value attributes)Generates a SELECT tag including OPTIONs (only 1 option allowed)

see also FormWidgetwidget

class gluonsqlhtmlPasswordWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates a INPUT password tag If a value is present it will be shown as a number of lsquorsquo not related tothe length of the actual value

see also FormWidgetwidget

class gluonsqlhtmlRadioWidgetBases gluonsqlhtmlOptionsWidget

classmethod widget(field value attributes)Generates a TABLE tag including INPUT radios (only 1 option allowed)

see also FormWidgetwidget

class gluonsqlhtmlSQLFORM(table record=None deletable=False linkto=None upload=Nonefields=None labels=None col3= submit_button=rsquoSubmitrsquodelete_label=rsquoCheck to deletersquo showid=True readonly=False com-ments=True keepopts=[] ignore_rw=False record_id=Noneformstyle=None buttons=[rsquosubmitrsquo] separator=None ex-tra_fields=None attributes)

Bases gluonhtmlFORM

SQLFORM is used to map a table (and a current record) into an HTML form

Given a Table like dbtable

Generates an insert form

SQLFORM(dbtable)

Generates an update form

record=dbtable[some_id]SQLFORM(dbtable record)

Generates an update with a delete button

100 Chapter 30 sqlhtml Module

web2py Documentation Release 2146-stable

SQLFORM(dbtable record deletable=True)

Parameters

bull table ndash Table object

bull record ndash either an int if the id is an int or the record fetched from the table

bull deletable ndash adds the delete checkbox

bull linkto ndash the URL of a controllerfunction to access referencedby records

bull upload ndash the URL of a controllerfunction to download an uploaded file

bull fields ndash a list of fields that should be placed in the form default is all

bull labels ndash a dictionary with labels for each field keys are the field names

bull col3 ndash a dictionary with content for an optional third column (right of each field) keys arefield names

bull submit_button ndash text to show in the submit button

bull delete_label ndash text to show next to the delete checkbox

bull showid ndash shows the id of the record

bull readonly ndash doesnrsquot allow for any modification

bull comments ndash show comments (stored in col3 or in Field definition)

bull ignore_rw ndash overrides readablewritable attributes

bull record_id ndash used to create session key against CSRF

bull formstyle ndash what to use to generate the form layout

bull buttons ndash override buttons as you please (will be also stored in formcustomsubmit)

bull separator ndash character as separator between labels and inputs

any named optional attribute is passed to the ltformgt tag for example _class _id _style _action _method etc

AUTOTYPES = lttype intgt (integer ltgluonvalidatorsIS_INT_IN_RANGE object at 0x7fcf10deb210gt) lttype floatgt (double ltgluonvalidatorsIS_FLOAT_IN_RANGE object at 0x7fcf10deb250gt) lttype unicodegt (string None) lttype boolgt (boolean None) lttype strgt (string None) lttype listgt (liststring None) lttype datetimedatetimegt (datetime ltgluonvalidatorsIS_DATETIME object at 0x7fcf10deb310gt) lttype datetimedategt (date ltgluonvalidatorsIS_DATE object at 0x7fcf10deb2d0gt)

FIELDKEY_DELETE_RECORD = delete_record

FIELDNAME_REQUEST_DELETE = delete_this_record

ID_LABEL_SUFFIX = __label

ID_ROW_SUFFIX = __row

accepts(request_vars session=None formname=rsquo(tablename)s(record_id)srsquo keepvalues=Noneonvalidation=None dbio=True hideerror=False detect_record_change=False kwargs)

Similar to FORMaccepts but also does insert update or delete in DAL If detect_record_change is Truethan

bull formrecord_changed = False (record is properly validatedsubmitted)

bull formrecord_changed = True (record cannot be submitted because changed)

If detect_record_change == False than

bull formrecord_changed = None

assert_status(status request_vars)

101

web2py Documentation Release 2146-stable

static build_query(fields keywords)

createform(xfields)

static dictform(dictionary kwargs)

static factory(fields attributes)Generates a SQLFORM for the given fields

Internally will build a non-database based data model to hold the fields

formstyles = bootstrap ltfunction formstyle_bootstrap at 0x7fcf10de99b0gt bootstrap3_inline ltfunction _inner at 0x7fcf10de9b90gt bootstrap3_stacked ltfunction formstyle_bootstrap3_stacked at 0x7fcf10de9a28gt divs ltfunction formstyle_divs at 0x7fcf10de9848gt inline ltfunction formstyle_inline at 0x7fcf10de98c0gt table2cols ltfunction formstyle_table2cols at 0x7fcf10de97d0gt table3cols ltfunction formstyle_table3cols at 0x7fcf10dcdde8gt ul ltfunction formstyle_ul at 0x7fcf10de9938gt

static grid(query fields=None field_id=None left=None headers= or-derby=None groupby=None searchable=True sortable=True pagi-nate=20 deletable=True editable=True details=True selectable=None cre-ate=True csv=True links=None links_in_grid=True upload=rsquoltdefaultgtrsquoargs=[] user_signature=True maxtextlengths= maxtextlength=20 on-validation=None onfailure=None oncreate=None onupdate=None on-delete=None sorter_icons=(ltgluonhtmlXML objectgt ltgluonhtmlXMLobjectgt) ui=rsquoweb2pyrsquo showbuttontext=True _class=rsquoweb2py_gridrsquo form-name=rsquoweb2py_gridrsquo search_widget=rsquodefaultrsquo advanced_search=True ig-nore_rw=False formstyle=None exportclasses=None formargs= cre-ateargs= editargs= viewargs= selectable_submit_button=rsquoSubmitrsquobuttons_placement=rsquorightrsquo links_placement=rsquorightrsquo noconfirm=Falsecache_count=None client_side_delete=False ignore_common_filters=Noneauto_pagination=True use_cursor=False)

static search_menu(fields search_options=None prefix=rsquow2prsquo)

static smartdictform(session name filename=None query=None kwargs)

static smartgrid(table constraints=None linked_tables=None links=None links_in_grid=Trueargs=None user_signature=True divider=rsquogtrsquo breadcrumbs_class=rdquokwargs)

Builds a system of SQLFORMgrid(s) between any referenced tables

Parameters

bull table ndash main table

bull constraints (dict) ndash lsquotablersquoquery that limits which records can be accessible

bull links (dict) ndash like lsquotablenamersquo[lambda row A( ) ] that will add buttons whentable tablename is displayed

bull linked_tables (list) ndash list of tables to be linked

Example

given you defined a model as

dbdefine_table(person Field(name) format=(name)s)dbdefine_table(dog

Field(name) Field(owner dbperson) format=(name)s)dbdefine_table(comment Field(body) Field(dog dbdog))if db(dbperson)isempty()

from gluoncontribpopulate import populatepopulate(dbperson 300)populate(dbdog 300)populate(dbcomment 1000)

102 Chapter 30 sqlhtml Module

web2py Documentation Release 2146-stable

in a controller you can do

authrequires_login()def index()

form=SQLFORMsmartgrid(db[requestargs(0) or person])return dict(form=form)

widgets = autocomplete ltclass gluonsqlhtmlAutocompleteWidgetgt blob None boolean ltclass gluonsqlhtmlBooleanWidgetgt checkboxes ltclass gluonsqlhtmlCheckboxesWidgetgt date ltclass gluonsqlhtmlDateWidgetgt datetime ltclass gluonsqlhtmlDatetimeWidgetgt decimal ltclass gluonsqlhtmlDecimalWidgetgt double ltclass gluonsqlhtmlDoubleWidgetgt integer ltclass gluonsqlhtmlIntegerWidgetgt json ltclass gluonsqlhtmlJSONWidgetgt list ltclass gluonsqlhtmlListWidgetgt multiple ltclass gluonsqlhtmlMultipleOptionsWidgetgt options ltclass gluonsqlhtmlOptionsWidgetgt password ltclass gluonsqlhtmlPasswordWidgetgt radio ltclass gluonsqlhtmlRadioWidgetgt string ltclass gluonsqlhtmlStringWidgetgt text ltclass gluonsqlhtmlTextWidgetgt time ltclass gluonsqlhtmlTimeWidgetgt upload ltclass gluonsqlhtmlUploadWidgetgt

class gluonsqlhtmlSQLTABLE(sqlrows linkto=None upload=None orderby=None headers=truncate=16 columns=None th_link=rdquo extracolumns=None se-lectid=None renderstyle=False cid=None colgroup=False at-tributes)

Bases gluonhtmlTABLE

Given with a Rows object as returned by a db()select() generates an html table with the rows

Parameters

bull sqlrows ndash the Rows object

bull linkto ndash URL (or lambda to generate a URL) to edit individual records

bull upload ndash URL to download uploaded files

bull orderby ndash Add an orderby link to column headers

bull headers ndash dictionary of headers to headers redefinions headers can also be a string to gen-erate the headers from data for now only headers=rdquofieldnamecapitalizerdquo headers=rdquolabelsrdquoand headers=None are supported

bull truncate ndash length at which to truncate text in table cells Defaults to 16 characters

bull columns ndash a list or dict contaning the names of the columns to be shown Defaults to all

bull th_link ndash base link to support orderby headers

bull extracolumns ndash a list of dicts

bull selectid ndash The id you want to select

bull renderstyle ndash Boolean render the style with the table

bull cid ndash use this cid for all links

bull colgroup ndash FIXME

Extracolumns example

[labelA(Extra _href=)class class name of the headerwidth width in pixels or contentlambda row rc A(Edit _href=editsrowid)selected False agregate class selected to this column]

style()

class gluonsqlhtmlStringWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates an INPUT text tag

see also FormWidgetwidget

103

web2py Documentation Release 2146-stable

class gluonsqlhtmlTextWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates a TEXTAREA tag

see also FormWidgetwidget

class gluonsqlhtmlTimeWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlUploadWidgetBases gluonsqlhtmlFormWidget

DEFAULT_WIDTH = 150px

DELETE_FILE = delete

GENERIC_DESCRIPTION = file download

ID_DELETE_SUFFIX = __delete

static is_image(value)Tries to check if the filename provided references to an image

Checking is based on filename extension Currently recognized gif png jp(e)g bmp

Parameters value ndash filename

classmethod represent(field value download_url=None)How to represent the file

bull with download url and if it is an image ltA href= gtltIMG gtltAgt

bull otherwise with download url ltA href= gtfileltAgt

bull otherwise file

Parameters

bull field ndash the field

bull value ndash the field value

bull download_url ndash url for the file download (default = None)

classmethod widget(field value download_url=None attributes)generates a INPUT file tag

Optionally provides an A link to the file including a checkbox so the file can be deleted

All is wrapped in a DIV

see also FormWidgetwidget

Parameters

bull field ndash the field

bull value ndash the field value

bull download_url ndash url for the file download (default = None)

gluonsqlhtmladd_class(a b)

104 Chapter 30 sqlhtml Module

web2py Documentation Release 2146-stable

gluonsqlhtmlform_factory(fields attributes)Generates a SQLFORM for the given fields

Internally will build a non-database based data model to hold the fields

gluonsqlhtmlformstyle_bootstrap(form fields)bootstrap 23x format form layout

gluonsqlhtmlformstyle_bootstrap3_inline_factory(col_label_size=3)bootstrap 3 horizontal form layout

Note Experimental

gluonsqlhtmlformstyle_bootstrap3_stacked(form fields)bootstrap 3 format form layout

Note Experimental

gluonsqlhtmlformstyle_divs(form fields)divs only

gluonsqlhtmlformstyle_inline(form fields)divs only but inline

gluonsqlhtmlformstyle_table2cols(form fields)2 column table

gluonsqlhtmlformstyle_table3cols(form fields)3 column table - default

gluonsqlhtmlformstyle_ul(form fields)unordered list

gluonsqlhtmlrepresent(field value record)

gluonsqlhtmlsafe_float(x)

gluonsqlhtmlsafe_int(x)

gluonsqlhtmlshow_if(cond)

105

web2py Documentation Release 2146-stable

106 Chapter 30 sqlhtml Module

CHAPTER 31

storage Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

Provides

bull List like list but returns None instead of IndexOutOfBounds

bull Storage like dictionary allowing also for objfoo for obj[lsquofoorsquo]

class gluonstorageListBases list

Like a regular python list but callable When a(i) is called if i is out of bounds returns None instead of IndexError

class gluonstorageStorageBases dict

A Storage object is like a dictionary except objfoo can be used in addition to obj[lsquofoorsquo] and setting objfoo =None deletes item foo

Example

gtgtgt o = Storage(a=1)gtgtgt print oa1

gtgtgt o[a]1

gtgtgt oa = 2gtgtgt print o[a]2

gtgtgt del oa

(continues on next page)

107

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt print oaNone

getfirst(key default=None)Returns the first value of a list or the value itself when given a requestvars style key

If the value is a list its first item will be returned otherwise the value will be returned as-is

Example output for a query string of x=abcampy=abcampy=def

gtgtgt request = Storage()gtgtgt requestvars = Storage()gtgtgt requestvarsx = abcgtgtgt requestvarsy = [abc def]gtgtgt requestvarsgetfirst(x)abcgtgtgt requestvarsgetfirst(y)abcgtgtgt requestvarsgetfirst(z)

getlast(key default=None)Returns the last value of a list or value itself when given a requestvars style key

If the value is a list the last item will be returned otherwise the value will be returned as-is

Simulated output with a query string of x=abcampy=abcampy=def

gtgtgt request = Storage()gtgtgt requestvars = Storage()gtgtgt requestvarsx = abcgtgtgt requestvarsy = [abc def]gtgtgt requestvarsgetlast(x)abcgtgtgt requestvarsgetlast(y)defgtgtgt requestvarsgetlast(z)

getlist(key)Returns a Storage value as a list

If the value is a list it will be returned as-is If object is None an empty list will be returned Otherwise[value] will be returned

Example output for a query string of x=abcampy=abcampy=def

gtgtgt request = Storage()gtgtgt requestvars = Storage()gtgtgt requestvarsx = abcgtgtgt requestvarsy = [abc def]gtgtgt requestvarsgetlist(x)[abc]gtgtgt requestvarsgetlist(y)[abc def]gtgtgt requestvarsgetlist(z)[]

class gluonstorageSettingsBases gluonstorageStorage

108 Chapter 31 storage Module

web2py Documentation Release 2146-stable

class gluonstorageMessages(T)Bases gluonstorageSettings

class gluonstorageStorageListBases gluonstorageStorage

Behaves like Storage but missing elements defaults to [] instead of None

gluonstorageload_storage(filename)

gluonstoragesave_storage(storage filename)

109

web2py Documentation Release 2146-stable

110 Chapter 31 storage Module

CHAPTER 32

streamer Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

321 Facilities to handle file streaming

gluonstreamerstream_file_or_304_or_206(static_file chunk_size=65536 request=Noneheaders= status=200 error_message=None)

gluonstreamerstreamer(stream chunk_size=65536 bytes=None)

111

web2py Documentation Release 2146-stable

112 Chapter 32 streamer Module

CHAPTER 33

template Module

This file is part of the web2py Web FrameworkLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)Author Thadeus BurgessContributors- Massimo Di Pierro for creating the original gluontemplatepy- Jonathan Lundell for extensively testing the regex on Jython- Limodou (creater of uliweb) who inspired the block-element support for web2py

331 Templating syntax

class gluontemplateBlockNode(name=rdquo pre_extend=False delimiters=(rsquorsquo rsquorsquo))Bases gluontemplateNode

Block Container

This Node can contain other Nodes and will render in a hierarchical order of when nodes were added

ie

block test This is default block test

end

append(node)Adds an element to the nodes

Parameters node ndash Node object or string to append

extend(other)Extends the list of nodes with another BlockNode class

Parameters other ndash BlockNode or Content object to extend from

113

web2py Documentation Release 2146-stable

output(blocks)Merges all nodes into a single string

Parameters blocks ndash Dictionary of blocks that are extending from this template

class gluontemplateContent(name=rsquoContentBlockrsquo pre_extend=False)Bases gluontemplateBlockNode

Parent Container ndash Used as the root level BlockNode

Contains functions that operate as such

Parameters name ndash Unique name for this BlockNode

append(node)Adds a node to list If it is a BlockNode then we assign a block for it

clear_content()

extend(other)Extends the objects list of nodes with another objects nodes

insert(other index=0)Inserts object at index

You may pass a list of objects and have them inserted

class gluontemplateDummyResponse

write(data escape=True)

class gluontemplateNOESCAPE(text)A little helper to avoid escaping

xml()

class gluontemplateNode(value=None pre_extend=False)Bases object

Basic Container Object

class gluontemplateSuperNode(name=rdquo pre_extend=False)Bases gluontemplateNode

class gluontemplateTemplateParser(text name=rsquoParserContainerrsquo context=path=rsquoviewsrsquo writer=rsquoresponsewritersquo lexers=delimiters=(rsquorsquo rsquorsquo) _super_nodes=[])

Bases object

Parse all blocks

Parameters

bull text ndash text to parse

bull context ndash context to parse in

bull path ndash folder path to templates

bull writer ndash string of writer class to use

bull lexers ndash dict of custom lexers to use

bull delimiters ndash for example (lsquolsquorsquorsquo)

114 Chapter 33 template Module

web2py Documentation Release 2146-stable

bull _super_nodes ndash a list of nodes to check for inclusion this should only be set byldquoselfextendrdquo It contains a list of SuperNodes from a child template that need to be han-dled

default_delimiters = ( )

extend(filename)Extends filename Anything not declared in a block defined by the parent will be placed in the parenttemplates include block

include(content filename)Includes filename here

parse(text)

r_multiline = lt_sreSRE_Pattern objectgt

r_tag = lt_sreSRE_Pattern objectgt

re_block = lt_sreSRE_Pattern objectgt

re_pass = lt_sreSRE_Pattern objectgt

re_unblock = lt_sreSRE_Pattern objectgt

reindent(text)Reindents a string of unindented python code

to_string()Returns the parsed template with correct indentation

Used to make it easier to port to python3

gluontemplateget_parsed(text)Returns the indented python code of text Useful for unit testing

gluontemplateoutput_aux(node blocks)

gluontemplateparse_template(filename path=rsquoviewsrsquo context= lexers= delimiters=(rsquorsquorsquorsquo))

Parameters

bull filename ndash can be a view filename in the views folder or an input stream

bull path ndash is the path of a views folder

bull context ndash is a dictionary of symbols used to render the template

bull lexers ndash dict of custom lexers to use

bull delimiters ndash opening and closing tags

gluontemplaterender(content=rsquohello worldrsquo stream=None filename=None path=None con-text= lexers= delimiters=(rsquorsquo rsquorsquo) writer=rsquoresponsewritersquo)

Generic render function

Parameters

bull content ndash default content

bull stream ndash file-like obj to read template from

bull filename ndash where to find template

bull path ndash base path for templates

bull context ndash env

331 Templating syntax 115

web2py Documentation Release 2146-stable

bull lexers ndash custom lexers to use

bull delimiters ndash opening and closing tags

bull writer ndash where to inject the resulting stream

Example

gtgtgt render()hello worldgtgtgt render(content=abc)abcgtgtgt render(content=abc)abcgtgtgt render(content=abc)abcgtgtgt render(content=anbc)anbcgtgtgt render(content=abcde)abcdegtgtgt render(content=anc)ancgtgtgt render(content=ac)acgtgtgt render(content=for i in range(a)=iltbr gtpassrarr˓context=dict(a=5))0ltbr gt1ltbr gt2ltbr gt3ltbr gt4ltbr gtgtgtgt render(content=for i in range(a)=iltbr gtpassrarr˓context=dict(a=5)delimiters=())0ltbr gt1ltbr gt2ltbr gt3ltbr gt4ltbr gtgtgtgt render(content==hellonworld)hellonworldgtgtgt render(content=for i in range(3)n=inpass)012

116 Chapter 33 template Module

CHAPTER 34

tools Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

341 Auth Mail PluginManager and various utilities

class gluontoolsMail(server=None sender=None login=None tls=True)Bases object

Class for configuring and sending emails with alternative text html body multiple attachments and encryptionsupport

Works with SMTP and Google App Engine

Parameters

bull server ndash SMTP server address in addressport notation

bull sender ndash sender email address

bull login ndash sender login name and password in loginpassword notation or None if no authen-tication is required

bull tls ndash enablesdisables encryption (True by default)

In Google App Engine use

server=gae

For sake of backward compatibility all fields are optional and default to None however to be able to send emailsat least server and sender must be specified They are available under following fields

117

web2py Documentation Release 2146-stable

mailsettingsservermailsettingssendermailsettingsloginmailsettingstimeout = 60 seconds (default)

When server is lsquologgingrsquo email is logged but not sent (debug mode)

Optionally you can use PGP encryption or X509

mailsettingscipher_type = Nonemailsettingsgpg_home = Nonemailsettingssign = Truemailsettingssign_passphrase = Nonemailsettingsencrypt = Truemailsettingsx509_sign_keyfile = Nonemailsettingsx509_sign_certfile = Nonemailsettingsx509_sign_chainfile = Nonemailsettingsx509_nocerts = Falsemailsettingsx509_crypt_certfiles = None

cipher_type Nonegpg - need a python-pyme package and gpgme libx509 - smime

gpg_home you can set a GNUPGHOME environment variableto specify home of gnupg

sign sign the message (True or False)sign_passphrase passphrase for key signingencrypt encrypt the message (True or False) It defaults

to True x509 only

x509_sign_keyfile the signers private key filename orstring containing the key (PEM format)

x509_sign_certfile the signers certificate filename orstring containing the cert (PEM format)

x509_sign_chainfile sets the optional all-in-one file where youcan assemble the certificates of CertificationAuthorities (CA) which form the certificatechain of email certificate It can be astring containing the certs to (PEM format)

x509_nocerts if True then no attached certificate in mailx509_crypt_certfiles the certificates file or strings to encrypt

the messages with can be a file name string or a list of file names strings (PEM format)

Examples

Create Mail object with authentication data for remote server

mail = Mail(examplecom25 meexamplecom mepassword)

Notice for GAE users attachments have an automatic content_id=rsquoattachment-irsquo where i is progressive num-ber in this way the can be referenced from the HTML as ltimg src=rdquocidattachment-0rdquo gt etc

118 Chapter 34 tools Module

web2py Documentation Release 2146-stable

class Attachment(payload filename=None content_id=None content_type=Noneencoding=rsquoutf-8rsquo)

Bases emailmimebaseMIMEBase

Email attachment

Parameters

bull payload ndash path to file or file-like object with read() method

bull filename ndash name of the attachment stored in message if set to None it will be fetchedfrom payload path file-like object payload must have explicit filename specified

bull content_id ndash id of the attachment automatically contained within lt and gt

bull content_type ndash content type of the attachment if set to None it will be fetched fromfilename using gluoncontenttype module

bull encoding ndash encoding of all strings passed to this function (except attachment body)

Content ID is used to identify attachments within the html body in example attached image with contentID lsquophotorsquo may be used in html message as a source of img tag ltimg src=rdquocidphotordquo gt

Example Create attachment from text file

attachment = MailAttachment(pathtofiletxt)

Content-Type textplainMIME-Version 10Content-Disposition attachment filename=filetxtContent-Transfer-Encoding base64

SOMEBASE64CONTENT=

Create attachment from image file with custom filename and cid

attachment = MailAttachment(pathtofilepngfilename=photopngcontent_id=photo)

Content-Type imagepngMIME-Version 10Content-Disposition attachment filename=photopngContent-Id ltphotogtContent-Transfer-Encoding base64

SOMEOTHERBASE64CONTENT=

send(to subject=rsquo[no subject]rsquo message=rsquo[no message]rsquo attachments=None cc=None bcc=Nonereply_to=None sender=None encoding=rsquoutf-8rsquo raw=False headers= from_address=Nonecipher_type=None sign=None sign_passphrase=None encrypt=None x509_sign_keyfile=Nonex509_sign_chainfile=None x509_sign_certfile=None x509_crypt_certfiles=Nonex509_nocerts=None)

Sends an email using data specified in constructor

Parameters

bull to ndash list or tuple of receiver addresses will also accept single object

bull subject ndash subject of the email

bull message ndash email body text depends on type of passed object

341 Auth Mail PluginManager and various utilities 119

web2py Documentation Release 2146-stable

ndash if 2-list or 2-tuple is passed first element will be source of plain text while second ofhtml text

ndash otherwise object will be the only source of plain text and html source will be set toNone

If text or html source is

ndash None content part will be ignored

ndash string content part will be set to it

ndash file-like object content part will be fetched from it using itrsquos read() method

bull attachments ndash list or tuple of MailAttachment objects will also accept single object

bull cc ndash list or tuple of carbon copy receiver addresses will also accept single object

bull bcc ndash list or tuple of blind carbon copy receiver addresses will also accept single object

bull reply_to ndash address to which reply should be composed

bull encoding ndash encoding of all strings passed to this method (including message bodies)

bull headers ndash dictionary of headers to refine the headers just before sending mail eg lsquoX-Mailerrsquo lsquoweb2py mailerrsquo

bull from_address ndash address to appear in the lsquoFromrsquo header this is not the envelopesender If not specified the sender will be used

bull cipher_type ndash gpg - need a python-pyme package and gpgme lib x509 - smime

bull gpg_home ndash you can set a GNUPGHOME environment variable to specify home ofgnupg

bull sign ndash sign the message (True or False)

bull sign_passphrase ndash passphrase for key signing

bull encrypt ndash encrypt the message (True or False) It defaults to True x509 only

bull x509_sign_keyfile ndash the signers private key filename or string containing the key(PEM format)

bull x509_sign_certfile ndash the signers certificate filename or string containing the cert(PEM format)

bull x509_sign_chainfile ndash sets the optional all-in-one file where you can assemblethe certificates of Certification Authorities (CA) which form the certificate chain of emailcertificate It can be a string containing the certs to (PEM format)

bull x509_nocerts ndash if True then no attached certificate in mail

bull x509_crypt_certfiles ndash the certificates file or strings to encrypt the messages withcan be a file name string or a list of file names strings (PEM format)

Examples

Send plain text message to single address

mailsend(youexamplecomMessage subjectPlain text body of the message)

120 Chapter 34 tools Module

web2py Documentation Release 2146-stable

Send html message to single address

mailsend(youexamplecomMessage subjectlthtmlgtPlain text body of the messagelthtmlgt)

Send text and html message to three addresses (two in cc)

mailsend(youexamplecomMessage subject(Plain text body lthtmlgthtml bodylthtmlgt)cc=[other1examplecom other2examplecom])

Send html only message with image attachment available from the message by lsquophotorsquo content id

mailsend(youexamplecomMessage subject(None lthtmlgtltimg src=cidphoto gtlthtmlgt)MailAttachment(pathtophotojpg

content_id=photo))

Send email with two attachments and no body text

mailsend(youexamplecomMessage subjectNone[MailAttachment(pathtofistfile)MailAttachment(pathtosecondfile)])

Returns True on success False on failure

Before return method updates two objectrsquos fields

bull selfresult return value of smtplibSMTPsendmail() or GAErsquos mailsend_mail() method

bull selferror Exception message or None if above was successful

class gluontoolsAuth(environment=None db=None mailer=True hmac_key=None con-troller=rsquodefaultrsquo function=rsquouserrsquo cas_provider=None signature=Truesecure=False csrf_prevention=True propagate_extension=Noneurl_index=None jwt=None host_names=None)

Bases object

accessible_query(name table user_id=None)Returns a query with all accessible records for user_id or the current logged in user this method does notwork on GAE because uses JOIN and IN

Example

Use as

db(authaccessible_query(read dbmytable))select(dbmytableALL)

add_group(role description=rdquo)Creates a group associated to a role

add_membership(group_id=None user_id=None role=None)Gives user_id membership of group_id or role if user is None than user_id is that of current logged in user

341 Auth Mail PluginManager and various utilities 121

web2py Documentation Release 2146-stable

add_permission(group_id name=rsquoanyrsquo table_name=rdquo record_id=0)Gives group_id lsquonamersquo access to lsquotable_namersquo and lsquorecord_idrsquo

allows_jwt(otherwise=None)

static archive(form archive_table=None current_record=rsquocurrent_recordrsquoarchive_current=False fields=None)

If you have a table (dbmytable) that needs full revision history you can just do

form = crudupdate(dbmytable myrecord onaccept=autharchive)

or

form = SQLFORM(dbmytable myrecord)process(onaccept=autharchive)

crudarchive will define a new table ldquomytable_archiverdquo and store a copy of the current record (ifarchive_current=True) or a copy of the previous record (if archive_current=False) in the newly createdtable including a reference to the current record

fields allows to specify extra fields that need to be archived

If you want to access such table you need to define it yourself in a model

dbdefine_table(mytable_archiveField(current_record dbmytable)dbmytable)

Notice such table includes all fields of dbmytable plus one current_record crudarchive does not times-tamp the stored record unless your original table has a fields like

dbdefine_table(Field(saved_on datetime

default=requestnow update=requestnow writable=False)Field(saved_by authuser

default=authuser_id update=authuser_id writable=False)

there is nothing special about these fields since they are filled before the record is archived

If you want to change the archive table name and the name of the reference field you can do for example

dbdefine_table(myhistoryField(parent_record dbmytable) dbmytable)

and use it as

form = crudupdate(dbmytable myrecordonaccept=lambda formcrudarchive(form

archive_table=dbrarr˓myhistory

current_record=parent_rarr˓record))

basic(basic_auth_realm=False)Performs basic login

Parameters basic_auth_realm ndash optional basic http authentication realm Can take str orunicode or function or callable or boolean

reads currentrequestenvhttp_authorization and returns basic_allowedbasic_accepteduser

122 Chapter 34 tools Module

web2py Documentation Release 2146-stable

if basic_auth_realm is defined is a callable itrsquos return value is used to set the basic authentication realm ifitrsquos a string its content is used instead Otherwise basic authentication realm is set to the application nameIf basic_auth_realm is None or False (the default) the behavior is to skip sending any challenge

bulk_register(max_emails=100)Creates a form for ther user to send invites to other users to join

cas_login(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt version=2)

cas_validate(version=2 proxy=False)

change_password(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form that lets the user change password

confirm_registration(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form to confirm user registration

default_messages = access_denied Insufficient privileges add_group_log Group (group_id)s created add_membership_log None add_permission_log None bulk_invite_body You have been invited to join (site)s click (link)s to complete the process bulk_invite_subject Invitation to join (site)s change_password_log User (id)s Password changed del_group_log Group (group_id)s deleted del_membership_log None del_permission_log None delete_label Check to delete email_sent Email sent email_taken This email already has an account email_verified Email verified function_disabled Function disabled group_description Group uniquely assigned to user (id)s has_membership_log None has_permission_log None impersonate_log User (id)s is impersonating (other_id)s invalid_email Invalid email invalid_login Invalid login invalid_password Invalid password invalid_reset_password Invalid reset password invalid_two_factor_code Incorrect code 0 more attempt(s) remaining invalid_user Invalid user invalid_username Invalid username is_empty Cannot be empty label_client_ip Client IP label_description Description label_email E-mail label_first_name First name label_group_id Group ID label_last_name Last name label_name Name label_origin Origin label_password Password label_record_id Record ID label_registration_id Registration identifier label_registration_key Registration key label_remember_me Remember me (for 30 days) label_reset_password_key Reset Password key label_role Role label_table_name Object or table name label_time_stamp Timestamp label_two_factor Authentication code label_user_id User ID label_username Username logged_in Logged in logged_out Logged out login_button Log In login_disabled Login disabled by administrator login_failed_log None login_log User (id)s Logged-in logout_log User (id)s Logged-out mismatched_password Password fields dont match new_password New password new_password_sent A new password was emailed to you old_password Old password password_change_button Change password password_changed Password changed password_reset_button Request reset password profile_log User (id)s Profile updated profile_save_button Apply changes profile_updated Profile updated register_button Sign Up register_log User (id)s Registered registration_pending Registration is pending approval registration_successful Registration successful registration_verifying Registration needs verification reset_password Click on the link (link)s to reset your password reset_password_log User (id)s Password reset reset_password_subject Password reset retrieve_password Your password is (password)s retrieve_password_log User (id)s Password retrieved retrieve_password_subject Password retrieve retrieve_two_factor_code Your temporary login code is 0 retrieve_two_factor_code_subject Two-step Login Authentication Code retrieve_username Your username is (username)s retrieve_username_log User (id)s Username retrieved retrieve_username_subject Username retrieve submit_button Submit two_factor_comment This code was emailed to you and is required for login unable_send_email Unable to send email unable_to_send_email Unable to send email username_sent Your username was emailed to you username_taken Username already taken verify_email Welcome (username)s Click on the link (link)s to verify your email verify_email_log User (id)s Verification email sent verify_email_subject Email verification verify_password Verify Password verify_password_comment please input your password againClass for authentication authorization role based access control

Includes

bull registration and profile

bull login and logout

bull username and password retrieval

bull event logging

bull role creation and assignment

bull user defined grouprole based permission

Parameters

bull environment ndash is there for legacy but unused (awful)

bull db ndash has to be the database where to create tables for authentication

bull mailer ndash Mail( ) or None (no mailer) or True (make a mailer)

bull hmac_key ndash can be a hmac_key or hmac_key=Authget_or_create_key()

bull controller ndash (where is the user action)

bull cas_provider ndash (delegate authentication to the URL CAS2)

Authentication Example

from gluoncontributils import mail=Mail()mailsettingsserver=smtpgmailcom587mailsettingssender=yousomewherecommailsettingslogin=usernamepasswordauth=Auth(db)authsettingsmailer=mail authsettings=authdefine_tables()def authentication()

return dict(form=auth())

341 Auth Mail PluginManager and various utilities 123

web2py Documentation Release 2146-stable

Exposes

bull http applicationcontrollerauthenticationlogin

bull http applicationcontrollerauthenticationlogout

bull http applicationcontrollerauthenticationregister

bull http applicationcontrollerauthenticationverify_email

bull http applicationcontrollerauthenticationretrieve_username

bull http applicationcontrollerauthenticationretrieve_password

bull http applicationcontrollerauthenticationreset_password

bull http applicationcontrollerauthenticationprofile

bull http applicationcontrollerauthenticationchange_password

On registration a group with role=new_userid is created and user is given membership of this group

You can create a group with

group_id=authadd_group(Manager can access the manage action)authadd_permission(group_id access to manage)

Here ldquoaccess to managerdquo is just a user defined string You can give access to a user

authadd_membership(group_id user_id)

If user id is omitted the logged in user is assumed

Then you can decorate any action

authrequires_permission(access to manage)def manage()

return dict()

You can restrict a permission to a specific table

authadd_permission(group_id edit dbsometable)authrequires_permission(edit dbsometable)

Or to a specific record

authadd_permission(group_id edit dbsometable 45)authrequires_permission(edit dbsometable 45)

If authorization is not granted calls

authsettingson_failed_authorization

Other options

authsettingsmailer=Noneauthsettingsexpiration=3600 seconds

these are messages that can be customized

124 Chapter 34 tools Module

web2py Documentation Release 2146-stable

default_settings = allow_basic_login False allow_basic_login_only False allow_delete_accounts False alternate_requires_registration False auth_manager_role None auth_two_factor_enabled False auth_two_factor_tries_left 3 bulk_register_enabled False captcha None cas_maps None client_side True create_user_groups user_(id)s email_case_sensitive True everybody_group_id None expiration 3600 formstyle None hideerror False keep_session_onlogin True keep_session_onlogout False label_separator None logging_enabled True login_after_password_change True login_after_registration False login_captcha None login_email_validate True login_userfield None logout_onlogout None long_expiration 2592000 manager_actions multi_login False on_failed_authentication ltfunction ltlambdagt at 0x7fcf0cf9f578gt ondelete CASCADE password_field password password_min_length 4 pre_registration_div None prevent_open_redirect_attacks True prevent_password_reset_attacks True profile_fields None register_captcha None register_fields None register_verify_password True registration_requires_approval False registration_requires_verification False remember_me_form True renew_session_onlogin True renew_session_onlogout True reset_password_requires_verification False retrieve_password_captcha None retrieve_username_captcha None showid False table_cas None table_cas_name auth_cas table_event None table_event_name auth_event table_group None table_group_name auth_group table_membership None table_membership_name auth_membership table_permission None table_permission_name auth_permission table_token_name auth_token table_user None table_user_name auth_user two_factor_authentication_group None update_fields [email] use_username False username_case_sensitive True wiki ltStorage gt

define_signature()

define_tables(username=None signature=None enable_tokens=False migrate=Nonefake_migrate=None)

To be called unless tables are defined manually

Examples

Use as

defines all needed tables and table files myprefix_auth_usertable authdefine_tables(migrate=myprefix_)

defines all needed tables without migrationtable filesauthdefine_tables(migrate=False)

del_group(group_id)Deletes a group

del_membership(group_id=None user_id=None role=None)Revokes membership from group_id to user_id if user_id is None than user_id is that of current logged inuser

del_permission(group_id name=rsquoanyrsquo table_name=rdquo record_id=0)Revokes group_id lsquonamersquo access to lsquotable_namersquo and lsquorecord_idrsquo

email_registration(subject body user)Sends and email invitation to a user informing they have been registered with the application

email_reset_password(user)

enable_record_versioning(tables archive_db=None archive_names=rsquo(tablename)s_archiversquocurrent_record=rsquocurrent_recordrsquo current_record_label=None)

Used to enable full record versioning (including auth tables)

auth = Auth(db)authdefine_tables(signature=True) define our own tablesdbdefine_table(mythingField(name)authsignature)authenable_record_versioning(tables=db)

tables can be the db (all table) or a list of tables only tables with modified_by and modified_on fiels (ascreated by authsignature) will have versioning Old record versions will be in table lsquomything_archiversquoautomatically defined

when you enable enable_record_versioning records are never deleted but marked with is_active=False

enable_record_versioning enables a common_filter for every table that filters out records with is_active =False

Note If you use authenable_record_versioning do not use autharchive or you will end up with dupli-cates autharchive does explicitly what enable_record_versioning does automatically

static get_or_create_key(filename=None alg=rsquosha512rsquo)

341 Auth Mail PluginManager and various utilities 125

web2py Documentation Release 2146-stable

get_or_create_user(keys update_fields=[rsquoemailrsquo] login=True get=True)Used for alternate login methods If the user exists already then password is updated If the user doesnrsquotyet exist then they are created

get_vars_next()

groups()Displays the groups and their roles for the logged in user

has_membership(group_id=None user_id=None role=None)Checks if user is member of group_id or role

has_permission(name=rsquoanyrsquo table_name=rdquo record_id=0 user_id=None group_id=None)Checks if user_id or current logged in user is member of a group that has lsquonamersquo permission on lsquota-ble_namersquo and lsquorecord_idrsquo if group_id is passed it checks whether the group has the permission

here()

id_group(role)Returns the group_id of the group specified by the role

impersonate(user_id=ltfunction ltlambdagtgt)To use this make a POST to http impersonate requestpost_varsuser_id=ltidgt

Set requestpost_varsuser_id to 0 to restore original user

requires impersonator is logged in and

has_permission(impersonate auth_user user_id)

is_impersonating()

is_logged_in()Checks if the user is logged in and returns TrueFalse If so user is in authuser as well as in ses-sionauthuser

jwt()To use JWT authentication 1) instantiate auth with

auth = Auth(db jwt = secret_keysecret)

where lsquosecretrsquo is your own secret string

2 Decorate functions that require login but should accept the JWT token credentials

authallows_jwt()authrequires_login()def myapi() return hello s authuseremail

Notice jwt is allowed but not required if user is logged in myapi is accessible

3 Use it

Now API users can obtain a token with

http appdefaultuserjwtusername= amppassword=

(returns json object with a token attribute) API users can refresh an existing token with

http appdefaultuserjwttoken=

they can authenticate themselves when calling http myapi by injecting a header

Authorization Bearer ltthe jwt tokengt

126 Chapter 34 tools Module

web2py Documentation Release 2146-stable

Any additional attributes in the jwt argument of Auth() below

auth = Auth(db jwt = )

are passed to the constructor of class AuthJWT Look there for documentation

log_event(description vars=None origin=rsquoauthrsquo)

Examples

Use as

authlog_event(description=this happened origin=auth)

login(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a login form

login_bare(username password)Logins user as specified by username (or email) and password

login_user(user)Logins the user = dbauth_user(id)

logout(next=ltfunction ltlambdagtgt onlogout=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)Logouts and redirects to login

logout_bare()

manage_tokens()

navbar(prefix=rsquoWelcomersquo action=None separators=(rsquo [ rsquo rsquo | rsquo rsquo ] rsquo) user_identifier=ltfunctionltlambdagtgt referrer_actions=ltfunction ltlambdagtgt mode=rsquodefaultrsquo)

Navbar with support for more templates This uses some code from the old navbar

Parameters mode ndash see options for list of

not_authorized()You can change the view for this page to make it look as you like

profile(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form that lets the user change hisher profile

random_password()

register(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a registration form

register_bare(fields)Registers a user as specified by username (or email) and a raw password

request_reset_password(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgtonaccept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form to reset the user password

requires(condition requires_login=True otherwise=None)Decorator that prevents access to action if not logged in

requires_login(otherwise=None)Decorator that prevents access to action if not logged in

341 Auth Mail PluginManager and various utilities 127

web2py Documentation Release 2146-stable

requires_login_or_token(otherwise=None)

requires_membership(role=None group_id=None otherwise=None)Decorator that prevents access to action if not logged in or if user logged in is not a member of group_idIf role is provided instead of group_id then the group_id is calculated

requires_permission(name table_name=rdquo record_id=0 otherwise=None)Decorator that prevents access to action if not logged in or if user logged in is not a member of any group(role) that has lsquonamersquo access to lsquotable_namersquo lsquorecord_idrsquo

requires_signature(otherwise=None hash_vars=True)Decorator that prevents access to action if not logged in or if user logged in is not a member of group_idIf role is provided instead of group_id then the group_id is calculated

reset_password(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form to reset the user password

reset_password_deprecated(next=ltfunction ltlambdagtgt onvalidation=ltfunctionltlambdagtgt onaccept=ltfunction ltlambdagtgt log=ltfunctionltlambdagtgt)

Returns a form to reset the user password (deprecated)

retrieve_password(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

retrieve_username(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form to retrieve the user username (only if there is a username field)

run_login_onaccept()

select_host(host host_names=None)checks that host is valid ie in the list of glob host_names if the host is missing then is it selects the firstentry from host_names read more here httpsgithubcomweb2pyweb2pyissues1196

table_cas()

table_event()

table_group()

table_membership()

table_permission()

table_token()

table_user()

update_groups()

url(f=None args=None vars=None scheme=False)

user_group(user_id=None)Returns the group_id of the group uniquely associated to this user ie role=user[user_id]

user_group_role(user_id=None)

user_iduserid or None

verify_email(next=ltfunction ltlambdagtgt onaccept=ltfunction ltlambdagtgt log=ltfunctionltlambdagtgt)

Action used to verify the registration email

128 Chapter 34 tools Module

web2py Documentation Release 2146-stable

when_is_logged_in_bypass_next_in_url(next session)This function should be use when someone want to avoid asking for user credentials when loaded pagecontains ldquouserlogin_next=NEXT_COMPONENTrdquo in the URL is refresh but user is already authenti-cated

wiki(slug=None env=None render=rsquomarkminrsquo manage_permissions=False force_prefix=rdquo re-strict_search=False resolve=True extra=None menu_groups=None templates=None mi-grate=True controller=None function=None force_render=False groups=None)

wikimenu()To be used in menupy for app wide wiki menus

class gluontoolsRecaptcha(request=None public_key=rdquo private_key=rdquo use_ssl=False er-ror=None error_message=rsquoinvalidrsquo label=rsquoVerifyrsquo options=rdquocomment=rdquo ajax=False)

Bases gluonhtmlDIV

Examples

Use as

form = FORM(Recaptcha(public_key= private_key=))

or

form = SQLFORM()formappend(Recaptcha(public_key= private_key=))

API_SERVER = httpwwwgooglecomrecaptchaapi

API_SSL_SERVER = httpswwwgooglecomrecaptchaapi

VERIFY_SERVER = httpwwwgooglecomrecaptchaapiverify

xml()generates the xml for this component

class gluontoolsRecaptcha2(request=None public_key=rdquo private_key=rdquo er-ror_message=rsquoinvalidrsquo label=rsquoVerifyrsquo options=None com-ment=rdquo)

Bases gluonhtmlDIV

Experimental Creates a DIV holding the newer Recaptcha from Google (v2)

Parameters

bull request ndash the request If not passed uses current request

bull public_key ndash the public key Google gave you

bull private_key ndash the private key Google gave you

bull error_message ndash the error message to show if verification fails

bull label ndash the label to use

bull options (dict) ndash takes these parameters

ndash hl

ndash theme

ndash type

341 Auth Mail PluginManager and various utilities 129

web2py Documentation Release 2146-stable

ndash tabindex

ndash callback

ndash expired-callback

see httpsdevelopersgooglecomrecaptchadocsdisplay for docs about those

bull comment ndash the comment

Examples

Use as

form = FORM(Recaptcha2(public_key= private_key=))

or

form = SQLFORM()formappend(Recaptcha2(public_key= private_key=))

to protect the login page instead use

from gluontools import Recaptcha2authsettingscaptcha = Recaptcha2(request public_key= private_key=)

API_URI = httpswwwgooglecomrecaptchaapijs

VERIFY_SERVER = httpswwwgooglecomrecaptchaapisiteverify

xml()generates the xml for this component

class gluontoolsCrud(environment db=None controller=rsquodefaultrsquo)Bases object

static archive(form archive_table=None current_record=rsquocurrent_recordrsquo)

create(table next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt message=ltfunction ltlambdagtgt form-name=ltfunction ltlambdagtgt attributes)

delete(table record_id next=ltfunction ltlambdagtgt message=ltfunction ltlambdagtgt)

get_format(field)

get_query(field op value refsearch=False)

has_permission(name table record=0)

log_event(message vars)

read(table record)

rows(table query=None fields=None orderby=None limitby=None)

search(tables args)Creates a search form and its results for a table rubric Examples

Use as

130 Chapter 34 tools Module

web2py Documentation Release 2146-stable

form results = crudsearch(dbtestqueries = [equals not equal contains]query_labels=equalsEquals

not equalNot equalfields = [idchildren]field_labels =

idIDchildrenChildrenzero=Please choosequery = (dbtestid gt 0)amp(dbtestid = 3) )

select(table query=None fields=None orderby=None limitby=None headers=None attr)

tables()

update(table record next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt ondelete=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgtmessage=ltfunction ltlambdagtgt deletable=ltfunction ltlambdagtgt formname=ltfunctionltlambdagtgt attributes)

url(f=None args=None vars=None)This should point to the controller that exposes download and crud

class gluontoolsService(environment=None)Bases object

exception JsonRpcException(code info)Bases exceptionsException

amfrpc(f)

Example

Use as

service = Service()serviceamfrpcdef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget httpappdefaultcallamfrpcmyfunctiona=helloampb=world

amfrpc3(domain=rsquodefaultrsquo)

Example

Use as

service = Service()serviceamfrpc3(domain)def myfunction(a b)

return a + bdef call()

return service()

341 Auth Mail PluginManager and various utilities 131

web2py Documentation Release 2146-stable

Then call it with

wget http appdefaultcallamfrpc3myfunctiona=helloampb=world

csv(f)

Example

Use as

service = Service()servicecsvdef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget httpappdefaultcallcsvmyfunctiona=3ampb=4

error()

json(f)

Example

Use as

service = Service()servicejsondef myfunction(a b)

return [a b]def call()

return service()

Then call it with

wget http appdefaultcalljsonmyfunctiona=helloampb=world

jsonrpc(f)

Example

Use as

service = Service()servicejsonrpcdef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget http appdefaultcalljsonrpcmyfunctiona=helloampb=world

132 Chapter 34 tools Module

web2py Documentation Release 2146-stable

jsonrpc2(f)

Example

Use as

service = Service()servicejsonrpc2def myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget ndashpost-data lsquoldquojsonrpcrdquo ldquo20rdquo ldquoidrdquo 1 ldquomethodrdquo ldquomyfunctionrdquo ldquoparamsrdquo ldquoardquo 1 ldquobrdquo2rsquo http appdefaultcalljsonrpc2

jsonrpc_errors = -32700 (Parse error Invalid JSON was received by the server An error occurred on the server while parsing the JSON text) -32603 (Internal error Internal JSON-RPC error) -32602 (Invalid params Invalid method parameter(s)) -32601 (Method not found The method does not exist is not available) -32600 (Invalid Request The JSON sent is not a valid Request object) -32099 (Server error Reserved for implementation-defined server-errors)

rss(f)

Example

Use as

service = Service()servicerssdef myfunction()

return dict(title= link= description=created_on= entries=[dict(title= link=

description= created_on=])def call()

return service()

Then call it with

wget http appdefaultcallrssmyfunction

run(f)

Example

Use as

service = Service()servicerundef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget httpappdefaultcallrunmyfunctiona=3ampb=4

341 Auth Mail PluginManager and various utilities 133

web2py Documentation Release 2146-stable

serve_amfrpc(version=0)

serve_csv(args=None)

serve_json(args=None)

serve_jsonrpc()

serve_jsonrpc2(data=None batch_element=False)

serve_rss(args=None)

serve_run(args=None)

serve_soap(version=rsquo11rsquo)

serve_xml(args=None)

serve_xmlrpc()

soap(name=None returns=None args=None doc=None)

Example

Use as

service = Service()servicesoap(MyFunctionreturns=resultintargs=aintbint)def myfunction(a b)

return a + bdef call()

return service()

Then call it with

from gluoncontribpysimplesoapclient import SoapClientclient = SoapClient(wsdl=httpappdefaultcallsoapWSDL)response = clientMyFunction(a=1b=2)return response[result]

It also exposes online generated documentation and xml example messages athttp appdefaultcallsoap

xml(f)

Example

Use as

service = Service()servicexmldef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget httpappdefaultcallxmlmyfunctiona=3ampb=4

134 Chapter 34 tools Module

web2py Documentation Release 2146-stable

xmlrpc(f)

Example

Use as

service = Service()servicexmlrpcdef myfunction(a b)

return a + bdef call()

return service()

The call it with

wget http appdefaultcallxmlrpcmyfunctiona=helloampb=world

class gluontoolsWiki(auth env=None render=rsquomarkminrsquo manage_permissions=Falseforce_prefix=rdquo restrict_search=False extra=None menu_groups=Nonetemplates=None migrate=True controller=None function=Nonegroups=None)

Bases object

automenu()adds the menu if not present

can_edit(page=None)

can_manage()

can_read(page)

can_search()

can_see_menu()

cloud()

static component(text)In wiki docs allows componentcontrollerfunctionargs which renders as a LOAD( ajax=True)

create()

edit(slug from_template=0)

editmedia(slug)

everybody = everybody

first_paragraph(page)

fix_hostname(body)

get_renderer()

html_render(page)

markmin_base(body)

markmin_render(page)

media(id)

menu(controller=rsquodefaultrsquo function=rsquoindexrsquo)

341 Auth Mail PluginManager and various utilities 135

web2py Documentation Release 2146-stable

not_authorized(page=None)

pages()

preview(render)

read(slug force_render=False)

render_tags(tags)

rows_page = 25

search(tags=None query=None cloud=True preview=True limitby=(0 100) orderby=None)

class gluontoolsPluginManager(plugin=None defaults)Bases object

Plugin Manager is similar to a storage object but it is a single level singleton This means that multiple instanceswithin the same thread share the same attributes Its constructor is also special The first argument is the nameof the plugin you are defining The named arguments are parameters needed by the plugin with default valuesIf the parameters were previous defined the old values are used

Example

in some general configuration file

plugins = PluginManager()pluginsmeparam1=3

within the plugin model

_ = PluginManager(meparam1=5param2=6param3=7)

where the plugin is used

gtgtgt print pluginsmeparam13gtgtgt print pluginsmeparam26gtgtgt pluginsmeparam3 = 8gtgtgt print pluginsmeparam38

Here are some tests

gtgtgt a=PluginManager()gtgtgt ax=6gtgtgt b=PluginManager(check)gtgtgt print bx6gtgtgt b=PluginManager() reset settingsgtgtgt print bxltStorage gtgtgtgt bx=7gtgtgt print ax7gtgtgt ayz=8gtgtgt print byz8

(continues on next page)

136 Chapter 34 tools Module

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt test_thread_separation()5gtgtgt plugins=PluginManager(medb=mydb)gtgtgt print pluginsmedbmydbgtgtgt print me in pluginsTruegtgtgt print pluginsmeinstalledTrue

instances =

keys()

gluontoolsfetch(url data=None headers=None cookie= user_agent=rsquoMozilla50rsquo)

gluontoolsgeocode(address)

gluontoolsreverse_geocode(lat lng lang=None)Try to get an approximate address for a given latitude longitude

gluontoolsprettydate(d T=ltfunction ltlambdagtgt utc=False)

341 Auth Mail PluginManager and various utilities 137

web2py Documentation Release 2146-stable

138 Chapter 34 tools Module

CHAPTER 35

utf8 Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)Created by Vladyslav Kozlovskyy (Ukraine) ltdbdevelopcopygmailcomgtfor Web2py project

351 Utilities and class for UTF8 strings managing

class gluonutf8Utf8Bases str

Class for utf8 string storing and manipulations

The base presupposition of this class usage is ldquoALL strings in the application are either of utf-8 or unicodetype even when simple str type is used UTF-8 is only a ldquopackedrdquo version of unicode so Utf-8 and unicodestrings are interchangeablerdquo

CAUTION This class is slower than strunicode Do NOT use it inside intensive loops Simply decode string(s)to unicode before loop and encode it back to utf-8 string(s) after intensive calculation

You can see the benefit of this class in doctests() below

capitalize()rarr stringReturn a copy of the string S with only its first character capitalized

center(width[ fillchar ])rarr stringReturn S centered in a string of length width Padding is done using the specified fill character (default isa space)

count(sub[ start[ end ]])rarr intReturn the number of non-overlapping occurrences of substring sub in string S[startend] Optional argu-ments start and end are interpreted as in slice notation

139

web2py Documentation Release 2146-stable

decode([encoding[ errors]])rarr objectDecodes S using the codec registered for encoding encoding defaults to the default encoding errors maybe given to set a different error handling scheme Default is lsquostrictrsquo meaning that encoding errors raise aUnicodeDecodeError Other possible values are lsquoignorersquo and lsquoreplacersquo as well as any other name registeredwith codecsregister_error that is able to handle UnicodeDecodeErrors

encode([encoding[ errors]])rarr objectEncodes S using the codec registered for encoding encoding defaults to the default encoding errors maybe given to set a different error handling scheme Default is lsquostrictrsquo meaning that encoding errors raise aUnicodeEncodeError Other possible values are lsquoignorersquo lsquoreplacersquo and lsquoxmlcharrefreplacersquo as well as anyother name registered with codecsregister_error that is able to handle UnicodeEncodeErrors

endswith(suffix[ start[ end ]])rarr boolReturn True if S ends with the specified suffix False otherwise With optional start test S beginning atthat position With optional end stop comparing S at that position suffix can also be a tuple of strings totry

expandtabs([tabsize])rarr stringReturn a copy of S where all tab characters are expanded using spaces If tabsize is not given a tab size of8 characters is assumed

find(sub[ start[ end ]])rarr intReturn the lowest index in S where substring sub is found such that sub is contained within S[startend]Optional arguments start and end are interpreted as in slice notation

Return -1 on failure

format(args kwargs)rarr stringReturn a formatted version of S using substitutions from args and kwargs The substitutions are identifiedby braces (lsquolsquo and lsquorsquo)

index(sub[ start[ end ]])rarr intLike Sfind() but raise ValueError when the substring is not found

isalnum()rarr boolReturn True if all characters in S are alphanumeric and there is at least one character in S False otherwise

isalpha()rarr boolReturn True if all characters in S are alphabetic and there is at least one character in S False otherwise

isdigit()rarr boolReturn True if all characters in S are digits and there is at least one character in S False otherwise

islower()rarr boolReturn True if all cased characters in S are lowercase and there is at least one cased character in S Falseotherwise

isspace()rarr boolReturn True if all characters in S are whitespace and there is at least one character in S False otherwise

istitle()rarr boolReturn True if S is a titlecased string and there is at least one character in S ie uppercase characters mayonly follow uncased characters and lowercase characters only cased ones Return False otherwise

isupper()rarr boolReturn True if all cased characters in S are uppercase and there is at least one cased character in S Falseotherwise

join(iterable)rarr stringReturn a string which is the concatenation of the strings in the iterable The separator between elements isS

140 Chapter 35 utf8 Module

web2py Documentation Release 2146-stable

ljust(width[ fillchar ])rarr stringReturn S left-justified in a string of length width Padding is done using the specified fill character (defaultis a space)

lower()rarr stringReturn a copy of the string S converted to lowercase

lstrip([chars])rarr string or unicodeReturn a copy of the string S with leading whitespace removed If chars is given and not None removecharacters in chars instead If chars is unicode S will be converted to unicode before stripping

partition(sep) -gt (head sep tail)Search for the separator sep in S and return the part before it the separator itself and the part after it Ifthe separator is not found return S and two empty strings

replace(old new[ count ])rarr stringReturn a copy of string S with all occurrences of substring old replaced by new If the optional argumentcount is given only the first count occurrences are replaced

rfind(sub[ start[ end ]])rarr intReturn the highest index in S where substring sub is found such that sub is contained within S[startend]Optional arguments start and end are interpreted as in slice notation

Return -1 on failure

rindex(sub[ start[ end ]])rarr intLike Srfind() but raise ValueError when the substring is not found

rjust(width[ fillchar ])rarr stringReturn S right-justified in a string of length width Padding is done using the specified fill character (defaultis a space)

rpartition(sep) -gt (head sep tail)Search for the separator sep in S starting at the end of S and return the part before it the separator itselfand the part after it If the separator is not found return two empty strings and S

rsplit([sep[ maxsplit ]])rarr list of stringsReturn a list of the words in the string S using sep as the delimiter string starting at the end of the stringand working to the front If maxsplit is given at most maxsplit splits are done If sep is not specified or isNone any whitespace string is a separator

rstrip([chars])rarr string or unicodeReturn a copy of the string S with trailing whitespace removed If chars is given and not None removecharacters in chars instead If chars is unicode S will be converted to unicode before stripping

split([sep[ maxsplit ]])rarr list of stringsReturn a list of the words in the string S using sep as the delimiter string If maxsplit is given at mostmaxsplit splits are done If sep is not specified or is None any whitespace string is a separator and emptystrings are removed from the result

splitlines(keepends=False)rarr list of stringsReturn a list of the lines in S breaking at line boundaries Line breaks are not included in the resulting listunless keepends is given and true

startswith(prefix[ start[ end ]])rarr boolReturn True if S starts with the specified prefix False otherwise With optional start test S beginning atthat position With optional end stop comparing S at that position prefix can also be a tuple of strings totry

strip([chars])rarr string or unicodeReturn a copy of the string S with leading and trailing whitespace removed If chars is given and not None

351 Utilities and class for UTF8 strings managing 141

web2py Documentation Release 2146-stable

remove characters in chars instead If chars is unicode S will be converted to unicode before stripping

swapcase()rarr stringReturn a copy of the string S with uppercase characters converted to lowercase and vice versa

title()rarr stringReturn a titlecased version of S ie words start with uppercase characters all remaining cased charactershave lowercase

translate(table[ deletechars])rarr stringReturn a copy of the string S where all characters occurring in the optional argument deletechars areremoved and the remaining characters have been mapped through the given translation table which mustbe a string of length 256 or None If the table argument is None no translation is applied and the operationsimply removes the characters in deletechars

upper()rarr stringReturn a copy of the string S converted to uppercase

zfill(width)rarr stringPad a numeric string S with zeros on the left to fill a field of the specified width The string S is nevertruncated

142 Chapter 35 utf8 Module

CHAPTER 36

utils Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

361 This file specifically includes utilities for security

gluonutilsAES_new(key IV=None)Returns an AES cipher object and random IV if None specified

gluonutilscompare(a b)Compares two strings and not vulnerable to timing attacks

gluonutilsfast_urandom16(urandom=[] locker=lt_RLock owner=None count=0gt)This is 4x faster than calling osurandom(16) and prevents the ldquotoo many files openrdquo issue with concurrent accessto osurandom()

gluonutilsget_callable_argspec(fn)

gluonutilsget_digest(value)Returns a hashlib digest algorithm from a string

gluonutilsgetipaddrinfo(host)Filter out non-IP and bad IP addresses from getaddrinfo

gluonutilsinitialize_urandom()This function and the web2py_uuid follow from the following discussionhttpgroupsgooglecomgroupweb2py-developersbrowse_threadthread7fd5789a7da3f09

At startup web2py compute a unique ID that identifies the machine by adding uuidgetnode() + int(timetime() 1e3)

This is a 48-bit number It converts the number into 16 8-bit tokens It uses this value to initialize the entropysource (lsquodevurandomrsquo) and to seed random

143

web2py Documentation Release 2146-stable

If osrandom() is not supported it falls back to using random and issues a warning

gluonutilsis_loopback_ip_address(ip=None addrinfo=None)Determines whether the address appears to be a loopback address This assumes that the IP is valid

gluonutilsis_valid_ip_address(address)

Examples

Better than a thousand words

gtgtgt is_valid_ip_address(1270)Falsegtgtgt is_valid_ip_address(127001)Truegtgtgt is_valid_ip_address(20016601)True

gluonutilsmd5_hash(text)Generates a md5 hash with the given text

gluonutilspad(s n=32 padchar=rsquo rsquo)

gluonutilspbkdf2_hex(data salt iterations=1000 keylen=24 hashfunc=None)

gluonutilssecure_dumps(data encryption_key hash_key=None compression_level=None)

gluonutilssecure_loads(data encryption_key hash_key=None compression_level=None)

gluonutilssimple_hash(text key=rdquo salt=rdquo digest_alg=rsquomd5rsquo)Generates hash with the given text using the specified digest hashing algorithm

gluonutilsweb2py_uuid(ctokens=(12807810588179607998L 787762416516532974))This function follows from the following discussion httpgroupsgooglecomgroupweb2py-developersbrowse_threadthread7fd5789a7da3f09

It works like uuiduuid4 except that tries to use osurandom() if possible and it XORs the output with the tokensuniquely associated with this machine

144 Chapter 36 utils Module

CHAPTER 37

validators Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)Thanks to ga2arch for help with IS_IN_DB and IS_NOT_IN_DB on GAE

371 Validators

class gluonvalidatorsANY_OF(subs)Bases gluonvalidatorsValidator

Tests if any of the validators in a list returns successfully

gtgtgt ANY_OF([IS_EMAIL()IS_ALPHANUMERIC()])(abco)(abco None)gtgtgt ANY_OF([IS_EMAIL()IS_ALPHANUMERIC()])(abco)(abco None)gtgtgt ANY_OF([IS_EMAIL()IS_ALPHANUMERIC()])(abco)(abco enter only letters numbers and underscore)gtgtgt ANY_OF([IS_ALPHANUMERIC()IS_EMAIL()])(abco)(abco enter a valid email address)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

class gluonvalidatorsCLEANUP(regex=None)Bases gluonvalidatorsValidator

Examples

Use as

145

web2py Documentation Release 2146-stable

INPUT(_type=text _name=name requires=CLEANUP())

removes special characters on validation

REGEX_CLEANUP = lt_sreSRE_Pattern objectgt

class gluonvalidatorsCRYPT(key=None digest_alg=rsquopbkdf2(1000 20 sha512)rsquo min_length=0error_message=rsquoToo shortrsquo salt=True max_length=1024)

Bases object

Examples

Use as

INPUT(_type=text _name=name requires=CRYPT())

encodes the value on validation with a digest

If no arguments are provided CRYPT uses the MD5 algorithm If the key argument is provided the HMAC+MD5algorithm is used If the digest_alg is specified this is used to replace the MD5 with for example SHA512 Thedigest_alg can be the name of a hashlib algorithm as a string or the algorithm itself

min_length is the minimal password length (default 4) - IS_STRONG for serious security error_message is themessage if password is too short

Notice that an empty password is accepted but invalid It will not allow login back Stores junk as hashedpassword

Specify an algorithm or by default we will use sha512

Typical available algorithms md5 sha1 sha224 sha256 sha384 sha512

If salt it hashes a password with a salt If salt is True this method will automatically generate one Either caseit returns an encrypted password string in the following format

ltalgorithmgt$ltsaltgt$lthashgt

Important hashed password is returned as a LazyCrypt object and computed only if needed The LasyCryptobject also knows how to compare itself with an existing salted password

Supports standard algorithms

gtgtgt for alg in (md5sha1sha256sha384sha512) print str(CRYPT(digest_alg=algsalt=True)(test)[0])md5$$sha1$$sha256$$sha384$$sha512$$

The syntax is always alg$salt$hash

Supports for pbkdf2

gtgtgt alg = pbkdf2(100020sha512)gtgtgt print str(CRYPT(digest_alg=algsalt=True)(test)[0])pbkdf2(100020sha512)$$

An optional hmac_key can be specified and it is used as salt prefix

146 Chapter 37 validators Module

web2py Documentation Release 2146-stable

gtgtgt a = str(CRYPT(digest_alg=md5key=mykeysalt=True)(test)[0])gtgtgt print amd5$$

Even if the algorithm changes the hash can still be validated

gtgtgt CRYPT(digest_alg=sha1key=mykeysalt=True)(test)[0] == aTrue

If no salt is specified CRYPT can guess the algorithms from length

gtgtgt a = str(CRYPT(digest_alg=sha1salt=False)(test)[0])gtgtgt asha1$$a94a8fe5ccb19ba61c4c0873d391e987982fbbd3gtgtgt CRYPT(digest_alg=sha1salt=False)(test)[0] == aTruegtgtgt CRYPT(digest_alg=sha1salt=False)(test)[0] == a[6]Truegtgtgt CRYPT(digest_alg=md5salt=False)(test)[0] == aTruegtgtgt CRYPT(digest_alg=md5salt=False)(test)[0] == a[6]True

class gluonvalidatorsIS_ALPHANUMERIC(error_message=rsquoEnter only letters numbers andunderscorersquo)

Bases gluonvalidatorsIS_MATCH

Example

Used as

INPUT(_type=text _name=name requires=IS_ALPHANUMERIC())

gtgtgt IS_ALPHANUMERIC()(1)(1 None)gtgtgt IS_ALPHANUMERIC()()( None)gtgtgt IS_ALPHANUMERIC()(A_a)(A_a None)gtgtgt IS_ALPHANUMERIC()()( enter only letters numbers and underscore)

class gluonvalidatorsIS_DATE_IN_RANGE(minimum=None maximum=None format=rsquoY-m-drsquo error_message=None)

Bases gluonvalidatorsIS_DATE

Examples

Use as

gtgtgt v = IS_DATE_IN_RANGE(minimum=datetimedate(200811)rarr˓ maximum=datetimedate(20091231)rarr˓ format=mdYerror_message=Oops)

(continues on next page)

371 Validators 147

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt v(03032008)(datetimedate(2008 3 3) None)

gtgtgt v(03032010)(03032010 oops)

gtgtgt v(datetimedate(200833))(datetimedate(2008 3 3) None)

gtgtgt v(datetimedate(201033))(datetimedate(2010 3 3) oops)

class gluonvalidatorsIS_DATE(format=rsquoY-m-drsquo error_message=rsquoEnter date as (for-mat)srsquo)

Bases gluonvalidatorsValidator

Examples

Use as

INPUT(_type=text _name=name requires=IS_DATE())

date has to be in the ISO8960 format YYYY-MM-DD

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

class gluonvalidatorsIS_DATETIME_IN_RANGE(minimum=None maximum=Noneformat=rsquoY-m-d HMSrsquo er-ror_message=None timezone=None)

Bases gluonvalidatorsIS_DATETIME

Examples

Use as

gtgtgt v = IS_DATETIME_IN_RANGE( minimum=datetimerarr˓datetime(2008111220) maximum=datetimerarr˓datetime(200912311220) format=mdY HMrarr˓error_message=Oops)gtgtgt v(03032008 1240)(datetimedatetime(2008 3 3 12 40) None)

gtgtgt v(03032010 1034)(03032010 1034 oops)

gtgtgt v(datetimedatetime(20083300))(datetimedatetime(2008 3 3 0 0) None)

gtgtgt v(datetimedatetime(20103300))(datetimedatetime(2010 3 3 0 0) oops)

148 Chapter 37 validators Module

web2py Documentation Release 2146-stable

class gluonvalidatorsIS_DATETIME(format=rsquoY-m-d HMSrsquo er-ror_message=rsquoEnter date and time as (format)srsquotimezone=None)

Bases gluonvalidatorsValidator

Examples

Use as

INPUT(_type=text _name=name requires=IS_DATETIME())

datetime has to be in the ISO8960 format YYYY-MM-DD hhmmss timezome must be None or apytztimezone(ldquoAmericaChicagordquo) object

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

isodatetime = Y-m-d HMS

static nice(format)

class gluonvalidatorsIS_DECIMAL_IN_RANGE(minimum=None maximum=None er-ror_message=None dot=rsquorsquo)

Bases gluonvalidatorsValidator

Determines that the argument is (or can be represented as) a Python Decimal and that it falls within the specifiedinclusive range The comparison is made with Python Decimal arithmetic

The minimum and maximum limits can be None meaning no lower or upper limit respectively

Example

Used as

INPUT(_type=text _name=name requires=IS_DECIMAL_IN_RANGE(0 10))

gtgtgt IS_DECIMAL_IN_RANGE(15)(4)(Decimal(4) None)gtgtgt IS_DECIMAL_IN_RANGE(15)(4)(Decimal(4) None)gtgtgt IS_DECIMAL_IN_RANGE(15)(1)(Decimal(1) None)gtgtgt IS_DECIMAL_IN_RANGE(15)(525)(525 enter a number between 1 and 5)gtgtgt IS_DECIMAL_IN_RANGE(5256)(525)(Decimal(525) None)gtgtgt IS_DECIMAL_IN_RANGE(5256)(525)(Decimal(525) None)gtgtgt IS_DECIMAL_IN_RANGE(15)(60)(60 enter a number between 1 and 5)gtgtgt IS_DECIMAL_IN_RANGE(15)(35)(Decimal(35) None)gtgtgt IS_DECIMAL_IN_RANGE(1555)(35)(Decimal(35) None)gtgtgt IS_DECIMAL_IN_RANGE(1555)(65)(65 enter a number between 15 and 55)

(continues on next page)

371 Validators 149

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_DECIMAL_IN_RANGE(15None)(65)(Decimal(65) None)gtgtgt IS_DECIMAL_IN_RANGE(15None)(05)(05 enter a number greater than or equal to 15)gtgtgt IS_DECIMAL_IN_RANGE(None55)(45)(Decimal(45) None)gtgtgt IS_DECIMAL_IN_RANGE(None55)(65)(65 enter a number less than or equal to 55)gtgtgt IS_DECIMAL_IN_RANGE()(65)(Decimal(65) None)gtgtgt IS_DECIMAL_IN_RANGE(099)(123123)(123123 enter a number between 0 and 99)gtgtgt IS_DECIMAL_IN_RANGE(099)(123123)(123123 enter a number between 0 and 99)gtgtgt IS_DECIMAL_IN_RANGE(099)(1234)(Decimal(1234) None)gtgtgt IS_DECIMAL_IN_RANGE()(abc)(abc enter a number)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

class gluonvalidatorsIS_EMAIL(banned=None forced=None error_message=rsquoEnter a validemail addressrsquo)

Bases gluonvalidatorsValidator

Checks if fieldrsquos value is a valid email address Can be set to disallow or force addresses from certain domain(s)

Email regex adapted from httphaackedcomarchive20070821i-knew-how-to-validate-an-email-address-until-iaspx generally following the RFCs except that we disallow quoted strings and permit underscores and leadingnumerics in subdomain labels

Parameters

bull banned ndash regex text for disallowed address domains

bull forced ndash regex text for required address domains

Both arguments can also be custom objects with a match(value) method

Example

Check for valid email address

INPUT(_type=text _name=namerequires=IS_EMAIL())

Check for valid email address that canrsquot be from a com domain

INPUT(_type=text _name=namerequires=IS_EMAIL(banned=^com(|)$))

Check for valid email address that must be from a edu domain

INPUT(_type=text _name=namerequires=IS_EMAIL(forced=^edu(|)$))

(continues on next page)

150 Chapter 37 validators Module

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_EMAIL()(abcom)(abcom None)gtgtgt IS_EMAIL()(abcdefcom)(abcdefcom None)gtgtgt IS_EMAIL()(abc3defcom)(abc3defcom None)gtgtgt IS_EMAIL()(abcdefus)(abcdefus None)gtgtgt IS_EMAIL()(abcd_-fus)(abcd_-fus None)gtgtgt IS_EMAIL()(defcom) missing name(defcom enter a valid email address)gtgtgt IS_EMAIL()(abcdefcom) quoted name(abcdefcom enter a valid email address)gtgtgt IS_EMAIL()(abc+defcom) no (abc+defcom enter a valid email address)gtgtgt IS_EMAIL()(abcdefx) one-char TLD(abcdefx enter a valid email address)gtgtgt IS_EMAIL()(abcdef12) numeric TLD(abcdef12 enter a valid email address)gtgtgt IS_EMAIL()(abcdefcom) double-dot in domain(abcdefcom enter a valid email address)gtgtgt IS_EMAIL()(abcdefcom) dot starts domain(abcdefcom enter a valid email address)gtgtgt IS_EMAIL()(abcdefc_m) underscore in TLD(abcdefc_m enter a valid email address)gtgtgt IS_EMAIL()(NotAnEmail) missing (NotAnEmail enter a valid email address)gtgtgt IS_EMAIL()(abcNotAnEmail) missing TLD(abcNotAnEmail enter a valid email address)gtgtgt IS_EMAIL()(customerdepartmentexamplecom)(customerdepartmentexamplecom None)gtgtgt IS_EMAIL()($A12345examplecom)($A12345examplecom None)gtgtgt IS_EMAIL()(defxyzabcexamplecom)(defxyzabcexamplecom None)gtgtgt IS_EMAIL()(_YosemiteSamexamplecom)(_YosemiteSamexamplecom None)gtgtgt IS_EMAIL()(~examplecom)(~examplecom None)gtgtgt IS_EMAIL()(woolyexamplecom) dot starts name(woolyexamplecom enter a valid email address)gtgtgt IS_EMAIL()(woolyexamplecom) adjacent dots in name(woolyexamplecom enter a valid email address)gtgtgt IS_EMAIL()(pootietangexamplecom) dot ends name(pootietangexamplecom enter a valid email address)gtgtgt IS_EMAIL()(examplecom) name is bare dot(examplecom enter a valid email address)gtgtgt IS_EMAIL()(ImaFoolexamplecom)(ImaFoolexamplecom None)gtgtgt IS_EMAIL()(Ima Foolexamplecom) space in name(Ima Foolexamplecom enter a valid email address)gtgtgt IS_EMAIL()(localguylocalhost) localhost as domain(localguylocalhost None)

regex = lt_sreSRE_Pattern object at 0x2e0e160gt

371 Validators 151

web2py Documentation Release 2146-stable

regex_proposed_but_failed = lt_sreSRE_Pattern object at 0x2e100d0gt

class gluonvalidatorsIS_LIST_OF_EMAILS(error_message=rsquoInvalid emails srsquo)Bases object

Example

Used as

Field(emailsliststringwidget=SQLFORMwidgetstextwidgetrequires=IS_LIST_OF_EMAILS()represent=lambda vr SPAN([A(x_href=mailto+x)

rarr˓for x in (v or [])]))

formatter(value row=None)

split_emails = lt_sreSRE_Pattern objectgt

class gluonvalidatorsIS_EMPTY_OR(other null=None empty_regex=None)Bases gluonvalidatorsValidator

Dummy class for testing IS_EMPTY_OR

gtgtgt IS_EMPTY_OR(IS_EMAIL())(abcdefcom)(abcdefcom None)gtgtgt IS_EMPTY_OR(IS_EMAIL())( )(None None)gtgtgt IS_EMPTY_OR(IS_EMAIL() null=abc)( )(abc None)gtgtgt IS_EMPTY_OR(IS_EMAIL() null=abc empty_regex=def)(def)(abc None)gtgtgt IS_EMPTY_OR(IS_EMAIL())(abc)(abc enter a valid email address)gtgtgt IS_EMPTY_OR(IS_EMAIL())( abc )(abc enter a valid email address)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

set_self_id(id)

class gluonvalidatorsIS_EXPR(expression error_message=rsquoInvalid expressionrsquo environ-ment=None)

Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=namerequires=IS_EXPR(5 lt int(value) lt 10))

The argument of IS_EXPR must be python condition

152 Chapter 37 validators Module

web2py Documentation Release 2146-stable

gtgtgt IS_EXPR(int(value) lt 2)(1)(1 None)

gtgtgt IS_EXPR(int(value) lt 2)(2)(2 invalid expression)

class gluonvalidatorsIS_FLOAT_IN_RANGE(minimum=None maximum=None er-ror_message=None dot=rsquorsquo)

Bases gluonvalidatorsValidator

Determines that the argument is (or can be represented as) a float and that it falls within the specified inclusiverange The comparison is made with native arithmetic

The minimum and maximum limits can be None meaning no lower or upper limit respectively

Example

Used as

INPUT(_type=text _name=name requires=IS_FLOAT_IN_RANGE(0 10))

gtgtgt IS_FLOAT_IN_RANGE(15)(4)(40 None)gtgtgt IS_FLOAT_IN_RANGE(15)(4)(40 None)gtgtgt IS_FLOAT_IN_RANGE(15)(1)(10 None)gtgtgt IS_FLOAT_IN_RANGE(15)(525)(525 enter a number between 1 and 5)gtgtgt IS_FLOAT_IN_RANGE(15)(60)(60 enter a number between 1 and 5)gtgtgt IS_FLOAT_IN_RANGE(15)(35)(35 None)gtgtgt IS_FLOAT_IN_RANGE(1None)(35)(35 None)gtgtgt IS_FLOAT_IN_RANGE(None5)(35)(35 None)gtgtgt IS_FLOAT_IN_RANGE(1None)(05)(05 enter a number greater than or equal to 1)gtgtgt IS_FLOAT_IN_RANGE(None5)(65)(65 enter a number less than or equal to 5)gtgtgt IS_FLOAT_IN_RANGE()(65)(65 None)gtgtgt IS_FLOAT_IN_RANGE()(abc)(abc enter a number)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

class gluonvalidatorsIS_IMAGE(extensions=(rsquobmprsquo rsquogifrsquo rsquojpegrsquo rsquopngrsquo) maxsize=(1000010000) minsize=(0 0) error_message=rsquoInvalid imagersquo)

Bases gluonvalidatorsValidator

Checks if file uploaded through file input was saved in one of selected image formats and has dimensions (widthand height) within given boundaries

371 Validators 153

web2py Documentation Release 2146-stable

Does not check for maximum file size (use IS_LENGTH for that) Returns validation failure if no data wasuploaded

Supported file formats BMP GIF JPEG PNG

Code parts taken from httpmailpythonorgpipermailpython-list2007-June617126html

Parameters

bull extensions ndash iterable containing allowed lowercase image file extensions

bull extension of uploaded file counts as jpeg) ((jpg) ndash

bull maxsize ndash iterable containing maximum width and height of the image

bull minsize ndash iterable containing minimum width and height of the image

Use (-1 -1) as minsize to pass image size check

Examples

Check if uploaded file is in any of supported image formats

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_IMAGE())

Check if uploaded file is either JPEG or PNG

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_IMAGE(extensions=(lsquojpegrsquo lsquopngrsquo)))

Check if uploaded file is PNG with maximum size of 200x200 pixels

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_IMAGE(extensions=(lsquopngrsquo) maxsize=(200200)))

class gluonvalidatorsIS_IN_DB(dbset field label=None error_message=rsquoValue not indatabasersquo orderby=None groupby=None distinct=Nonecache=None multiple=False zero=rdquo sort=False_and=None left=None delimiter=None auto_add=False)

Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=namerequires=IS_IN_DB(db dbmytablemyfield zero=))

used for reference fields rendered as a dropbox

build_set()

maybe_add(table fieldname value)

options(zero=True)

set_self_id(id)

class gluonvalidatorsIS_IN_SET(theset labels=None error_message=rsquoValue not allowedrsquomultiple=False zero=rdquo sort=False)

Bases gluonvalidatorsValidator

154 Chapter 37 validators Module

web2py Documentation Release 2146-stable

Example

Used as

INPUT(_type=text _name=namerequires=IS_IN_SET([max john]zero=))

The argument of IS_IN_SET must be a list or set

gtgtgt IS_IN_SET([max john])(max)(max None)gtgtgt IS_IN_SET([max john])(massimo)(massimo value not allowed)gtgtgt IS_IN_SET([max john] multiple=True)((max john))((max john) None)gtgtgt IS_IN_SET([max john] multiple=True)((bill john))((bill john) value not allowed)gtgtgt IS_IN_SET((id1id2) [first labelsecond label])(id1) Traditionalrarr˓way(id1 None)gtgtgt IS_IN_SET(id1first label id2second label)(id1)(id1 None)gtgtgt import itertoolsgtgtgt IS_IN_SET(itertoolschain([135][246]))(1)(1 None)gtgtgt IS_IN_SET([(id1first label) (id2second label)])(id1) Redundantrarr˓way(id1 None)

options(zero=True)

class gluonvalidatorsIS_INT_IN_RANGE(minimum=None maximum=None er-ror_message=None)

Bases gluonvalidatorsValidator

Determines that the argument is (or can be represented as) an int and that it falls within the specified range Therange is interpreted in the Pythonic way so the test is min lt= value lt max

The minimum and maximum limits can be None meaning no lower or upper limit respectively

Example

Used as

INPUT(_type=text _name=name requires=IS_INT_IN_RANGE(0 10))

gtgtgt IS_INT_IN_RANGE(15)(4)(4 None)gtgtgt IS_INT_IN_RANGE(15)(4)(4 None)gtgtgt IS_INT_IN_RANGE(15)(1)(1 None)gtgtgt IS_INT_IN_RANGE(15)(5)(5 enter an integer between 1 and 4)gtgtgt IS_INT_IN_RANGE(15)(5)(5 enter an integer between 1 and 4)gtgtgt IS_INT_IN_RANGE(15)(35)

(continues on next page)

371 Validators 155

web2py Documentation Release 2146-stable

(continued from previous page)

(35 enter an integer between 1 and 4)gtgtgt IS_INT_IN_RANGE(None5)(4)(4 None)gtgtgt IS_INT_IN_RANGE(None5)(6)(6 enter an integer less than or equal to 4)gtgtgt IS_INT_IN_RANGE(1None)(4)(4 None)gtgtgt IS_INT_IN_RANGE(1None)(0)(0 enter an integer greater than or equal to 1)gtgtgt IS_INT_IN_RANGE()(6)(6 None)gtgtgt IS_INT_IN_RANGE()(abc)(abc enter an integer)

class gluonvalidatorsIS_IPV4(minip=rsquo0000rsquo maxip=rsquo255255255255rsquo invert=Falseis_localhost=None is_private=None is_automatic=Noneerror_message=rsquoEnter valid IPv4 addressrsquo)

Bases gluonvalidatorsValidator

Checks if fieldrsquos value is an IP version 4 address in decimal form Can be set to force addresses from certainrange

IPv4 regex taken from httpregexlibcomREDetailsaspxregexp_id=1411

Parameters

bull minip ndash lowest allowed address accepts

ndash str eg 19216801

ndash list or tuple of octets eg [192 168 0 1]

bull maxip ndash highest allowed address same as above

bull invert ndash True to allow addresses only from outside of given range note that range bound-aries are not matched this way

bull is_localhost ndash localhost address treatment

ndash None (default) indifferent

ndash True (enforce) query address must match localhost address (127001)

ndash False (forbid) query address must not match localhost address

bull is_private ndash same as above except that query address is checked against two addressranges 1721600 - 17231255255 and 19216800 - 192168255255

bull is_automatic ndash same as above except that query address is checked against one addressrange 16925400 - 169254255255

Minip and maxip may also be lists or tuples of addresses in all above forms (str int list tuple) allowing setupof multiple address ranges

minip = (minip1 minip2 minipN)| | || | |

maxip = (maxip1 maxip2 maxipN)

Longer iterable will be truncated to match length of shorter one

156 Chapter 37 validators Module

web2py Documentation Release 2146-stable

Examples

Check for valid IPv4 address

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV4())

Check for valid IPv4 address belonging to specific range

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV4(minip=lsquo10020000rsquomaxip=lsquo100200255255rsquo))

Check for valid IPv4 address belonging to either 10011000 - 100110255255 or 2005000 - 200500255address range

INPUT(_type=rsquotextrsquo _name=rsquonamersquo

requires=IS_IPV4(minip=(lsquo10011000rsquo lsquo2005000rsquo) maxip=(lsquo100110255255rsquolsquo200500255rsquo)))

Check for valid IPv4 address belonging to private address space

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV4(is_private=True))

Check for valid IPv4 address that is not a localhost address

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV4(is_localhost=False))

gtgtgt IS_IPV4()(1234)(1234 None)gtgtgt IS_IPV4()(255255255255)(255255255255 None)gtgtgt IS_IPV4()(1234 )(1234 enter valid IPv4 address)gtgtgt IS_IPV4()(12345)(12345 enter valid IPv4 address)gtgtgt IS_IPV4()(123123)(123123 enter valid IPv4 address)gtgtgt IS_IPV4()(1111234)(1111234 enter valid IPv4 address)gtgtgt IS_IPV4()(0111234)(0111234 enter valid IPv4 address)gtgtgt IS_IPV4()(256234)(256234 enter valid IPv4 address)gtgtgt IS_IPV4()(300234)(300234 enter valid IPv4 address)gtgtgt IS_IPV4(minip=1234 maxip=1234)(1234)(1234 None)gtgtgt IS_IPV4(minip=1235 maxip=1239 error_message=Bad ip)(1rarr˓234)(1234 bad ip)gtgtgt IS_IPV4(maxip=1234 invert=True)(127001)(127001 None)gtgtgt IS_IPV4(maxip=1234 invert=True)(1234)(1234 enter valid IPv4 address)gtgtgt IS_IPV4(is_localhost=True)(127001)(127001 None)gtgtgt IS_IPV4(is_localhost=True)(1234)(1234 enter valid IPv4 address)gtgtgt IS_IPV4(is_localhost=False)(127001)(127001 enter valid IPv4 address)

(continues on next page)

371 Validators 157

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_IPV4(maxip=100000 is_localhost=True)(127001)(127001 enter valid IPv4 address)

automatic = (2851995648L 2852061183L)

localhost = 2130706433

numbers = (16777216 65536 256 1)

private = ((2886729728L 2886795263L) (3232235520L 3232301055L))

regex = lt_sreSRE_Pattern object at 0x2e26320gt

class gluonvalidatorsIS_IPV6(is_private=None is_link_local=None is_reserved=Noneis_multicast=None is_routeable=None is_6to4=Noneis_teredo=None subnets=None error_message=rsquoEnter validIPv6 addressrsquo)

Bases gluonvalidatorsValidator

Checks if fieldrsquos value is an IP version 6 address First attempts to use the ipaddress library and falls back tocontribipaddrpy from Google (httpscodegooglecompipaddr-py)

Parameters

bull is_private ndash None (default) indifferent True (enforce) address must be in fc007range False (forbid) address must NOT be in fc007 range

bull is_link_local ndash Same as above but uses fe8010 range

bull is_reserved ndash Same as above but uses IETF reserved range

bull is_mulicast ndash Same as above but uses ff008 range

bull is_routeable ndash Similar to above but enforces not private link_local reserved or multi-cast

bull is_6to4 ndash Same as above but uses 200216 range

bull is_teredo ndash Same as above but uses 200132 range

bull subnets ndash value must be a member of at least one from list of subnets

Examples

Check for valid IPv6 address

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV6())

Check for valid IPv6 address is a link_local address

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV6(is_link_local=True))

Check for valid IPv6 address that is Internet routeable

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV6(is_routeable=True))

Check for valid IPv6 address in specified subnet

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV6(subnets=[lsquo200132rsquo])

158 Chapter 37 validators Module

web2py Documentation Release 2146-stable

gtgtgt IS_IPV6()(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPV6()(19216811)(19216811 enter valid IPv6 address)gtgtgt IS_IPV6(error_message=Bad ip)(19216811)(19216811 bad ip)gtgtgt IS_IPV6(is_link_local=True)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPV6(is_link_local=False)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(is_link_local=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(is_multicast=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(is_multicast=True)(ff00126c8ffafe22b3af)(ff00126c8ffafe22b3af None)gtgtgt IS_IPV6(is_routeable=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af None)gtgtgt IS_IPV6(is_routeable=True)(ff00126c8ffafe22b3af)(ff00126c8ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(subnets=200132)(20018ffafe22b3af)(20018ffafe22b3af None)gtgtgt IS_IPV6(subnets=fb008)(20018ffafe22b3af)(20018ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(subnets=[fc008200132])(20018ffafe22b3af)(20018ffafe22b3af None)gtgtgt IS_IPV6(subnets=invalidsubnet)(20018ffafe22b3af)(20018ffafe22b3af invalid subnet provided)

class gluonvalidatorsIS_IPADDRESS(minip=rsquo0000rsquo maxip=rsquo255255255255rsquo in-vert=False is_localhost=None is_private=Noneis_automatic=None is_ipv4=None is_link_local=Noneis_reserved=None is_multicast=Noneis_routeable=None is_6to4=None is_teredo=Nonesubnets=None is_ipv6=None error_message=rsquoEntervalid IP addressrsquo)

Bases gluonvalidatorsValidator

Checks if fieldrsquos value is an IP Address (v4 or v6) Can be set to force addresses from within a specific rangeChecks are done with the correct IS_IPV4 and IS_IPV6 validators

Uses ipaddress library if found falls back to PEP-3144 ipaddrpy from Google (in contrib)

Parameters

bull minip ndash lowest allowed address accepts str eg 19216801 list or tuple of octets eg[192 168 0 1]

bull maxip ndash highest allowed address same as above

bull invert ndash True to allow addresses only from outside of given range note that range bound-aries are not matched this way

IPv4 specific arguments

bull is_localhost localhost address treatment

ndash None (default) indifferent

ndash True (enforce) query address must match localhost address (127001)

371 Validators 159

web2py Documentation Release 2146-stable

ndash False (forbid) query address must not match localhost address

bull is_private same as above except that query address is checked against two address ranges 1721600 -17231255255 and 19216800 - 192168255255

bull is_automatic same as above except that query address is checked against one address range 16925400- 169254255255

bull is_ipv4 either

ndash None (default) indifferent

ndash True (enforce) must be an IPv4 address

ndash False (forbid) must NOT be an IPv4 address

IPv6 specific arguments

bull is_link_local Same as above but uses fe8010 range

bull is_reserved Same as above but uses IETF reserved range

bull is_mulicast Same as above but uses ff008 range

bull is_routeable Similar to above but enforces not private link_local reserved or multicast

bull is_6to4 Same as above but uses 200216 range

bull is_teredo Same as above but uses 200132 range

bull subnets value must be a member of at least one from list of subnets

bull is_ipv6 either

ndash None (default) indifferent

ndash True (enforce) must be an IPv6 address

ndash False (forbid) must NOT be an IPv6 address

Minip and maxip may also be lists or tuples of addresses in all above forms (str int list tuple) allowing setupof multiple address ranges

minip = (minip1 minip2 minipN)| | || | |

maxip = (maxip1 maxip2 maxipN)

Longer iterable will be truncated to match length of shorter one

gtgtgt IS_IPADDRESS()(19216815)(19216815 None)gtgtgt IS_IPADDRESS(is_ipv6=False)(19216815)(19216815 None)gtgtgt IS_IPADDRESS()(255255255255)(255255255255 None)gtgtgt IS_IPADDRESS()(19216815 )(19216815 enter valid IP address)gtgtgt IS_IPADDRESS()(192168115)(192168115 enter valid IP address)gtgtgt IS_IPADDRESS()(123123)(123123 enter valid IP address)gtgtgt IS_IPADDRESS()(1111234)(1111234 enter valid IP address)gtgtgt IS_IPADDRESS()(0111234)

(continues on next page)

160 Chapter 37 validators Module

web2py Documentation Release 2146-stable

(continued from previous page)

(0111234 enter valid IP address)gtgtgt IS_IPADDRESS()(256234)(256234 enter valid IP address)gtgtgt IS_IPADDRESS()(300234)(300234 enter valid IP address)gtgtgt IS_IPADDRESS(minip=19216810 maxip=1921681255)(1921681100)(1921681100 None)gtgtgt IS_IPADDRESS(minip=1235 maxip=1239 error_message=Bad ip)(123rarr˓4)(1234 bad ip)gtgtgt IS_IPADDRESS(maxip=1234 invert=True)(127001)(127001 None)gtgtgt IS_IPADDRESS(maxip=19216814 invert=True)(19216814)(19216814 enter valid IP address)gtgtgt IS_IPADDRESS(is_localhost=True)(127001)(127001 None)gtgtgt IS_IPADDRESS(is_localhost=True)(192168110)(192168110 enter valid IP address)gtgtgt IS_IPADDRESS(is_localhost=False)(127001)(127001 enter valid IP address)gtgtgt IS_IPADDRESS(maxip=100000 is_localhost=True)(127001)(127001 enter valid IP address)

gtgtgt IS_IPADDRESS()(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPADDRESS(is_ipv4=False)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPADDRESS()(fe80126c8ffafe22b3af )(fe80126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_ipv4=True)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_ipv6=True)(19216811)(19216811 enter valid IP address)gtgtgt IS_IPADDRESS(is_ipv6=True error_message=Bad ip)(19216811)(19216811 bad ip)gtgtgt IS_IPADDRESS(is_link_local=True)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPADDRESS(is_link_local=False)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_link_local=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_multicast=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_multicast=True)(ff00126c8ffafe22b3af)(ff00126c8ffafe22b3af None)gtgtgt IS_IPADDRESS(is_routeable=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af None)gtgtgt IS_IPADDRESS(is_routeable=True)(ff00126c8ffafe22b3af)(ff00126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(subnets=200132)(20018ffafe22b3af)(20018ffafe22b3af None)gtgtgt IS_IPADDRESS(subnets=fb008)(20018ffafe22b3af)(20018ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(subnets=[fc008200132])(20018ffafe22b3af)(20018ffafe22b3af None)gtgtgt IS_IPADDRESS(subnets=invalidsubnet)(20018ffafe22b3af)(20018ffafe22b3af invalid subnet provided)

371 Validators 161

web2py Documentation Release 2146-stable

class gluonvalidatorsIS_LENGTH(maxsize=255 minsize=0 error_message=rsquoEnter from(min)g to (max)g charactersrsquo)

Bases gluonvalidatorsValidator

Checks if length of fieldrsquos value fits between given boundaries Works for both text and file inputs

Parameters

bull maxsize ndash maximum allowed length size

bull minsize ndash minimum allowed length size

Examples

Check if text string is shorter than 33 characters

INPUT(_type=text _name=name requires=IS_LENGTH(32))

Check if password string is longer than 5 characters

INPUT(_type=password _name=name requires=IS_LENGTH(minsize=6))

Check if uploaded file has size between 1KB and 1MB

INPUT(_type=file _name=name requires=IS_LENGTH(1048576 1024))

Other examples

gtgtgt IS_LENGTH()()( None)gtgtgt IS_LENGTH()(1234567890)(1234567890 None)gtgtgt IS_LENGTH(maxsize=5 minsize=0)(1234567890) too long(1234567890 enter from 0 to 5 characters)gtgtgt IS_LENGTH(maxsize=50 minsize=20)(1234567890) too short(1234567890 enter from 20 to 50 characters)

class gluonvalidatorsIS_LIST_OF(other=None minimum=0 maximum=100 er-ror_message=None)

Bases gluonvalidatorsValidator

class gluonvalidatorsIS_LOWERBases gluonvalidatorsValidator

Converts to lower case

gtgtgt IS_LOWER()(ABC)(abc None)gtgtgt IS_LOWER()(Ntilde)(xc3xb1 None)

class gluonvalidatorsIS_MATCH(expression error_message=rsquoInvalid expressionrsquo strict=Falsesearch=False extract=False is_unicode=False)

Bases gluonvalidatorsValidator

Example

Used as

162 Chapter 37 validators Module

web2py Documentation Release 2146-stable

INPUT(_type=text _name=name requires=IS_MATCH(+))

The argument of IS_MATCH is a regular expression

gtgtgt IS_MATCH(+)(hello)(hello None)

gtgtgt IS_MATCH(hell)(hello)(hello None)

gtgtgt IS_MATCH(hell strict=False)(hello)(hello None)

gtgtgt IS_MATCH(hello)(shello)(shello invalid expression)

gtgtgt IS_MATCH(hello search=True)(shello)(shello None)

gtgtgt IS_MATCH(hello search=True strict=False)(shellox)(shellox None)

gtgtgt IS_MATCH(hello search=True strict=False)(shellox)(shellox None)

gtgtgt IS_MATCH(+)()( invalid expression)

class gluonvalidatorsIS_EQUAL_TO(expression error_message=rsquoNo matchrsquo)Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=password)INPUT(_type=text _name=password2

requires=IS_EQUAL_TO(requestvarspassword))

The argument of IS_EQUAL_TO is a string

gtgtgt IS_EQUAL_TO(aaa)(aaa)(aaa None)

gtgtgt IS_EQUAL_TO(aaa)(aab)(aab no match)

class gluonvalidatorsIS_NOT_EMPTY(error_message=rsquoEnter a valuersquo empty_regex=None)Bases gluonvalidatorsValidator

Example

Used as

371 Validators 163

web2py Documentation Release 2146-stable

INPUT(_type=text _name=name requires=IS_NOT_EMPTY())

gtgtgt IS_NOT_EMPTY()(1)(1 None)gtgtgt IS_NOT_EMPTY()(0)(0 None)gtgtgt IS_NOT_EMPTY()(x)(x None)gtgtgt IS_NOT_EMPTY()( x )(x None)gtgtgt IS_NOT_EMPTY()(None)(None enter a value)gtgtgt IS_NOT_EMPTY()()( enter a value)gtgtgt IS_NOT_EMPTY()( )( enter a value)gtgtgt IS_NOT_EMPTY()( nt)( enter a value)gtgtgt IS_NOT_EMPTY()([])([] enter a value)gtgtgt IS_NOT_EMPTY(empty_regex=def)(def)( enter a value)gtgtgt IS_NOT_EMPTY(empty_regex=de[fg])(deg)( enter a value)gtgtgt IS_NOT_EMPTY(empty_regex=def)(abc)(abc None)

class gluonvalidatorsIS_NOT_IN_DB(dbset field error_message=rsquoValue already indatabase or emptyrsquo allowed_override=[] ig-nore_common_filters=False)

Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=name requires=IS_NOT_IN_DB(db dbtable))

makes the field unique

set_self_id(id)

gluonvalidatorsIS_NULL_ORalias of gluonvalidatorsIS_EMPTY_OR

class gluonvalidatorsIS_SLUG(maxlen=80 check=False error_message=rsquoMust be slugrsquokeep_underscores=False)

Bases gluonvalidatorsValidator

converts arbitrary text string to a slug

gtgtgt IS_SLUG()(abc123)(abc123 None)gtgtgt IS_SLUG()(ABC123)(abc123 None)gtgtgt IS_SLUG()(abc-123)(abc-123 None)

(continues on next page)

164 Chapter 37 validators Module

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_SLUG()(abc--123)(abc-123 None)gtgtgt IS_SLUG()(abc 123)(abc-123 None)gtgtgt IS_SLUG()(abc _123)(abc-123 None)gtgtgt IS_SLUG()(-abc-)(abc None)gtgtgt IS_SLUG()(--a--b--_ -c--)(a-b-c None)gtgtgt IS_SLUG()(abcampamp123)(abc123 None)gtgtgt IS_SLUG()(abcampamp123ampampdef)(abc123def None)gtgtgt IS_SLUG()(ntilde)(n None)gtgtgt IS_SLUG(maxlen=4)(abc123)(abc1 None)gtgtgt IS_SLUG()(abc_123)(abc-123 None)gtgtgt IS_SLUG(keep_underscores=False)(abc_123)(abc-123 None)gtgtgt IS_SLUG(keep_underscores=True)(abc_123)(abc_123 None)gtgtgt IS_SLUG(check=False)(abc)(abc None)gtgtgt IS_SLUG(check=True)(abc)(abc None)gtgtgt IS_SLUG(check=False)(a bc)(a-bc None)gtgtgt IS_SLUG(check=True)(a bc)(a bc must be slug)

static urlify(value maxlen=80 keep_underscores=False)

class gluonvalidatorsIS_STRONG(min=None max=None upper=None lower=Nonenumber=None entropy=None special=Nonespecials=rsquo~$^amp()_+-=ltgt []|rsquo invalid=rsquorsquo error_message=None es=False)

Bases object

Examples

Use as

INPUT(_type=password _name=passwdrequires=IS_STRONG(min=10 special=2 upper=2))

enforces complexity requirements on a field

gtgtgt IS_STRONG(es=True)(Abcd1234)(Abcd1234Must include at least 1 of the following ~$^amp()_+-=ltgt[]|)gtgtgt IS_STRONG(es=True)(Abcd1234)(Abcd1234 None)

(continues on next page)

371 Validators 165

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_STRONG(es=True entropy=1)(a)(a None)gtgtgt IS_STRONG(es=True entropy=1 min=2)(a)(a Minimum length is 2)gtgtgt IS_STRONG(es=True entropy=100)(abc123)(abc123 Entropy (3235) less than required (100))gtgtgt IS_STRONG(es=True entropy=100)(and)(and Entropy (1457) less than required (100))gtgtgt IS_STRONG(es=True entropy=100)(aaa)(aaa Entropy (1442) less than required (100))gtgtgt IS_STRONG(es=True entropy=100)(a1d)(a1d Entropy (1597) less than required (100))gtgtgt IS_STRONG(es=True entropy=100)(antilded)(axc3xb1d Entropy (1813) less than required (100))

class gluonvalidatorsIS_TIME(error_message=rsquoEnter time as hhmmss (seconds am pm op-tional)rsquo)

Bases gluonvalidatorsValidator

Example

Use as

INPUT(_type=text _name=name requires=IS_TIME())

understands the following formats hhmmss [ampm] hhmm [ampm] hh [ampm]

[ampm] is optional lsquorsquo can be replaced by any other non-space non-digit

gtgtgt IS_TIME()(2130)(datetimetime(21 30) None)gtgtgt IS_TIME()(21-30)(datetimetime(21 30) None)gtgtgt IS_TIME()(2130)(datetimetime(21 30) None)gtgtgt IS_TIME()(213059)(datetimetime(21 30 59) None)gtgtgt IS_TIME()(530)(datetimetime(5 30) None)gtgtgt IS_TIME()(530 am)(datetimetime(5 30) None)gtgtgt IS_TIME()(530 pm)(datetimetime(17 30) None)gtgtgt IS_TIME()(530 whatever)(530 whatever enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()(530 20)(530 20 enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()(2430)(2430 enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()(2160)(2160 enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()(2130)(2130 enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()()( enter time as hhmmss (seconds am pm optional))ugrave

166 Chapter 37 validators Module

web2py Documentation Release 2146-stable

class gluonvalidatorsIS_UPLOAD_FILENAME(filename=None extension=None lastdot=Truecase=1 error_message=rsquoEnter valid filenamersquo)

Bases gluonvalidatorsValidator

Checks if name and extension of file uploaded through file input matches given criteria

Does not ensure the file type in any way Returns validation failure if no data was uploaded

Parameters

bull filename ndash filename (before dot) regex

bull extension ndash extension (after dot) regex

bull lastdot ndash which dot should be used as a filename extension separator True means lastdot eg filepng -gt file png False means first dot eg filetargz -gt file targz

bull case ndash 0 - keep the case 1 - transform the string into lowercase (default) 2 - transform thestring into uppercase

If there is no dot present extension checks will be done against empty string and filename checks against wholevalue

Examples

Check if file has a pdf extension (case insensitive)

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_UPLOAD_FILENAME(extension=rsquopdfrsquo))

Check if file has a targz extension and name starting with backup

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_UPLOAD_FILENAME(filename=rsquobackuprsquo exten-sion=rsquotargzrsquo lastdot=False))

Check if file has no extension and name matching README (case sensitive)

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_UPLOAD_FILENAME(filename=rsquo^README$rsquoextension=rsquo^$rsquo case=0)

class gluonvalidatorsIS_UPPERBases gluonvalidatorsValidator

Converts to upper case

gtgtgt IS_UPPER()(abc)(ABC None)gtgtgt IS_UPPER()(ntilde)(xc3x91 None)

class gluonvalidatorsIS_URL(error_message=rsquoEnter a valid URLrsquo mode=rsquohttprsquo al-lowed_schemes=None prepend_scheme=rsquohttprsquo al-lowed_tlds=None)

Bases gluonvalidatorsValidator

Rejects a URL string if any of the following is true

bull The string is empty or None

bull The string uses characters that are not allowed in a URL

bull The string breaks any of the HTTP syntactic rules

bull The URL scheme specified (if one is specified) is not lsquohttprsquo or lsquohttpsrsquo

371 Validators 167

web2py Documentation Release 2146-stable

bull The top-level domain (if a host name is specified) does not exist

(These rules are based on RFC 2616 httpwwwfaqsorgrfcsrfc2616html)

This function only checks the URLrsquos syntax It does not check that the URL points to a real document forexample or that it otherwise makes sense semantically This function does automatically prepend lsquohttprsquo infront of a URL in the case of an abbreviated URL (eg lsquogooglecarsquo)

If the parameter mode=rsquogenericrsquo is used then this functionrsquos behavior changes It then rejects a URL string ifany of the following is true

bull The string is empty or None

bull The string uses characters that are not allowed in a URL

bull The URL scheme specified (if one is specified) is not valid

(These rules are based on RFC 2396 httpwwwfaqsorgrfcsrfc2396html)

The list of allowed schemes is customizable with the allowed_schemes parameter If you exclude None fromthe list then abbreviated URLs (lacking a scheme such as lsquohttprsquo) will be rejected

The default prepended scheme is customizable with the prepend_scheme parameter If you set prepend_schemeto None then prepending will be disabled URLs that require prepending to parse will still be accepted but thereturn value will not be modified

IS_URL is compatible with the Internationalized Domain Name (IDN) standard specified in RFC 3490 (httptoolsietforghtmlrfc3490) As a result URLs can be regular strings or unicode strings If the URLrsquos domaincomponent (eg googleca) contains non-US-ASCII letters then the domain will be converted into Punycode(defined in RFC 3492 httptoolsietforghtmlrfc3492) IS_URL goes a bit beyond the standards and allowsnon-US-ASCII characters to be present in the path and query components of the URL as well These non-US-ASCII characters will be escaped using the standard lsquo20rsquo type syntax eg the unicode character with hexcode 0x4e86 will become lsquo4e86rsquo

Parameters

bull error_message ndash a string the error message to give the end user if the URL does notvalidate

bull allowed_schemes ndash a list containing strings or None Each element is a scheme theinputed URL is allowed to use

bull prepend_scheme ndash a string this scheme is prepended if itrsquos necessary to make the URLvalid

Code Examples

INPUT(_type=text _name=name requires=IS_URL())gtgtgt IS_URL()(abccom)(httpabccom None)

INPUT(_type=text _name=name requires=IS_URL(mode=generic))gtgtgt IS_URL(mode=generic)(abccom)(abccom None)

INPUT(_type=text _name=namerequires=IS_URL(allowed_schemes=[https] prepend_scheme=https))

gtgtgt IS_URL(allowed_schemes=[https] prepend_scheme=https)(httpsabccom)(httpsabccom None)

INPUT(_type=text _name=namerequires=IS_URL(prepend_scheme=https))

(continues on next page)

168 Chapter 37 validators Module

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_URL(prepend_scheme=https)(abccom)(httpsabccom None)

INPUT(_type=text _name=namerequires=IS_URL(mode=generic allowed_schemes=[ftps https]

prepend_scheme=https))gtgtgt IS_URL(mode=generic allowed_schemes=[ftps https] prepend_scheme=rarr˓https)(httpsabccom)(httpsabccom None)gtgtgt IS_URL(mode=generic allowed_schemes=[ftps https None] prepend_rarr˓scheme=https)(abccom)(abccom None)

author Jonathan Benn

class gluonvalidatorsIS_JSON(error_message=rsquoInvalid jsonrsquo native_json=False)Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=namerequires=IS_JSON(error_message=This is not a valid json input)

gtgtgt IS_JSON()(a 100)(ua 100 None)

gtgtgt IS_JSON()(spam1234)(spam1234 invalid json)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

371 Validators 169

web2py Documentation Release 2146-stable

170 Chapter 37 validators Module

CHAPTER 38

widget Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

381 The widget is called from web2py

class gluonwidgetIOBases object

write(data)

gluonwidgetcheck_existent_app(options appname)

gluonwidgetconsole()Defines the behavior of the console web2py execution

gluonwidgetget_code_for_scheduler(app options)

gluonwidgetget_url(host path=rsquorsquo proto=rsquohttprsquo port=80)

gluonwidgetrun_system_tests(options)Runs unittests for gluontests

gluonwidgetstart(cron=True)Starts server

gluonwidgetstart_browser(url startup=False)

gluonwidgetstart_schedulers(options)

class gluonwidgetweb2pyDialog(root options)Bases object

Main window dialog

171

web2py Documentation Release 2146-stable

checkTaskBar()Checks taskbar status

connect_pages()Connects pages

error(message)Shows error message

quit(justHide=False)Finishes the program execution

server_ready()

start()Starts web2py server

start_schedulers(app)

stop()Stops web2py server

try_start_scheduler(app)

try_stop_scheduler(app)

update(text)Updates app text

update_canvas()Updates canvas

update_schedulers(start=False)

172 Chapter 38 widget Module

CHAPTER 39

xmlrpc Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

gluonxmlrpchandler(request response methods)

173

web2py Documentation Release 2146-stable

174 Chapter 39 xmlrpc Module

CHAPTER 40

Indices and tables

bull genindex

bull modindex

bull search

175

web2py Documentation Release 2146-stable

176 Chapter 40 Indices and tables

Python Module Index

ggluonadmin 3gluoncache 7gluoncfs 9gluoncompileapp 11gluoncontenttype 15gluoncustom_import 17gluondal 19gluondebug 21gluondecoder 23gluonfileutils 25gluonglobals 27gluonhighlight 33gluonhtml 35gluonhttp 51gluonlanguages 53gluonmain 57gluonmessageboxhandler 59gluonmyregex 61gluonnewcron 63gluonportalocker 65gluonrecfile 67gluonrestricted 69gluonrewrite 71gluonsanitizer 75gluonscheduler 77gluonserializers 83gluonsettings 85gluonshell 87gluonsql 89gluonsqlhtml 97gluonstorage 107gluonstreamer 111gluontemplate 113gluontools 117gluonutf8 139gluonutils 143gluonvalidators 145gluonwidget 171

gluonxmlrpc 173

177

web2py Documentation Release 2146-stable

178 Python Module Index

Index

AA (class in gluonhtml) 35absolute_path_link() (in module gluonnewcron) 63abspath() (in module gluonfileutils) 25accepts() (gluonhtmlFORM method) 41accepts() (gluonsqlhtmlSQLFORM method) 101accessible_query() (gluontoolsAuth method) 121acf() (gluonrewriteMapUrlOut method) 72acquire() (gluonnewcronToken method) 63action() (gluoncacheCache method) 7add_button() (gluonhtmlFORM method) 41add_class() (in module gluonsqlhtml) 104add_deps() (gluonschedulerJobGraph method) 77add_group() (gluontoolsAuth method) 121add_membership() (gluontoolsAuth method) 121add_path_first() (in module gluonadmin) 3add_permission() (gluontoolsAuth method) 122adj_hibernation() (gluonschedulerScheduler method)

79AES_new() (in module gluonutils) 143allows_jwt() (gluontoolsAuth method) 122amfrpc() (gluontoolsService method) 131amfrpc3() (gluontoolsService method) 131ANY_OF (class in gluonvalidators) 145apath() (in module gluonadmin) 3API_SERVER (gluontoolsRecaptcha attribute) 129API_SSL_SERVER (gluontoolsRecaptcha attribute)

129API_URI (gluontoolsRecaptcha2 attribute) 130app_cleanup() (in module gluonadmin) 3app_compile() (in module gluonadmin) 3app_create() (in module gluonadmin) 4app_install() (in module gluonadmin) 4app_pack() (in module gluonadmin) 4app_pack_compiled() (in module gluonadmin) 4app_uninstall() (in module gluonadmin) 4append() (gluonhtmlDIV method) 37append() (gluontemplateBlockNode method) 113append() (gluontemplateContent method) 114

appfactory() (in module gluonmain) 58apply_filter() (gluonlanguagestranslator method) 53archive() (gluontoolsAuth static method) 122archive() (gluontoolsCrud static method) 130arg0 (gluonrewriteMapUrlIn attribute) 71as_dict() (gluonhtmlFORM method) 41as_dict() (gluonsqlDAL method) 92as_dict() (gluonsqlDALField method) 91as_dict() (gluonsqlDALRow method) 91as_dict() (gluonsqlDALTable method) 92as_dict() (gluonsqlField method) 96as_json() (gluonhtmlFORM method) 41as_json() (gluonsqlDALRow method) 91as_xml() (gluonhtmlFORM method) 41as_xml() (gluonsqlDALRow method) 91as_yaml() (gluonhtmlFORM method) 41assert_status() (gluonhtmlFORM method) 41assert_status() (gluonsqlhtmlSQLFORM method) 101assign_tasks() (gluonschedulerScheduler method) 79ASSIGNJS() (in module gluonhtml) 35async() (gluonschedulerMetaScheduler method) 77Auth (class in gluontools) 121AutocompleteWidget (class in gluonsqlhtml) 97autoDetectXMLEncoding() (in module gluondecoder)

23autokey (gluoncacheCache attribute) 8automatic (gluonvalidatorsIS_IPV4 attribute) 158automenu() (gluontoolsWiki method) 135AUTOTYPES (gluonsqlhtmlSQLFORM attribute) 101

BB (class in gluonhtml) 36basic() (gluontoolsAuth method) 122BEAUTIFY (class in gluonhtml) 36being_a_ticker() (gluonschedulerScheduler method) 79BlockNode (class in gluontemplate) 113BODY (class in gluonhtml) 36body (gluonglobalsRequest attribute) 28BooleanWidget (class in gluonsqlhtml) 97BR (class in gluonhtml) 36

179

web2py Documentation Release 2146-stable

build_acf() (gluonrewriteMapUrlOut method) 72build_environment() (in module gluoncompileapp) 12build_query() (gluonsqlhtmlSQLFORM static method)

101build_set() (gluonvalidatorsIS_IN_DB method) 154bulk_insert() (gluonsqlDALTable method) 92bulk_register() (gluontoolsAuth method) 123BUTTON (class in gluonhtml) 36

CCache (class in gluoncache) 7CacheRepresenter (class in gluonsqlhtml) 97callback() (gluonsqlhtmlAutocompleteWidget method)

97can_edit() (gluontoolsWiki method) 135can_join() (gluonsqlDAL method) 92can_manage() (gluontoolsWiki method) 135can_read() (gluontoolsWiki method) 135can_search() (gluontoolsWiki method) 135can_see_menu() (gluontoolsWiki method) 135capitalize() (gluonutf8Utf8 method) 139cas_login() (gluontoolsAuth method) 123cas_validate() (gluontoolsAuth method) 123cast_keys() (in module gluonserializers) 83CAT (class in gluonhtml) 36CENTER (class in gluonhtml) 36center() (gluonutf8Utf8 method) 139change_password() (gluontoolsAuth method) 123check_credentials() (in module gluonfileutils) 26check_existent_app() (in module gluonwidget) 171check_interaction() (in module gluondebug) 22check_new_version() (in module gluonadmin) 4check_reserved_keyword() (gluonsqlDAL method) 92CheckboxesWidget (class in gluonsqlhtml) 97checkTaskBar() (gluonwidgetweb2pyDialog method)

171cleanpath() (in module gluonfileutils) 25CLEANUP (class in gluonvalidators) 145clear() (gluonglobalsSession method) 30clear_content() (gluontemplateContent method) 114clear_interaction() (gluondebugWebDebugger method)

21clear_session_cookies() (gluonglobalsSession method)

30clone() (gluonsqlDALField method) 91clone() (gluonsqlField method) 96close() (gluonportalockerLockedFile method) 65close() (gluonsqlDAL method) 92cloud() (gluontoolsWiki method) 135CODE (class in gluonhtml) 36COL (class in gluonhtml) 37COLGROUP (class in gluonhtml) 37commit() (gluonsqlDAL method) 92communicate() (in module gluondebug) 22

compare() (in module gluonutils) 143compile2() (in module gluonrestricted) 69compile_application() (in module gluoncompileapp) 12compile_controllers() (in module gluoncompileapp) 12compile_models() (in module gluoncompileapp) 12compile_regex() (in module gluonrewrite) 72compile_views() (in module gluoncompileapp) 12component() (gluontoolsWiki static method) 135compute_uuid() (gluonglobalsRequest method) 28confirm() (gluonhtmlFORM static method) 41confirm_registration() (gluontoolsAuth method) 123connect() (gluonglobalsSession method) 30connect_pages() (gluonwidgetweb2pyDialog method)

172console() (in module gluonwidget) 171Content (class in gluontemplate) 114content_type (gluonsqlhtmlExportClass attribute) 98content_type (gluonsqlhtmlExporterCSV attribute) 98content_type (gluonsqlhtmlExporterCSV_hidden

attribute) 98content_type (gluonsqlhtmlExporterHTML attribute)

98content_type (gluonsqlhtmlExporterJSON attribute) 98content_type (gluonsqlhtmlExporterTSV attribute) 99content_type (gluonsqlhtmlExporterXML attribute) 99contenttype() (in module gluoncontenttype) 15cookies2headers() (gluonhttpHTTP method) 51count() (gluonsqlDALField method) 91count() (gluonsqlField method) 96count() (gluonutf8Utf8 method) 139create() (gluontoolsCrud method) 130create() (gluontoolsWiki method) 135create_missing_app_folders() (in module gluonadmin) 5create_missing_folders() (in module gluonadmin) 5createform() (gluonsqlhtmlSQLFORM method) 102crondance() (in module gluonnewcron) 63cronlauncher (class in gluonnewcron) 63Crud (class in gluontools) 130CRYPT (class in gluonvalidators) 146csv() (gluontoolsService method) 132csv() (in module gluonserializers) 83custom_import_install() (in module

gluoncustom_import) 17custom_importer() (in module gluoncustom_import) 17custom_json() (in module gluonserializers) 83CustomImportException 17

DDAL (class in gluonsql) 89DALField (class in gluonsql) 91DALRow (class in gluonsql) 91DALTable (class in gluonsql) 92DatetimeWidget (class in gluonsqlhtml) 98DateWidget (class in gluonsqlhtml) 98

180 Index

web2py Documentation Release 2146-stable

DecimalWidget (class in gluonsqlhtml) 98decode() (gluonutf8Utf8 method) 139decoder() (in module gluondecoder) 23default_delimiters (gluontemplateTemplateParser

attribute) 115default_messages (gluontoolsAuth attribute) 123default_settings (gluontoolsAuth attribute) 124DEFAULT_WIDTH (gluonsqlhtmlUploadWidget

attribute) 104define_signature() (gluontoolsAuth method) 125define_table() (gluonsqlDAL method) 93define_tables() (gluonschedulerScheduler method) 79define_tables() (gluontoolsAuth method) 125del_group() (gluontoolsAuth method) 125del_membership() (gluontoolsAuth method) 125del_permission() (gluontoolsAuth method) 125delete() (gluontoolsCrud method) 130DELETE_FILE (gluonsqlhtmlUploadWidget attribute)

104dictform() (gluonsqlhtmlSQLFORM static method) 102die() (gluonschedulerMetaScheduler method) 78die() (in module gluonshell) 87disable() (gluonschedulerScheduler method) 79distributed_transaction_begin() (gluonsqlDAL static

method) 93distributed_transaction_commit() (gluonsqlDAL static

method) 93DIV (class in gluonhtml) 37do_continue() (gluondebugWebDebugger method) 21do_exec() (gluondebugWebDebugger method) 21do_next() (gluondebugWebDebugger method) 21do_quit() (gluondebugWebDebugger method) 21do_return() (gluondebugWebDebugger method) 21do_step() (gluondebugWebDebugger method) 21DoubleWidget (class in gluonsqlhtml) 98download() (gluonglobalsResponse method) 28drop() (gluonsqlDALTable method) 92DummyResponse (class in gluontemplate) 114

Eedit() (gluontoolsWiki method) 135editmedia() (gluontoolsWiki method) 135element() (gluonhtmlDIV method) 38elements() (gluonhtmlDIV method) 38elements() (gluonhtmlXML method) 49EM (class in gluonhtml) 40email_registration() (gluontoolsAuth method) 125email_reset_password() (gluontoolsAuth method) 125EMBED (class in gluonhtml) 40embed64() (in module gluonhtml) 50emit() (gluonmessageboxhandlerMessageBoxHandler

method) 59emit() (gluonmessageboxhandlerNotifySendHandler

method) 59

enable_autocomplete_and_history() (in modulegluonshell) 87

enable_record_versioning() (gluontoolsAuth method)125

encode() (gluonutf8Utf8 method) 140endswith() (gluonutf8Utf8 method) 140env() (in module gluonshell) 87error() (gluontoolsService method) 132error() (gluonwidgetweb2pyDialog method) 172everybody (gluontoolsWiki attribute) 135exception() (gluondebugWebDebugger method) 21exec_environment() (in module gluonshell) 87exec_pythonrc() (in module gluonshell) 87execute_from_command_line() (in module gluonshell)

87executesql() (gluonsqlDAL method) 93executor() (in module gluonscheduler) 82exists() (in module gluonrecfile) 67expandtabs() (gluonutf8Utf8 method) 140export() (gluonsqlhtmlExportClass method) 98export() (gluonsqlhtmlExporterCSV method) 98export() (gluonsqlhtmlExporterCSV_hidden method)

98export() (gluonsqlhtmlExporterHTML method) 98export() (gluonsqlhtmlExporterJSON method) 98export() (gluonsqlhtmlExporterTSV method) 99export() (gluonsqlhtmlExporterXML method) 99export_to_csv_file() (gluonsqlDAL method) 93ExportClass (class in gluonsqlhtml) 98ExporterCSV (class in gluonsqlhtml) 98ExporterCSV_hidden (class in gluonsqlhtml) 98ExporterHTML (class in gluonsqlhtml) 98ExporterJSON (class in gluonsqlhtml) 98ExporterTSV (class in gluonsqlhtml) 99ExporterXML (class in gluonsqlhtml) 99extcron (class in gluonnewcron) 63extend() (gluontemplateBlockNode method) 113extend() (gluontemplateContent method) 114extend() (gluontemplateTemplateParser method) 115

Ffactory() (gluonsqlhtmlSQLFORM static method) 102fast_urandom16() (in module gluonutils) 143fetch() (in module gluontools) 137Field (class in gluonsql) 95FIELDKEY_DELETE_RECORD

(gluonsqlhtmlSQLFORM attribute) 101FIELDNAME_REQUEST_DELETE

(gluonsqlhtmlSQLFORM attribute) 101fields (gluonsqlDALTable attribute) 92FIELDSET (class in gluonhtml) 40file_ext (gluonsqlhtmlExportClass attribute) 98file_ext (gluonsqlhtmlExporterCSV attribute) 98

Index 181

web2py Documentation Release 2146-stable

file_ext (gluonsqlhtmlExporterCSV_hidden attribute)98

file_ext (gluonsqlhtmlExporterHTML attribute) 98file_ext (gluonsqlhtmlExporterJSON attribute) 98file_ext (gluonsqlhtmlExporterTSV attribute) 99file_ext (gluonsqlhtmlExporterXML attribute) 99filter_err() (in module gluonrewrite) 72filter_url() (in module gluonrewrite) 72find() (gluonutf8Utf8 method) 140find_exposed_functions() (in module gluoncompileapp)

12findT() (in module gluonlanguages) 55first_paragraph() (gluontoolsWiki method) 135fix_hostname() (gluontoolsWiki method) 135fix_newlines() (in module gluonfileutils) 26fixup_missing_path_info() (in module gluonrewrite) 72flatten() (gluonhtmlDIV method) 39flatten() (gluonhtmlMARKMIN method) 44flatten() (gluonhtmlXML method) 49flush() (gluondebugPipe method) 21force() (gluonlanguagestranslator method) 53forget() (gluonglobalsSession method) 30FORM (class in gluonhtml) 40form_factory() (in module gluonsqlhtml) 104format() (gluonutf8Utf8 method) 140formatter() (gluonsqlDALField method) 91formatter() (gluonsqlField method) 96formatter() (gluonvalidatorsANY_OF method) 145formatter() (gluonvalidatorsIS_DATE method) 148formatter() (gluonvalidatorsIS_DATETIME method)

149formatter() (gluonvalidatorsIS_DECIMAL_IN_RANGE

method) 150formatter() (gluonvalidatorsIS_EMPTY_OR method)

152formatter() (gluonvalidatorsIS_FLOAT_IN_RANGE

method) 153formatter() (gluonvalidatorsIS_JSON method) 169formatter() (gluonvalidatorsIS_LIST_OF_EMAILS

method) 152formstyle_bootstrap() (in module gluonsqlhtml) 105formstyle_bootstrap3_inline_factory() (in module

gluonsqlhtml) 105formstyle_bootstrap3_stacked() (in module

gluonsqlhtml) 105formstyle_divs() (in module gluonsqlhtml) 105formstyle_inline() (in module gluonsqlhtml) 105formstyle_table2cols() (in module gluonsqlhtml) 105formstyle_table3cols() (in module gluonsqlhtml) 105formstyle_ul() (in module gluonsqlhtml) 105formstyles (gluonsqlhtmlSQLFORM attribute) 102FormWidget (class in gluonsqlhtml) 99frameset (gluonhtmlHTML attribute) 43frameset (gluonhtmlXHTML attribute) 49

Ggenerate() (in module gluonrecfile) 67GENERIC_DESCRIPTION

(gluonsqlhtmlUploadWidget attribute)104

geocode() (in module gluontools) 137get() (gluonhtmlDIV method) 39get() (gluonsqlDALRow method) 91get_callable_argspec() (in module gluonutils) 143get_code_for_scheduler() (in module gluonwidget) 171get_digest() (in module gluonutils) 143get_effective_router() (in module gluonrewrite) 72get_format() (gluontoolsCrud method) 130get_instances() (gluonsqlDAL static method) 93get_or_create_key() (gluontoolsAuth static method)

125get_or_create_user() (gluontoolsAuth method) 125get_parsed() (in module gluontemplate) 115get_possible_languages() (gluonlanguagestranslator

method) 54get_possible_languages_info()

(gluonlanguagestranslator method) 54get_query() (gluontoolsCrud method) 130get_renderer() (gluontoolsWiki method) 135get_session() (in module gluonfileutils) 26get_t() (gluonlanguagestranslator method) 54get_url() (in module gluonwidget) 171get_usage() (in module gluonshell) 87get_vars (gluonglobalsRequest attribute) 28get_vars_next() (gluontoolsAuth method) 126get_workers() (gluonschedulerScheduler method) 79getcfs() (in module gluoncfs) 9getfirst() (gluonstorageStorage method) 108getipaddrinfo() (in module gluonutils) 143getlast() (gluonstorageStorage method) 108getlist() (gluonstorageStorage method) 108give_up() (gluonschedulerMetaScheduler method) 78gluonadmin (module) 3gluoncache (module) 7gluoncfs (module) 9gluoncompileapp (module) 11gluoncontenttype (module) 15gluoncustom_import (module) 17gluondal (module) 19gluondebug (module) 21gluondecoder (module) 23gluonfileutils (module) 25gluonglobals (module) 27gluonhighlight (module) 33gluonhtml (module) 35gluonhttp (module) 51gluonlanguages (module) 53gluonmain (module) 57gluonmessageboxhandler (module) 59

182 Index

web2py Documentation Release 2146-stable

gluonmyregex (module) 61gluonnewcron (module) 63gluonportalocker (module) 65gluonrecfile (module) 67gluonrestricted (module) 69gluonrewrite (module) 71gluonsanitizer (module) 75gluonscheduler (module) 77gluonserializers (module) 83gluonsettings (module) 85gluonshell (module) 87gluonsql (module) 89gluonsqlhtml (module) 97gluonstorage (module) 107gluonstreamer (module) 111gluontemplate (module) 113gluontools (module) 117gluonutf8 (module) 139gluonutils (module) 143gluonvalidators (module) 145gluonwidget (module) 171gluonxmlrpc (module) 173grid() (gluonsqlhtmlSQLFORM static method) 102groups() (gluontoolsAuth method) 126

HH1 (class in gluonhtml) 42H2 (class in gluonhtml) 42H3 (class in gluonhtml) 42H4 (class in gluonhtml) 42H5 (class in gluonhtml) 42H6 (class in gluonhtml) 42handler() (in module gluonxmlrpc) 173hardcron (class in gluonnewcron) 64harg0 (gluonrewriteMapUrlIn attribute) 71has_membership() (gluontoolsAuth method) 126has_options() (gluonsqlhtmlOptionsWidget static

method) 100has_permission() (gluontoolsAuth method) 126has_permission() (gluontoolsCrud method) 130has_representer() (gluonsqlDAL method) 94HEAD (class in gluonhtml) 42here() (gluontoolsAuth method) 126hidden_fields() (gluonhtmlFORM method) 41highlight() (in module gluonhighlight) 33HR (class in gluonhtml) 42HTML (class in gluonhtml) 42html5 (gluonhtmlHTML attribute) 43html_render() (gluontoolsWiki method) 135HTTP 51HttpServer (class in gluonmain) 58

II (class in gluonhtml) 43

ics() (in module gluonserializers) 83ID_DELETE_SUFFIX (gluonsqlhtmlUploadWidget at-

tribute) 104id_group() (gluontoolsAuth method) 126ID_LABEL_SUFFIX (gluonsqlhtmlSQLFORM at-

tribute) 101ID_ROW_SUFFIX (gluonsqlhtmlSQLFORM attribute)

101IFRAME (class in gluonhtml) 43IMG (class in gluonhtml) 43impersonate() (gluontoolsAuth method) 126import_from_csv_file() (gluonsqlDAL method) 94import_from_csv_file() (gluonsqlDALTable method)

92import_table_definitions() (gluonsqlDAL method) 94include() (gluontemplateTemplateParser method) 115include_files() (gluonglobalsResponse method) 28include_meta() (gluonglobalsResponse method) 28index() (gluonutf8Utf8 method) 140initialize_urandom() (in module gluonutils) 143INPUT (class in gluonhtml) 43insert() (gluonhtmlDIV method) 40insert() (gluonsqlDALTable method) 92insert() (gluontemplateContent method) 114instances (gluontoolsPluginManager attribute) 137IntegerWidget (class in gluonsqlhtml) 99interaction() (gluondebugWebDebugger method) 22invalid_url() (in module gluonrewrite) 72IO (class in gluonwidget) 171IS_ALPHANUMERIC (class in gluonvalidators) 147IS_DATE (class in gluonvalidators) 148IS_DATE_IN_RANGE (class in gluonvalidators) 147IS_DATETIME (class in gluonvalidators) 148IS_DATETIME_IN_RANGE (class in gluonvalidators)

148IS_DECIMAL_IN_RANGE (class in gluonvalidators)

149IS_EMAIL (class in gluonvalidators) 150IS_EMPTY_OR (class in gluonvalidators) 152IS_EQUAL_TO (class in gluonvalidators) 163is_expired() (gluonglobalsSession method) 30IS_EXPR (class in gluonvalidators) 152IS_FLOAT_IN_RANGE (class in gluonvalidators) 153IS_IMAGE (class in gluonvalidators) 153is_image() (gluonsqlhtmlUploadWidget static method)

104is_impersonating() (gluontoolsAuth method) 126IS_IN_DB (class in gluonvalidators) 154IS_IN_SET (class in gluonvalidators) 154IS_INT_IN_RANGE (class in gluonvalidators) 155IS_IPADDRESS (class in gluonvalidators) 159IS_IPV4 (class in gluonvalidators) 156IS_IPV6 (class in gluonvalidators) 158IS_JSON (class in gluonvalidators) 169

Index 183

web2py Documentation Release 2146-stable

IS_LENGTH (class in gluonvalidators) 161IS_LIST_OF (class in gluonvalidators) 162IS_LIST_OF_EMAILS (class in gluonvalidators) 152is_logged_in() (gluontoolsAuth method) 126is_loopback_ip_address() (in module gluonutils) 144IS_LOWER (class in gluonvalidators) 162IS_MATCH (class in gluonvalidators) 162is_new() (gluonglobalsSession method) 30IS_NOT_EMPTY (class in gluonvalidators) 163IS_NOT_IN_DB (class in gluonvalidators) 164IS_NULL_OR (in module gluonvalidators) 164IS_SLUG (class in gluonvalidators) 164IS_STRONG (class in gluonvalidators) 165IS_TIME (class in gluonvalidators) 166is_tracking_changes() (in module gluoncustom_import)

17IS_UPLOAD_FILENAME (class in gluonvalidators)

166IS_UPPER (class in gluonvalidators) 167IS_URL (class in gluonvalidators) 167is_valid_ip_address() (in module gluonutils) 144isalnum() (gluonutf8Utf8 method) 140isalpha() (gluonutf8Utf8 method) 140isdigit() (gluonutf8Utf8 method) 140islower() (gluonutf8Utf8 method) 140isodatetime (gluonvalidatorsIS_DATETIME attribute)

149isspace() (gluonutf8Utf8 method) 140istitle() (gluonutf8Utf8 method) 140isupper() (gluonutf8Utf8 method) 140

JJobGraph (class in gluonscheduler) 77join() (gluonutf8Utf8 method) 140json() (gluonglobalsResponse method) 28json() (gluontoolsService method) 132json() (in module gluonserializers) 83jsonrpc() (gluontoolsService method) 132jsonrpc2() (gluontoolsService method) 132jsonrpc_errors (gluontoolsService attribute) 133JSONWidget (class in gluonsqlhtml) 99jwt() (gluontoolsAuth method) 126

Kkeys() (gluontoolsPluginManager method) 137kill() (gluonschedulerScheduler method) 79

LLABEL (class in gluonhtml) 44label (gluonsqlhtmlExportClass attribute) 98label (gluonsqlhtmlExporterCSV attribute) 98label (gluonsqlhtmlExporterCSV_hidden attribute) 98label (gluonsqlhtmlExporterHTML attribute) 98label (gluonsqlhtmlExporterJSON attribute) 98

label (gluonsqlhtmlExporterTSV attribute) 99label (gluonsqlhtmlExporterXML attribute) 99launch() (gluonnewcronhardcron method) 64Lazy (gluonsqlDALField attribute) 91Lazy (gluonsqlField attribute) 95lazy_cache() (in module gluoncache) 8lazy_define_table() (gluonsqlDAL method) 94LEGEND (class in gluonhtml) 44LI (class in gluonhtml) 44LINK (class in gluonhtml) 44List (class in gluonstorage) 107listdir() (in module gluonfileutils) 25ListWidget (class in gluonsqlhtml) 99ljust() (gluonutf8Utf8 method) 140load() (gluonrestrictedRestrictedError method) 69load() (gluonrestrictedTicketStorage method) 69LOAD() (in module gluoncompileapp) 11load() (in module gluonrewrite) 72load_routers() (in module gluonrewrite) 73load_storage() (in module gluonstorage) 109LoadFactory (class in gluoncompileapp) 12loads_json() (in module gluonserializers) 83loads_yaml() (in module gluonserializers) 83local_import_aux() (in module gluoncompileapp) 12localhost (gluonvalidatorsIS_IPV4 attribute) 158lock() (in module gluonportalocker) 66LockedFile (class in gluonportalocker) 65log() (gluonrestrictedRestrictedError method) 69log_event() (gluontoolsAuth method) 127log_event() (gluontoolsCrud method) 130log_rewrite() (in module gluonrewrite) 73logger (gluonsqlDAL attribute) 94login() (gluontoolsAuth method) 127login_bare() (gluontoolsAuth method) 127login_user() (gluontoolsAuth method) 127logout() (gluontoolsAuth method) 127logout_bare() (gluontoolsAuth method) 127loop() (gluonschedulerMetaScheduler method) 78loop() (gluonschedulerScheduler method) 79lower() (gluonutf8Utf8 method) 141lstrip() (gluonutf8Utf8 method) 141

MM() (gluonlanguagestranslator method) 53Mail (class in gluontools) 117MailAttachment (class in gluontools) 118main() (in module gluonscheduler) 82make_fake_file_like_object() (in module gluonfileutils)

26manage_tokens() (gluontoolsAuth method) 127map_app() (gluonrewriteMapUrlIn method) 71map_controller() (gluonrewriteMapUrlIn method) 71map_function() (gluonrewriteMapUrlIn method) 71map_language() (gluonrewriteMapUrlIn method) 71

184 Index

web2py Documentation Release 2146-stable

map_prefix() (gluonrewriteMapUrlIn method) 71map_root_static() (gluonrewriteMapUrlIn method) 72map_static() (gluonrewriteMapUrlIn method) 72map_url_in() (in module gluonrewrite) 73map_url_out() (in module gluonrewrite) 73MapUrlIn (class in gluonrewrite) 71MapUrlOut (class in gluonrewrite) 72MARKMIN (class in gluonhtml) 44markmin_base() (gluontoolsWiki method) 135markmin_render() (gluontoolsWiki method) 135maybe_add() (gluonvalidatorsIS_IN_DB method) 154md5_hash() (in module gluonutils) 144media() (gluontoolsWiki method) 135MENU (class in gluonhtml) 44menu() (gluontoolsWiki method) 135message (gluonhttpHTTP attribute) 51MessageBoxHandler (class in

gluonmessageboxhandler) 59Messages (class in gluonstorage) 108META (class in gluonhtml) 45MetaScheduler (class in gluonscheduler) 77Method (gluonsqlDALField attribute) 91Method (gluonsqlField attribute) 95mktree() (in module gluonfileutils) 25model_cmp() (in module gluoncompileapp) 12model_cmp_sep() (in module gluoncompileapp) 12MultipleOptionsWidget (class in gluonsqlhtml) 99mybuiltin (class in gluoncompileapp) 12

Nnavbar() (gluontoolsAuth method) 127nice() (gluonvalidatorsIS_DATETIME static method)

149no_underscore() (gluonhtmlBEAUTIFY static method)

36Node (class in gluontemplate) 114NOESCAPE (class in gluontemplate) 114not_authorized() (gluontoolsAuth method) 127not_authorized() (gluontoolsWiki method) 135NotifySendHandler (class in gluonmessageboxhandler)

59now() (gluonschedulerScheduler method) 79numbers (gluonvalidatorsIS_IPV4 attribute) 158

OOBJECT (class in gluonhtml) 45OL (class in gluonhtml) 44omit_acf() (gluonrewriteMapUrlOut method) 72omit_lang() (gluonrewriteMapUrlOut method) 72on() (gluonsqlDALTable method) 92open() (in module gluonrecfile) 67OPTGROUP (class in gluonhtml) 45OPTION (class in gluonhtml) 45options() (gluonvalidatorsIS_IN_DB method) 154

options() (gluonvalidatorsIS_IN_SET method) 155OptionsWidget (class in gluonsqlhtml) 100output() (gluontemplateBlockNode method) 113output_aux() (in module gluontemplate) 115

PP (class in gluonhtml) 45PACKAGE_PATH_SUFFIX

(gluoncustom_importTrackImporter at-tribute) 17

pad() (in module gluonutils) 144pages() (gluontoolsWiki method) 136params_substitution() (gluonlanguagestranslator

method) 54parse() (gluontemplateTemplateParser method) 115parse_all_vars() (gluonglobalsRequest method) 28parse_as_rest() (gluonsqlDAL method) 94parse_get_vars() (gluonglobalsRequest method) 28parse_path_info() (in module gluonshell) 87parse_post_vars() (gluonglobalsRequest method) 28parse_template() (in module gluontemplate) 115parse_version() (in module gluonfileutils) 25parsecronline() (in module gluonnewcron) 64partition() (gluonutf8Utf8 method) 141PasswordWidget (class in gluonsqlhtml) 100pbkdf2_hex() (in module gluonutils) 144Pipe (class in gluondebug) 21plugin_install() (in module gluonadmin) 5plugin_pack() (in module gluonadmin) 5PluginManager (class in gluontools) 136plural() (gluonlanguagestranslator method) 55pop_arg_if() (gluonrewriteMapUrlIn method) 72pop_task() (gluonschedulerMetaScheduler method) 78pop_task() (gluonschedulerScheduler method) 79post_vars (gluonglobalsRequest attribute) 28PRE (class in gluonhtml) 45prettydate() (in module gluontools) 137preview() (gluontoolsWiki method) 136private (gluonvalidatorsIS_IPV4 attribute) 158process() (gluonhtmlFORM method) 41profile() (gluontoolsAuth method) 127

Qqueue_task() (gluonschedulerScheduler method) 79quit() (gluonwidgetweb2pyDialog method) 172

Rr_multiline (gluontemplateTemplateParser attribute)

115r_tag (gluontemplateTemplateParser attribute) 115RadioWidget (class in gluonsqlhtml) 100random_password() (gluontoolsAuth method) 127rangetolist() (in module gluonnewcron) 64re_block (gluontemplateTemplateParser attribute) 115

Index 185

web2py Documentation Release 2146-stable

re_compile() (in module gluoncompileapp) 12re_pass (gluontemplateTemplateParser attribute) 115re_unblock (gluontemplateTemplateParser attribute)

115read() (gluondebugPipe method) 21read() (gluonportalockerLockedFile method) 66read() (gluontoolsCrud method) 130read() (gluontoolsWiki method) 136read_file() (in module gluonfileutils) 25read_locked() (in module gluonportalocker) 66read_pyc() (in module gluoncompileapp) 12readline() (gluondebugPipe method) 21readline() (gluonportalockerLockedFile method) 66readlines() (gluonportalockerLockedFile method) 66readlines_file() (in module gluonfileutils) 25Recaptcha (class in gluontools) 129Recaptcha2 (class in gluontools) 129recursive_unlink() (in module gluonfileutils) 25redirect() (in module gluonhttp) 51REDIRECT_JS (gluonhtmlFORM attribute) 41regex (gluonvalidatorsIS_EMAIL attribute) 151regex (gluonvalidatorsIS_IPV4 attribute) 158regex_attr (gluonhtmlDIV attribute) 40regex_class (gluonhtmlDIV attribute) 40REGEX_CLEANUP (gluonvalidatorsCLEANUP

attribute) 146regex_filter_in() (in module gluonrewrite) 73regex_filter_out() (in module gluonrewrite) 73regex_id (gluonhtmlDIV attribute) 40regex_proposed_but_failed (gluonvalidatorsIS_EMAIL

attribute) 151regex_select() (in module gluonrewrite) 73regex_tag (gluonhtmlDIV attribute) 40regex_uri() (in module gluonrewrite) 73regex_url_in() (in module gluonrewrite) 73register() (gluontoolsAuth method) 127register_bare() (gluontoolsAuth method) 127reindent() (gluontemplateTemplateParser method) 115release() (gluonnewcronToken method) 63remove() (in module gluonrecfile) 67remove_compiled_application() (in module

gluoncompileapp) 12render() (gluonglobalsResponse method) 28render() (in module gluontemplate) 115render_tags() (gluontoolsWiki method) 136renew() (gluonglobalsSession method) 30replace() (gluonutf8Utf8 method) 141report_task() (gluonschedulerMetaScheduler method)

78report_task() (gluonschedulerScheduler method) 80represent() (gluonsqlDAL method) 94represent() (gluonsqlhtmlUploadWidget class method)

104represent() (in module gluonsqlhtml) 105

represented() (gluonsqlhtmlExportClass method) 98representers (gluonsqlDAL attribute) 94Request (class in gluonglobals) 27request_reset_password() (gluontoolsAuth method) 127requires() (gluontoolsAuth method) 127requires_https() (gluonglobalsRequest method) 28requires_login() (gluontoolsAuth method) 127requires_login_or_token() (gluontoolsAuth method)

127requires_membership() (gluontoolsAuth method) 128requires_permission() (gluontoolsAuth method) 128requires_signature() (gluontoolsAuth method) 128reset_password() (gluontoolsAuth method) 128reset_password_deprecated() (gluontoolsAuth method)

128Response (class in gluonglobals) 28restful() (gluonglobalsRequest method) 28restricted() (in module gluonrestricted) 69RestrictedError 69resume() (gluonschedulerScheduler method) 80retrieve() (gluonsqlDALField method) 91retrieve() (gluonsqlField method) 96retrieve_file_properties() (gluonsqlDALField method)

91retrieve_file_properties() (gluonsqlField method) 96retrieve_password() (gluontoolsAuth method) 128retrieve_username() (gluontoolsAuth method) 128reverse_geocode() (in module gluontools) 137rfind() (gluonutf8Utf8 method) 141rindex() (gluonutf8Utf8 method) 141rjust() (gluonutf8Utf8 method) 141rollback() (gluonsqlDAL method) 94rows() (gluontoolsCrud method) 130rows_page (gluontoolsWiki attribute) 136rpartition() (gluonutf8Utf8 method) 141rsplit() (gluonutf8Utf8 method) 141rss() (gluontoolsService method) 133rss() (in module gluonserializers) 83rstrip() (gluonutf8Utf8 method) 141run() (gluondebugWebDebugger method) 22run() (gluonnewcroncronlauncher method) 63run() (gluonnewcronextcron method) 64run() (gluonnewcronhardcron method) 64run() (gluonnewcronsoftcron method) 64run() (gluonschedulerMetaScheduler method) 78run() (gluontoolsService method) 133run() (in module gluonshell) 88run_controller_in() (in module gluoncompileapp) 13run_login_onaccept() (gluontoolsAuth method) 128run_models_in() (in module gluoncompileapp) 13run_system_tests() (in module gluonwidget) 171run_view_in() (in module gluoncompileapp) 13

186 Index

web2py Documentation Release 2146-stable

Ssafe_encode() (in module gluonserializers) 83safe_float() (in module gluonsqlhtml) 105safe_int() (in module gluonsqlhtml) 105sanitize() (in module gluonsanitizer) 75save_password() (in module gluonmain) 58save_pyc() (in module gluoncompileapp) 13save_session_id_cookie() (gluonglobalsSession

method) 31save_storage() (in module gluonstorage) 109Scheduler (class in gluonscheduler) 78SCRIPT (class in gluonhtml) 45search() (gluontoolsCrud method) 130search() (gluontoolsWiki method) 136search_menu() (gluonsqlhtmlSQLFORM static

method) 102secure() (gluonglobalsSession method) 31secure_dumps() (in module gluonutils) 144secure_loads() (in module gluonutils) 144SELECT (class in gluonhtml) 45select() (gluontoolsCrud method) 131select_host() (gluontoolsAuth method) 128send() (gluontoolsMail method) 119send_heartbeat() (gluonschedulerMetaScheduler

method) 78send_heartbeat() (gluonschedulerScheduler method) 80serialize() (gluonhtmlMENU method) 45serialize_mobile() (gluonhtmlMENU method) 45serializers (gluonsqlDAL attribute) 95serve_amfrpc() (gluontoolsService method) 133serve_csv() (gluontoolsService method) 134serve_json() (gluontoolsService method) 134serve_jsonrpc() (gluontoolsService method) 134serve_jsonrpc2() (gluontoolsService method) 134serve_rss() (gluontoolsService method) 134serve_run() (gluontoolsService method) 134serve_soap() (gluontoolsService method) 134serve_xml() (gluontoolsService method) 134serve_xmlrpc() (gluontoolsService method) 134server_ready() (gluonwidgetweb2pyDialog method)

172Service (class in gluontools) 131ServiceJsonRpcException 131Session (class in gluonglobals) 29set_attributes() (gluonsqlDALField method) 91set_attributes() (gluonsqlField method) 96set_current_languages() (gluonlanguagestranslator

method) 55set_folder() (gluonsqlDAL static method) 95set_requirements() (gluonschedulerScheduler method)

80set_self_id() (gluonvalidatorsIS_EMPTY_OR method)

152set_self_id() (gluonvalidatorsIS_IN_DB method) 154

set_self_id() (gluonvalidatorsIS_NOT_IN_DB method)164

set_trace() (in module gluondebug) 22set_worker_status() (gluonschedulerScheduler method)

80Settings (class in gluonstorage) 108show_if() (in module gluonsqlhtml) 105sibling() (gluonhtmlDIV method) 40siblings() (gluonhtmlDIV method) 40simple_hash() (in module gluonutils) 144sleep() (gluonschedulerMetaScheduler method) 78sleep() (gluonschedulerScheduler method) 80sluggify() (gluonrewriteMapUrlIn method) 72sluggify() (in module gluonrewrite) 73smart_query() (gluonsqlDAL method) 95smartdictform() (gluonsqlhtmlSQLFORM static

method) 102smartgrid() (gluonsqlhtmlSQLFORM static method)

102soap() (gluontoolsService method) 134softcron (class in gluonnewcron) 64SPAN (class in gluonhtml) 46split() (gluonutf8Utf8 method) 141split_emails (gluonvalidatorsIS_LIST_OF_EMAILS at-

tribute) 152splitlines() (gluonutf8Utf8 method) 141SQLFORM (class in gluonsqlhtml) 100sqlsafe (gluonsqlDALField attribute) 91sqlsafe (gluonsqlDALTable attribute) 92sqlsafe (gluonsqlField attribute) 96sqlsafe_alias (gluonsqlDALTable attribute) 92sqlsafe_name (gluonsqlDALField attribute) 91sqlsafe_name (gluonsqlField attribute) 96SQLTABLE (class in gluonsqlhtml) 103start() (gluonmainHttpServer method) 58start() (gluonwidgetweb2pyDialog method) 172start() (in module gluonwidget) 171start_browser() (in module gluonwidget) 171start_heartbeats() (gluonschedulerMetaScheduler

method) 78start_schedulers() (gluonwidgetweb2pyDialog method)

172start_schedulers() (in module gluonwidget) 171startswith() (gluonutf8Utf8 method) 141stop() (gluonmainHttpServer method) 58stop() (gluonwidgetweb2pyDialog method) 172stop_task() (gluonschedulerScheduler method) 80stop_trace() (in module gluondebug) 22stopcron() (in module gluonnewcron) 64Storage (class in gluonstorage) 107StorageList (class in gluonstorage) 109store() (gluonrestrictedTicketStorage method) 69store() (gluonsqlDALField method) 91store() (gluonsqlField method) 96

Index 187

web2py Documentation Release 2146-stable

stream() (gluonglobalsResponse method) 28stream_file_or_304_or_206() (in module

gluonstreamer) 111streamer() (in module gluonstreamer) 111strict (gluonhtmlHTML attribute) 43strict (gluonhtmlXHTML attribute) 49StringWidget (class in gluonsqlhtml) 103strip() (gluonutf8Utf8 method) 141STRONG (class in gluonhtml) 46STYLE (class in gluonhtml) 46style() (gluonsqlhtmlSQLTABLE method) 103SuperNode (class in gluontemplate) 114swapcase() (gluonutf8Utf8 method) 142

TTABLE (class in gluonhtml) 46table_cas() (gluontoolsAuth method) 128table_event() (gluontoolsAuth method) 128table_group() (gluontoolsAuth method) 128table_membership() (gluontoolsAuth method) 128table_permission() (gluontoolsAuth method) 128table_token() (gluontoolsAuth method) 128table_user() (gluontoolsAuth method) 128tables (gluonsqlDAL attribute) 95tables() (gluontoolsCrud method) 131tag (gluonhtmlA attribute) 35tag (gluonhtmlB attribute) 36tag (gluonhtmlBEAUTIFY attribute) 36tag (gluonhtmlBODY attribute) 36tag (gluonhtmlBR attribute) 36tag (gluonhtmlBUTTON attribute) 36tag (gluonhtmlCAT attribute) 36tag (gluonhtmlCENTER attribute) 36tag (gluonhtmlCOL attribute) 37tag (gluonhtmlCOLGROUP attribute) 37tag (gluonhtmlDIV attribute) 40tag (gluonhtmlEM attribute) 40tag (gluonhtmlEMBED attribute) 40tag (gluonhtmlFIELDSET attribute) 40tag (gluonhtmlFORM attribute) 41tag (gluonhtmlH1 attribute) 42tag (gluonhtmlH2 attribute) 42tag (gluonhtmlH3 attribute) 42tag (gluonhtmlH4 attribute) 42tag (gluonhtmlH5 attribute) 42tag (gluonhtmlH6 attribute) 42tag (gluonhtmlHEAD attribute) 42tag (gluonhtmlHR attribute) 42tag (gluonhtmlHTML attribute) 43tag (gluonhtmlI attribute) 43tag (gluonhtmlIFRAME attribute) 43tag (gluonhtmlIMG attribute) 43tag (gluonhtmlINPUT attribute) 44tag (gluonhtmlLABEL attribute) 44

tag (gluonhtmlLEGEND attribute) 44tag (gluonhtmlLI attribute) 44tag (gluonhtmlLINK attribute) 44tag (gluonhtmlMENU attribute) 45tag (gluonhtmlMETA attribute) 45tag (gluonhtmlOBJECT attribute) 45tag (gluonhtmlOL attribute) 44tag (gluonhtmlOPTGROUP attribute) 45tag (gluonhtmlOPTION attribute) 45tag (gluonhtmlP attribute) 45tag (gluonhtmlPRE attribute) 45tag (gluonhtmlSCRIPT attribute) 45tag (gluonhtmlSELECT attribute) 46tag (gluonhtmlSPAN attribute) 46tag (gluonhtmlSTRONG attribute) 46tag (gluonhtmlSTYLE attribute) 46tag (gluonhtmlTABLE attribute) 46tag (gluonhtmlTBODY attribute) 47tag (gluonhtmlTD attribute) 46tag (gluonhtmlTEXTAREA attribute) 46tag (gluonhtmlTFOOT attribute) 47tag (gluonhtmlTH attribute) 47tag (gluonhtmlTHEAD attribute) 47tag (gluonhtmlTITLE attribute) 47tag (gluonhtmlTR attribute) 47tag (gluonhtmlTT attribute) 47tag (gluonhtmlUL attribute) 44tag (gluonhtmlXHTML attribute) 49TAG (in module gluonhtml) 46tar() (in module gluonfileutils) 26tar_compiled() (in module gluonfileutils) 26Task (class in gluonscheduler) 81task_status() (gluonschedulerScheduler method) 81TaskReport (class in gluonscheduler) 82TBODY (class in gluonhtml) 47TD (class in gluonhtml) 46TemplateParser (class in gluontemplate) 114terminate() (gluonschedulerScheduler method) 81terminate_process() (gluonschedulerMetaScheduler

method) 78test() (in module gluoncompileapp) 13test() (in module gluonshell) 88TEXTAREA (class in gluonhtml) 46TextWidget (class in gluonsqlhtml) 103TFOOT (class in gluonhtml) 47TH (class in gluonhtml) 46THEAD (class in gluonhtml) 47THREAD_LOCAL (gluoncustom_importTrackImporter

attribute) 17TicketStorage (class in gluonrestricted) 69TimeWidget (class in gluonsqlhtml) 104TITLE (class in gluonhtml) 47title() (gluonutf8Utf8 method) 142to() (gluonhttpHTTP method) 51

188 Index

web2py Documentation Release 2146-stable

to_string() (gluontemplateTemplateParser method) 115Token (class in gluonnewcron) 63toolbar() (gluonglobalsResponse method) 29total_seconds() (gluonschedulerScheduler static

method) 81TR (class in gluonhtml) 47track_changes() (in module gluoncustom_import) 17TrackImporter (class in gluoncustom_import) 17transitional (gluonhtmlHTML attribute) 43transitional (gluonhtmlXHTML attribute) 49translate() (gluonlanguagestranslator method) 55translate() (gluonutf8Utf8 method) 142translator (class in gluonlanguages) 53truncate() (gluonsqlDALTable method) 92try_redirect_on_error() (in module gluonrewrite) 73try_rewrite_on_error() (in module gluonrewrite) 73try_start_scheduler() (gluonwidgetweb2pyDialog

method) 172try_stop_scheduler() (gluonwidgetweb2pyDialog

method) 172TT (class in gluonhtml) 47TYPE (class in gluonscheduler) 81

UUL (class in gluonhtml) 44unlock() (in module gluonportalocker) 66untar() (in module gluonfileutils) 26unzip() (in module gluonadmin) 5up() (in module gluonfileutils) 25update() (gluonhtmlDIV method) 40update() (gluonsqlDALTable method) 92update() (gluontoolsCrud method) 131update() (gluonwidgetweb2pyDialog method) 172update_all_languages() (in module gluonlanguages) 55update_canvas() (gluonwidgetweb2pyDialog method)

172update_dependencies() (gluonschedulerScheduler

method) 81update_groups() (gluontoolsAuth method) 128update_or_insert() (gluonsqlDALTable method) 92update_request() (gluonrewriteMapUrlIn method) 72update_schedulers() (gluonwidgetweb2pyDialog

method) 172upgrade() (in module gluonadmin) 5UploadWidget (class in gluonsqlhtml) 104upper() (gluonutf8Utf8 method) 142url() (gluontoolsAuth method) 128url() (gluontoolsCrud method) 131URL() (in module gluonhtml) 47url_in() (in module gluonrewrite) 73url_out() (in module gluonrewrite) 73urlify() (gluonvalidatorsIS_SLUG static method) 165user_agent() (gluonglobalsRequest method) 28user_group() (gluontoolsAuth method) 128

user_group_role() (gluontoolsAuth method) 128user_id (gluontoolsAuth attribute) 128Utf8 (class in gluonutf8) 139uuid (gluonglobalsRequest attribute) 28uuid() (gluonsqlDAL method) 95

Vvalidate() (gluonhtmlFORM method) 41validate() (gluonschedulerJobGraph method) 77validate() (gluonsqlDALField method) 91validate() (gluonsqlField method) 96validate_and_insert() (gluonsqlDALTable method) 92validate_and_update() (gluonsqlDALTable method) 92validate_and_update_or_insert() (gluonsqlDALTable

method) 92validate_args() (gluonrewriteMapUrlIn method) 72validators (gluonsqlDAL attribute) 95validators_method() (gluonsqlDAL method) 95vars (gluonglobalsRequest attribute) 28verify_email() (gluontoolsAuth method) 128VERIFY_SERVER (gluontoolsRecaptcha attribute)

129VERIFY_SERVER (gluontoolsRecaptcha2 attribute)

130Virtual (gluonsqlDALField attribute) 91Virtual (gluonsqlField attribute) 96

Ww2p_pack() (in module gluonfileutils) 26w2p_pack_plugin() (in module gluonfileutils) 26w2p_unpack() (in module gluonfileutils) 26w2p_unpack_plugin() (in module gluonfileutils) 26web2py_uuid() (in module gluonutils) 144web2pyDialog (class in gluonwidget) 171WebDebugger (class in gluondebug) 21when_is_logged_in_bypass_next_in_url()

(gluontoolsAuth method) 128where() (gluonsqlDAL method) 95widget() (gluonsqlhtmlBooleanWidget class method)

97widget() (gluonsqlhtmlCheckboxesWidget class

method) 97widget() (gluonsqlhtmlFormWidget class method) 99widget() (gluonsqlhtmlJSONWidget class method) 99widget() (gluonsqlhtmlListWidget class method) 99widget() (gluonsqlhtmlMultipleOptionsWidget class

method) 100widget() (gluonsqlhtmlOptionsWidget class method)

100widget() (gluonsqlhtmlPasswordWidget class method)

100widget() (gluonsqlhtmlRadioWidget class method) 100widget() (gluonsqlhtmlStringWidget class method) 103widget() (gluonsqlhtmlTextWidget class method) 104

Index 189

web2py Documentation Release 2146-stable

widget() (gluonsqlhtmlUploadWidget class method)104

widgets (gluonsqlhtmlSQLFORM attribute) 103Wiki (class in gluontools) 135wiki() (gluontoolsAuth method) 129wikimenu() (gluontoolsAuth method) 129with_alias() (gluonsqlDALTable method) 92with_prefix() (gluoncacheCache static method) 8wrapped_assign_tasks() (gluonschedulerScheduler

method) 81wrapped_pop_task() (gluonschedulerScheduler

method) 81wrapped_report_task() (gluonschedulerScheduler

method) 81write() (gluondebugPipe method) 21write() (gluonglobalsResponse method) 29write() (gluonportalockerLockedFile method) 66write() (gluontemplateDummyResponse method) 114write() (gluonwidgetIO method) 171write_file() (in module gluonfileutils) 25write_locked() (in module gluonportalocker) 66wsgibase() (in module gluonmain) 57

XXHTML (class in gluonhtml) 49XML (class in gluonhtml) 49xml() (gluonhtmlA method) 35xml() (gluonhtmlCODE method) 37xml() (gluonhtmlDIV method) 40xml() (gluonhtmlFORM method) 42xml() (gluonhtmlHTML method) 43xml() (gluonhtmlINPUT method) 44xml() (gluonhtmlMARKMIN method) 44xml() (gluonhtmlMENU method) 45xml() (gluonhtmlP method) 45xml() (gluonhtmlSCRIPT method) 45xml() (gluonhtmlSTYLE method) 46xml() (gluonhtmlXHTML method) 49xml() (gluonhtmlXML method) 50xml() (gluontemplateNOESCAPE method) 114xml() (gluontoolsRecaptcha method) 129xml() (gluontoolsRecaptcha2 method) 130xml() (gluontoolsService method) 134xml() (in module gluonserializers) 83xml_rec() (in module gluonserializers) 83xmlescape() (in module gluonhtml) 50xmlns (gluonhtmlXHTML attribute) 49xmlrpc() (gluonglobalsResponse method) 29xmlrpc() (gluontoolsService method) 134

Yyaml() (in module gluonserializers) 83

Zzfill() (gluonutf8Utf8 method) 142

190 Index

  • admin Module
    • Utility functions for the Admin application
      • cache Module
        • Basic caching classes and methods
          • cfs Module
            • Functions required to execute app components
              • compileapp Module
                • Functions required to execute app components
                  • contenttype Module
                  • custom_import Module
                    • Support for smart import syntax for web2py applications
                      • dal Module
                        • Takes care of adapting pyDAL to web2pyrsquos needs
                          • debug Module
                            • Debugger support classes
                              • decoder Module
                              • fileutils Module
                                • File operations
                                  • globals Module
                                  • highlight Module
                                  • html Module
                                    • Template helpers
                                      • http Module
                                        • HTTP statuses helpers
                                          • languages Module
                                            • Translation system
                                              • main Module
                                                • The gluon wsgi application
                                                  • messageboxhandler Module
                                                  • myregex Module
                                                    • Useful regexes
                                                      • newcron Module
                                                      • portalocker Module
                                                      • recfile Module
                                                        • Generates names for cache and session files
                                                          • restricted Module
                                                            • Restricted environment to execute applicationrsquos code
                                                              • rewrite Module
                                                              • sanitizer Module
                                                                • Cross-site scripting (XSS) defense
                                                                  • scheduler Module
                                                                    • Background processes made simple
                                                                      • serializers Module
                                                                      • settings Module
                                                                      • shell Module
                                                                        • Web2py environment in the shell
                                                                          • sql Module
                                                                            • Just for backward compatibility
                                                                              • sqlhtml Module
                                                                              • storage Module
                                                                              • streamer Module
                                                                                • Facilities to handle file streaming
                                                                                  • template Module
                                                                                    • Templating syntax
                                                                                      • tools Module
                                                                                        • Auth Mail PluginManager and various utilities
                                                                                          • utf8 Module
                                                                                            • Utilities and class for UTF8 strings managing
                                                                                              • utils Module
                                                                                                • This file specifically includes utilities for security
                                                                                                  • validators Module
                                                                                                    • Validators
                                                                                                      • widget Module
                                                                                                        • The widget is called from web2py
                                                                                                          • xmlrpc Module
                                                                                                          • Indices and tables
                                                                                                          • Python Module Index
Page 7: web2py Documentation - Read the Docs

web2py Documentation Release 2146-stable

2 Contents

CHAPTER 1

admin Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

11 Utility functions for the Admin application

gluonadminadd_path_first(path)

gluonadminapath(path=rdquo r=None)Builds a path inside an application folder

Parameters

bull path (str) ndash path within the application folder

bull r ndash the global request object

gluonadminapp_cleanup(app request)Removes session cache and error files

Parameters

bull app (str) ndash application name

bull request ndash the global request object

Returns True if everything went ok False otherwise

gluonadminapp_compile(app request skip_failed_views=False)Compiles the application

Parameters

bull app (str) ndash application name

bull request ndash the global request object

3

web2py Documentation Release 2146-stable

Returns None if everything went ok traceback text if errors are found

gluonadminapp_create(app request force=False key=None info=False)Create a copy of welcomew2p (scaffolding) app

Parameters

bull app (str) ndash application name

bull request ndash the global request object

gluonadminapp_install(app fobj request filename overwrite=None)Installs an application

bull Identifies file type by filename

bull Writes fobj contents to the deposit folder

bull Calls w2p_unpack() to do the job

Parameters

bull app (str) ndash new application name

bull fobj (obj) ndash file object containing the application to be installed

bull request ndash the global request object

bull filename (str) ndash original filename of the fobj required to determine extension

bull overwrite (bool) ndash force overwrite of existing application

Returns name of the file where app is temporarily stored or None on failure

gluonadminapp_pack(app request raise_ex=False filenames=None)Builds a w2p package for the application

Parameters

bull app (str) ndash application name

bull request ndash the global request object

Returns filename of the w2p file or None on error

gluonadminapp_pack_compiled(app request raise_ex=False)Builds a w2p bytecode-compiled package for the application

Parameters

bull app (str) ndash application name

bull request ndash the global request object

Returns filename of the w2p file or None on error

gluonadminapp_uninstall(app request)Uninstalls the application

Parameters

bull app (str) ndash application name

bull request ndash the global request object

Returns True on success False on failure

4 Chapter 1 admin Module

web2py Documentation Release 2146-stable

gluonadmincheck_new_version(myversion version_url)Compares current web2pyrsquos version with the latest stable web2py version

Parameters

bull myversion ndash the current version as stored in file web2pyVERSION

bull version_URL ndash the URL that contains the version of the latest stable release

Returns

state version

bull state True if upgrade available False if current version is up-to-date -1 on error

bull version the most up-to-version available

Return type tuple

gluonadmincreate_missing_app_folders(request)

gluonadmincreate_missing_folders()

gluonadminplugin_install(app fobj request filename)Installs a plugin

bull Identifies file type by filename

bull Writes fobj contents to the deposit folder

bull Calls w2p_unpack_plugin() to do the job

Parameters

bull app (str) ndash new application name

bull fobj ndash file object containing the application to be installed

bull request ndash the global request object

bull filename ndash original filename of the fobj required to determine extension

Returns name of the file where plugin is temporarily stored or False on failure

gluonadminplugin_pack(app plugin_name request)Builds a w2p package for the plugin

Parameters

bull app (str) ndash application name

bull plugin_name (str) ndash the name of the plugin without plugin_ prefix

bull request ndash the current request app

Returns filename of the w2p file or False on error

gluonadminunzip(filename dir subfolder=rdquo)Unzips filename into dir (zip only no gz etc)

Parameters

bull filename (str) ndash archive

bull dir (str) ndash destination

bull subfolder (str) ndash if = lsquorsquo unzips only files in subfolder

11 Utility functions for the Admin application 5

web2py Documentation Release 2146-stable

gluonadminupgrade(request url=rsquohttpweb2pycomrsquo)Upgrades web2py (src osx win) if a new version is posted It detects whether src osx or win is running anddownloads the right one

Parameters

bull request ndash the current request object (required to determine version and path)

bull url ndash the incomplete url where to locate the latest web2py (actual url isurl+rsquoexamplesstaticweb2py_(src|osx|win)ziprsquo)

Returns tuple completed traceback

bull completed True on success False on failure (network problem or old version)

bull traceback None on success raised exception details on failure

6 Chapter 1 admin Module

CHAPTER 2

cache Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

21 Basic caching classes and methods

bull Cache - The generic caching object interfacing with the others

bull CacheInRam - providing caching in ram

bull CacheOnDisk - provides caches on disk

Memcache is also available via a different module (see gluoncontribmemcache)

When web2py is running on Google App Engine caching will be provided by the GAE memcache (seegluoncontribgae_memcache)

class gluoncacheCache(request)Bases object

Sets up generic caching creating an instance of both CacheInRam and CacheOnDisk In case of GAE will makeuse of gluoncontribgae_memcache

bull selfram is an instance of CacheInRam

bull selfdisk is an instance of CacheOnDisk

action(time_expire=300 cache_model=None prefix=None session=False vars=True lang=Trueuser_agent=False public=True valid_statuses=None quick=None)

Better fit for caching an action

Warning Experimental

7

web2py Documentation Release 2146-stable

Currently only HTTP 11 compliant reference httpcodegooglecompdoctype-mirrorwikiArticleHttpCaching

Parameters

bull time_expire (int) ndash same as cache

bull cache_model (str) ndash same as cache

bull prefix (str) ndash add a prefix to the calculated key

bull session (bool) ndash adds responsesession_id to the key

bull vars (bool) ndash adds requestenvquery_string

bull lang (bool) ndash adds Taccepted_language

bull user_agent (bool or dict) ndash if True adds is_mobile and is_tablet tothe key Pass a dict to use all the needed values (uses str(items())) (eguser_agent=requestuser_agent()) Used only if session is not True

bull public (bool) ndash if False forces the Cache-Control to be lsquoprivatersquo

bull valid_statuses ndash by default only status codes starting with 123 will be cached passan explicit list of statuses on which turn the cache on

bull quick ndash SessionVarsLangUser-agentPublic fast overrides with initials eg lsquoSVLPrsquoor lsquoVLPrsquo or lsquoVLPrsquo

autokey = (name)s(args)s(vars)s

static with_prefix(cache_model prefix)allow replacing cacheram with cachewith_prefix(cacheramrsquoprefixrsquo) it will add prefix to all the cachekeys used

gluoncachelazy_cache(key=None time_expire=None cache_model=rsquoramrsquo)Can be used to cache any function including ones in modules as long as the cached function is only calledwithin a web2py request

If a key is not provided one is generated from the function name time_expire defaults to None (no cacheexpiration)

If cache_model is ldquoramrdquo then the model is currentcacheram etc

8 Chapter 2 cache Module

CHAPTER 3

cfs Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

31 Functions required to execute app components

Note FOR INTERNAL USE ONLY

gluoncfsgetcfs(key filename filter=None)Caches the filtered file filename with key until the file is modified

Parameters

bull key (str) ndash the cache key

bull filename ndash the file to cache

bull filter ndash is the function used for filtering Normally filename is a py file and filter is afunction that bytecode compiles the file In this way the bytecode compiled file is cached(Default = None)

This is used on Google App Engine since pyc files cannot be saved

9

web2py Documentation Release 2146-stable

10 Chapter 3 cfs Module

CHAPTER 4

compileapp Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

41 Functions required to execute app components

Note FOR INTERNAL USE ONLY

gluoncompileappLOAD(c=None f=rsquoindexrsquo args=None vars=None extension=None target=Noneajax=False ajax_trap=False url=None user_signature=False time-out=None times=1 content=rsquoloadingrsquo post_vars= attr)

LOADs a component into the actionrsquos document

Parameters

bull c (str) ndash controller

bull f (str) ndash function

bull args (tuple or list) ndash arguments

bull vars (dict) ndash vars

bull extension (str) ndash extension

bull target (str) ndash id of the target

bull ajax (bool) ndash True to enable AJAX bahaviour

bull ajax_trap (bool) ndash True if ajax is set to True traps both links and forms ldquoinsiderdquo thetarget

bull url (str) ndash overrides clsquoflsquolsquoargslsquo and vars

11

web2py Documentation Release 2146-stable

bull user_signature (bool) ndash adds hmac signature to all links with a key that is differentfor every user

bull timeout (int) ndash in milliseconds specifies the time to wait before starting the request orthe frequency if times is greater than 1 or ldquoinfinityrdquo

bull times (integer or str) ndash how many times the component will be requested ldquoinfin-ityrdquo or ldquocontinuousrdquo are accepted to reload indefinitely the component

class gluoncompileappLoadFactory(environment)Bases object

Attention this helper is new and experimental

gluoncompileappbuild_environment(request response session store_current=True)Build the environment dictionary into which web2py files are executed

gluoncompileappcompile_application(folder skip_failed_views=False)Compiles all models views controller for the application in folder

gluoncompileappcompile_controllers(folder)Compiles all the controllers in the application specified by folder

gluoncompileappcompile_models(folder)Compiles all the models in the application specified by folder

gluoncompileappcompile_views(folder skip_failed_views=False)Compiles all the views in the application specified by folder

gluoncompileappfind_exposed_functions(data)

gluoncompileapplocal_import_aux(name reload_force=False app=rsquowelcomersquo)In apps instead of importing a local module (in applicationsappmodules) with

import abc as d

you should do

d = local_import(abc)

or (to force a reload)

d = local_import(lsquoabcrsquo reload=True)

This prevents conflict between applications and un-necessary execs It can be used to import any moduleincluding regular Python modules

gluoncompileappmodel_cmp(a b sep=rsquorsquo)

gluoncompileappmodel_cmp_sep(a b sep=rsquorsquo)

class gluoncompileappmybuiltinBases object

NOTE could simple use a dict and populate it NOTE not sure if this changes things though if monkey patchingimport

gluoncompileappre_compile(regex)

gluoncompileappread_pyc(filename)Read the code inside a bytecode compiled file if the MAGIC number is compatible

Returns a code object

12 Chapter 4 compileapp Module

web2py Documentation Release 2146-stable

gluoncompileappremove_compiled_application(folder)Deletes the folder compiled containing the compiled application

gluoncompileapprun_controller_in(controller function environment)Runs the controllerfunction() (for the app specified by the current folder) It tries pre-compiled con-troller_functionpyc first before compiling it

gluoncompileapprun_models_in(environment)Runs all models (in the app specified by the current folder) It tries pre-compiled models first before compilingthem

gluoncompileapprun_view_in(environment)Executes the view for the requested action The view is the one specified in responseview or determined by theurl or viewgenericextension It tries the pre-compiled views_controller_functionpyc before compiling it

gluoncompileappsave_pyc(filename)Bytecode compiles the file filename

gluoncompileapptest()Example

gtgtgt import traceback typesgtgtgt environment=x1gtgtgt open(apy w)write(print 1x)gtgtgt save_pyc(apy)gtgtgt osunlink(apy)gtgtgt if type(read_pyc(apyc))==typesCodeType print codecodegtgtgt exec read_pyc(apyc) in environment1

41 Functions required to execute app components 13

web2py Documentation Release 2146-stable

14 Chapter 4 compileapp Module

CHAPTER 5

contenttype Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

CONTENT_TYPE dictionary created against freedesktoporgrsquos shared mime info database version 11

Deviations from official standards

bull md applicationx-genesis-rom ndashgt textx-markdown

bull png imagex-apple-ios-png ndashgt imagepng

Additions

bull load texthtml

bull json applicationjson

bull jsonp applicationjsonp

bull pickle applicationpython-pickle

bull w2prsquo applicationw2p

gluoncontenttypecontenttype(filename default=rsquotextplainrsquo)Returns the Content-Type string matching extension of the given filename

15

web2py Documentation Release 2146-stable

16 Chapter 5 contenttype Module

CHAPTER 6

custom_import Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

61 Support for smart import syntax for web2py applications

exception gluoncustom_importCustomImportExceptionBases exceptionsImportError

class gluoncustom_importTrackImporterBases object

An importer tracking the date of the module files and reloading them when they are changed

PACKAGE_PATH_SUFFIX = __init__py

THREAD_LOCAL = ltthread_local objectgt

gluoncustom_importcustom_import_install()

gluoncustom_importcustom_importer(name globals=None locals=None fromlist=Nonelevel=-1)

web2pyrsquos custom importer It behaves like the standard Python importer but it tries to transform importstatements as something like ldquoimport applicationsapp_namemodulesxrdquo If the import fails it falls back onnaive_importer

gluoncustom_importis_tracking_changes()

gluoncustom_importtrack_changes(track=True)

17

web2py Documentation Release 2146-stable

18 Chapter 6 custom_import Module

CHAPTER 7

dal Module

Go to httppydalreadthedocsorgenlatest for docs on pyDAL

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

71 Takes care of adapting pyDAL to web2pyrsquos needs

19

web2py Documentation Release 2146-stable

20 Chapter 7 dal Module

CHAPTER 8

debug Module

This file is part of the web2py Web FrameworkDeveloped by Massimo Di Pierro ltmdipierrocsdepauledugtlimodou ltlimodougmailcomgt and srackham ltsrackhamgmailcomgtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

81 Debugger support classes

class gluondebugPipe(name mode=rsquorrsquo args kwargs)Bases QueueQueue

flush()

read(count=None timeout=None)

readline()

write(data)

class gluondebugWebDebugger(pipe completekey=rsquotabrsquo stdin=None stdout=None)Bases gluoncontribqdbFrontend

Qdb web2py interface

clear_interaction()

do_continue(args kwargs)

do_exec(statement)

do_next(args kwargs)

do_quit(args kwargs)

do_return(args kwargs)

do_step(args kwargs)

21

web2py Documentation Release 2146-stable

exception(title extype exvalue trace request)Show a user_exception

interaction(filename lineno line context)

run()Main method dispatcher (infinite loop)

gluondebugcheck_interaction(fn)Decorator to clean and prevent interaction when not available

gluondebugcommunicate(command=None)send command to debbuger wait result

gluondebugset_trace()breakpoint shortcut (like pdb)

gluondebugstop_trace()stop waiting for the debugger (called atexit)

22 Chapter 8 debug Module

CHAPTER 9

decoder Module

Caller will hand this library a buffer and ask it to either convert it or auto-detect the type

Based on httpcodeactivestatecomrecipes52257

Licensed under the PSF License

gluondecoderautoDetectXMLEncoding(buffer)buffer -gt encoding_name The buffer should be at least 4 bytes long Returns None if encoding cannot bedetected Note that encoding_name might not have an installed decoder (eg EBCDIC)

gluondecoderdecoder(buffer)

23

web2py Documentation Release 2146-stable

24 Chapter 9 decoder Module

CHAPTER 10

fileutils Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

101 File operations

gluonfileutilsparse_version(version)Attempts to parse SemVer fallbacks on legacy

gluonfileutilsread_file(filename mode=rsquorrsquo)Returns content from filename making sure to close the file explicitly on exit

gluonfileutilswrite_file(filename value mode=rsquowrsquo)Writes ltvaluegt to filename making sure to close the file explicitly on exit

gluonfileutilsreadlines_file(filename mode=rsquorrsquo)Applies split(lsquo lsquo) to the output of read_file()

gluonfileutilsup(path)

gluonfileutilsabspath(relpath base)Converts relative path to absolute path based (by default) on applications_parent

gluonfileutilsmktree(path)

gluonfileutilslistdir(path expression=rsquo^+$rsquo drop=True add_dirs=False sort=Truemaxnum=None exclude_content_from=None)

Like oslistdir() but you can specify a regex pattern to filter files If add_dirs is True the returned items willhave the full path

gluonfileutilsrecursive_unlink(f)Deletes f If itrsquos a folder also its contents will be deleted

gluonfileutilscleanpath(path)Turns any expressionpath into a valid filename replaces with _ and removes special characters

25

web2py Documentation Release 2146-stable

gluonfileutilstar(file dir expression=rsquo^+$rsquo filenames=None exclude_content_from=None)Tars dir into file only tars file that match expression

gluonfileutilsuntar(file dir)Untar file into dir

gluonfileutilstar_compiled(file dir expression=rsquo^+$rsquo exclude_content_from=None)Used to tar a compiled application The content of models views controllers is not stored in the tar file

gluonfileutilsget_session(request other_application=rsquoadminrsquo)Checks that user is authorized to access other_application

gluonfileutilscheck_credentials(request other_application=rsquoadminrsquo expiration=3600gae_login=True)

Checks that user is authorized to access other_application

gluonfileutilsw2p_pack(filename path compiled=False filenames=None)Packs a web2py application

Parameters

bull filename (str) ndash path to the resulting archive

bull path (str) ndash path to the application

bull compiled (bool) ndash if True packs the compiled version

bull filenames (list) ndash adds filenames to the archive

gluonfileutilsw2p_unpack(filename path delete_tar=True)

gluonfileutilsw2p_pack_plugin(filename path plugin_name)Packs the given plugin into a w2p file Will match files at

ltpathgtplugin_[name]ltpathgtplugin_[name]

gluonfileutilsw2p_unpack_plugin(filename path delete_tar=True)

gluonfileutilsfix_newlines(path)

gluonfileutilsmake_fake_file_like_object()

26 Chapter 10 fileutils Module

CHAPTER 11

globals Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

Contains the classes for the global used variables

bull Request

bull Response

bull Session

class gluonglobalsRequest(env)Bases gluonstorageStorage

Defines the request object and the default values of its members

bull env environment variables by gluonmainwsgibase()

bull cookies

bull get_vars

bull post_vars

bull vars

bull folder

bull application

bull function

bull args

bull extension

bull now datetimedatetimenow()

27

web2py Documentation Release 2146-stable

bull utcnow datetimedatetimeutcnow()

bull is_local

bull is_https

bull restful()

body

compute_uuid()

get_varsLazily parses the query string into get_vars

parse_all_vars()Merges get_vars and post_vars to vars

parse_get_vars()Takes the QUERY_STRING and unpacks it to get_vars

parse_post_vars()Takes the body of the request and unpacks it into post_vars applicationjson is also automatically parsed

post_varsLazily parse the body into post_vars

requires_https()If request comes in over HTTP redirects it to HTTPS and secures the session

restful()

user_agent()

uuidLazily uuid

varsLazily parses all get_vars and post_vars to fill vars

class gluonglobalsResponseBases gluonstorageStorage

Defines the response object and the default values of its members responsewrite( ) can be used to write in theoutput html

download(request db chunk_size=65536 attachment=True download_filename=None)Example of usage in controller

def download()return responsedownload(request db)

Downloads from http downloadfilename

include_files(extensions=None)Includes files (usually in the head) Can minify and cache local files By default caches in ram for 5minutes To change responsecache_includes = (cache_method time_expire) Example (cachedisk 60) caches to disk for 1 minute

include_meta()

json(data default=None)

render(a b)

28 Chapter 11 globals Module

web2py Documentation Release 2146-stable

stream(stream chunk_size=65536 request=None attachment=False filename=None)If in a controller function

return responsestream(file 100)

the file content will be streamed at 100 bytes at the time

Parameters

bull stream ndash filename or read()able content

bull chunk_size (int) ndash Buffer size

bull request ndash the request object

bull attachment (bool) ndash prepares the correct headers to download the file as an attach-ment Usually creates a pop-up download window on browsers

bull filename (str) ndash the name for the attachment

Note for using the stream name (filename) with attachments the option must be explicitly set as functionparameter (will default to the last request argument otherwise)

toolbar()

write(data escape=True)

xmlrpc(request methods)assuming

def add(a b)return a+b

if a controller function ldquofuncrdquo

return responsexmlrpc(request [add])

the controller will be able to handle xmlrpc requests for the add function Example

import xmlrpclibconnection = xmlrpclibServerProxy(

httphostnameappcontrfunc)print connectionadd(3 4)

class gluonglobalsSessionBases gluonstorageStorage

Defines the session object and the default values of its members (None)

bull session_storage_type lsquofilersquo lsquodbrsquo or lsquocookiersquo

bull session_cookie_compression_level

bull session_cookie_expires cookie expiration

bull session_cookie_key for encrypted sessions in cookies

bull session_id a number or None if no session

bull session_id_name

bull session_locked

29

web2py Documentation Release 2146-stable

bull session_masterapp

bull session_new a new session obj is being created

bull session_hash hash of the pickled loaded session

bull session_pickled picked session

if session in cookie

bull session_data_name name of the cookie for session data

if session in db

bull session_db_record_id

bull session_db_table

bull session_db_unique_key

if session in file

bull session_file

bull session_filename

clear()rarr None Remove all items from D

clear_session_cookies()

connect(request=None response=None db=None tablename=rsquoweb2py_sessionrsquo master-app=None migrate=True separate=None check_client=False cookie_key=Nonecookie_expires=None compression_level=None)

Used in models allows to customize Session handling

Parameters

bull request ndash the request object

bull response ndash the response object

bull db ndash to storeretrieve sessions in db (a table is created)

bull tablename (str) ndash table name

bull masterapp (str) ndash points to anotherrsquos app sessions This enables a ldquoSSOrdquo environmentamong apps

bull migrate ndash passed to the underlying db

bull separate ndash with True creates a folder with the 2 initials of the session id Can also bea function eg

separate=lambda(session_name) session_name[-2]

bull check_client ndash if True sessions can only come from the same ip

bull cookie_key (str) ndash secret for cookie encryption

bull cookie_expires ndash sets the expiration of the cookie

bull compression_level (int) ndash 0-9 sets zlib compression on the data before the en-cryption

forget(response=None)

is_expired(seconds=3600)

is_new()

30 Chapter 11 globals Module

web2py Documentation Release 2146-stable

renew(clear_session=False)

save_session_id_cookie()

secure()

31

web2py Documentation Release 2146-stable

32 Chapter 11 globals Module

CHAPTER 12

highlight Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

gluonhighlighthighlight(code language link=rsquoexamplesglobalsvarsrsquo counter=1styles=None highlight_line=None context_lines=None at-tributes=None)

33

web2py Documentation Release 2146-stable

34 Chapter 12 highlight Module

CHAPTER 13

html Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

131 Template helpers

class gluonhtmlA(components attributes)Bases gluonhtmlDIV

Generates an A() link A() in web2py is really important and with the included web2pyjs allows lots of Ajaxinteractions in the page

On top of ldquousualrdquo _attributes it takes

Parameters

bull callback ndash an url to call but not redirect to

bull cid ndash if you want to load the _href into an element of the page (component) pass its id(without the ) here

bull delete ndash element to delete after calling callback

bull target ndash same thing as cid

bull confirm ndash text to display upon a callback with a delete

bull noconfirm ndash donrsquot display alert upon a callback with delete

tag = a

xml()generates the xml for this component

gluonhtmlASSIGNJS(kargs)

35

web2py Documentation Release 2146-stable

Example

ASSIGNJS(var1=lsquo1rsquo var2=lsquo2rsquo) will return the following javascript variables assignations

var var1 = ldquo1rdquo var var2 = ldquo2rdquo

Parameters kargs ndash Any keywords arguments and assigned values

Returns Javascript vars assignations for the keyvalue passed

class gluonhtmlB(components attributes)Bases gluonhtmlDIV

tag = b

class gluonhtmlBEAUTIFY(component attributes)Bases gluonhtmlDIV

Turns any list dictionary etc into decent looking html

Two special attributes are

bull sorted a function that takes the dict and returned sorted keys

bull keyfilter a function that takes a key and returns its representation or None if the key is to be skipped Bydefault key[1]==rsquo_rsquo is skipped

Examples

gtgtgt BEAUTIFY([a b hello world])xml()ltdivgtlttablegtlttrgtlttdgtltdivgtaltdivgtlttdgtlttrgtlttrgtlttdgtltdivgtbltdivgtlttdgtlttrgtlttrgtlttdgtrarr˓ltdivgtlttablegtlttrgtlttd style=font-weightboldvertical-aligntopgthellolttdgtlttdrarr˓style=vertical-aligntopgtlttdgtlttdgtltdivgtworldltdivgtlttdgtlttrgtlttablegtltdivgtltrarr˓tdgtlttrgtlttablegtltdivgt

static no_underscore(key)

tag = div

class gluonhtmlBODY(components attributes)Bases gluonhtmlDIV

tag = body

class gluonhtmlBR(components attributes)Bases gluonhtmlDIV

tag = br

class gluonhtmlBUTTON(components attributes)Bases gluonhtmlDIV

tag = button

class gluonhtmlCENTER(components attributes)Bases gluonhtmlDIV

tag = center

class gluonhtmlCAT(components attributes)Bases gluonhtmlDIV

tag =

36 Chapter 13 html Module

web2py Documentation Release 2146-stable

class gluonhtmlCODE(components attributes)Bases gluonhtmlDIV

Displays code in HTML with syntax highlighting

Parameters

bull language ndash indicates the language otherwise PYTHON is assumed

bull link ndash can provide a link

bull styles ndash for styles

Examples

=CODE(ldquoprint lsquohello worldrsquordquo language=rsquopythonrsquo link=None counter=1 styles= high-light_line=None)

supported languages are

ldquopythonrdquo ldquohtml_plainrdquo ldquocrdquo ldquocpprdquo ldquoweb2pyrdquo ldquohtmlrdquo

The ldquohtmlrdquo language interprets and tags as ldquoweb2pyrdquo code ldquohtml_plainrdquo doesnrsquot

if a link=rsquoexamplesglobalvarsrsquo is provided web2py keywords are linked to the online docs

the counter is used for line numbering counter can be None or a prompt string

xml()generates the xml for this component

class gluonhtmlCOL(components attributes)Bases gluonhtmlDIV

tag = col

class gluonhtmlCOLGROUP(components attributes)Bases gluonhtmlDIV

tag = colgroup

class gluonhtmlDIV(components attributes)Bases gluonhtmlXmlComponent

HTML helper for easy generating and manipulating a DOM structure Little or no validation is done

Behaves like a dictionary regarding updating of attributes Behaves like a list regarding insertingappendingcomponents

Examples

gtgtgt DIV(hello world _style=colorred)xml()ltdiv style=colorredgthelloworldltdivgt

All other HTML helpers are derived from DIV

_something=rdquovaluerdquo attributes are transparently translated into something=rdquovaluerdquo HTML attributes

append(value)list style appending of components

Examples

131 Template helpers 37

web2py Documentation Release 2146-stable

gtgtgt a=DIV()gtgtgt aappend(SPAN(x))gtgtgt print altdivgtltspangtxltspangtltdivgt

element(args kargs)Finds the first component that matches the supplied attribute dictionary or None if nothing could be found

Also the components of the components are searched

elements(args kargs)Find all components that match the supplied attribute dictionary or None if nothing could be found

All components of the components are searched

Examples

gtgtgt a = DIV(DIV(SPAN(x)3DIV(SPAN(y))))gtgtgt for c in aelements(span first_only=True) c[0]=zgtgtgt print altdivgtltdivgtltspangtzltspangt3ltdivgtltspangtyltspangtltdivgtltdivgtltdivgtgtgtgt for c in aelements(span) c[0]=zgtgtgt print altdivgtltdivgtltspangtzltspangt3ltdivgtltspangtzltspangtltdivgtltdivgtltdivgt

It also supports a syntax compatible with jQuery

Examples

gtgtgt a=TAG(ltdivgtltspangtlta id=1-1 uv=$gthelloltagtltspangtltp class=this is ararr˓testgtworldltpgtltdivgt)gtgtgt for e in aelements(div a1-1 pis) print eflatten()helloworldgtgtgt for e in aelements(1-1) print eflatten()hellogtgtgt aelements(a[uv=$])[0]xml()lta id=1-1 uv=$gthelloltagtgtgtgt a=FORM( INPUT(_type=text) SELECT(range(1)) TEXTAREA() )gtgtgt for c in aelements(input select textarea) c[_disabled] = disabledrarr˓gtgtgt axml()ltform action= enctype=multipartform-data method=postgtltinput disabled=rarr˓disabled type=text gtltselect disabled=disabledgtltoption value=0gt0ltrarr˓optiongtltselectgtlttextarea cols=40 disabled=disabled rows=10gtltrarr˓textareagtltformgt

Elements that are matched can also be replaced or removed by specifying a ldquoreplacerdquo argument (note alist of the original matching elements is still returned as usual)

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=abc) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(spanabc replace=P(x _class=xyz))gtgtgt print a We should xml() here instead of printltdivgtltdivgtltp class=xyzgtxltpgtltdivgtltp class=xyzgtxltpgtltp class=xyzgtxltpgtltrarr˓divgtltdivgtltdivgt

38 Chapter 13 html Module

web2py Documentation Release 2146-stable

ldquoreplacerdquo can be a callable which will be passed the original element and should return a new element toreplace it

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=abc) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(spanabc replace=lambda el P(el[0] _class=xyz))gtgtgt print altdivgtltdivgtltp class=xyzgtxltpgtltdivgtltp class=xyzgtyltpgtltp class=xyzgtzltpgtltrarr˓divgtltdivgtltdivgt

If replace=None matching elements will be removed completely

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=abc) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(span find=y replace=None)gtgtgt print altdivgtltdivgtltspan class=abcgtxltspangtltdivgtltspan class=abcgtzltspangtltdivgtltrarr˓divgtltdivgt

If a ldquofind_textrdquo argument is specified elements will be searched for text components that match find_textand any matching text components will be replaced (find_text is ignored if ldquoreplacerdquo is not also specified)Like the ldquofindrdquo argument ldquofind_textrdquo can be a string or a compiled regex

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=abc) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(find_text=recompile(x|y|z) replace=hello)gtgtgt print altdivgtltdivgtltspan class=abcgthelloltspangtltdivgtltspan class=abcgthelloltspangtrarr˓ltspan class=abcgthelloltspangtltdivgtltdivgtltdivgt

If other attributes are specified along with find_text then only components that match the specified at-tributes will be searched for find_text

Examples

gtgtgt a = DIV(DIV(SPAN(x _class=abc) DIV(SPAN(y _class=efg) SPAN(zrarr˓ _class=abc))))gtgtgt b = aelements(spanefg find_text=recompile(x|y|z) replace=hello)gtgtgt print altdivgtltdivgtltspan class=abcgtxltspangtltdivgtltspan class=efggthelloltspangtltspanrarr˓class=abcgtzltspangtltdivgtltdivgtltdivgt

flatten(render=None)Returns the text stored by the DIV object rendered by the render function the render function must taketext tagname and attributes render=None is equivalent to render=lambda text tag attr text

Examples

gtgtgt markdown = lambda text tag=None attributes=rarr˓None resub(s+ text) h1+text+nnrarr˓ ptext+nget(tagtext)gtgtgt a=TAG(lth1gtHeaderlth1gtltpgtthis is a testltpgt)gtgtgt aflatten(markdown)Headernnthis is a testn

131 Template helpers 39

web2py Documentation Release 2146-stable

get(i)

insert(i value)List-style inserting of components

Examples

gtgtgt a=DIV()gtgtgt ainsert(0 SPAN(x))gtgtgt print altdivgtltspangtxltspangtltdivgt

regex_attr = lt_sreSRE_Pattern objectgt

regex_class = lt_sreSRE_Pattern objectgt

regex_id = lt_sreSRE_Pattern objectgt

regex_tag = lt_sreSRE_Pattern objectgt

sibling(args kargs)Finds the first sibling component that match the supplied argument list and attribute dictionary or None ifnothing could be found

siblings(args kargs)Finds all sibling components that match the supplied argument list and attribute dictionary or None ifnothing could be found

tag = div

update(kargs)dictionary like updating of the tag attributes

xml()generates the xml for this component

class gluonhtmlEM(components attributes)Bases gluonhtmlDIV

tag = em

class gluonhtmlEMBED(components attributes)Bases gluonhtmlDIV

tag = embed

class gluonhtmlFIELDSET(components attributes)Bases gluonhtmlDIV

tag = fieldset

class gluonhtmlFORM(components attributes)Bases gluonhtmlDIV

Examples

gtgtgt from validators import IS_NOT_EMPTYgtgtgt form=FORM(INPUT(_name=test requires=IS_NOT_EMPTY()))gtgtgt formxml()ltform action= enctype=multipartform-data method=postgtltinput name=testrarr˓type=text gtltformgt

a FORM is container for INPUT TEXTAREA SELECT and other helpers

form has one important method

40 Chapter 13 html Module

web2py Documentation Release 2146-stable

formaccepts(requestvars session)

if form is accepted (and all validators pass) formvars contains the accepted vars otherwise formerrors containsthe errors in case of errors the form is modified to present the errors to the user

REDIRECT_JS = windowlocation=sreturn false

accepts(request_vars session=None formname=rsquodefaultrsquo keepvalues=False onvalidation=Nonehideerror=False kwargs)

kwargs is not used but allows to specify the same interface for FORM and SQLFORM

add_button(value url _class=None)

as_dict(flat=False sanitize=True)EXPERIMENTAL

Sanitize is naive It should catch any unsafe value for client retrieval

as_json(sanitize=True)

as_xml(sanitize=True)

as_yaml(sanitize=True)

assert_status(status request_vars)

static confirm(text=rsquoOKrsquo buttons=None hidden=None)

hidden_fields()

process(kwargs)Perform the validate() method but returns the form

Usage in controllers

directly on returndef action()

some code herereturn dict(form=FORM()process())

You can use it with FORM SQLFORM or FORM based plugins

responseflash messagesdef action()

form = SQLFORM(dbtable)process(message_onsuccess=Sucess)return dict(form=form)

callback function callback receives True or False as first arg and a list of argsdef my_callback(status msg)

responseflash = Success +msg if status else Errors occured

after argument can be flash to responseflash messages or a function name to use as callback or None to do nothingdef action()

return dict(form=SQLFORM(dbtable)process(onsuccess=my_callback)

tag = form

validate(kwargs)This function validates the form you can use it instead of directly formaccepts

Usage In controller

131 Template helpers 41

web2py Documentation Release 2146-stable

def action()form=FORM(INPUT(_name=test requires=IS_NOT_EMPTY()))formvalidate() you can pass some args here - see belowreturn dict(form=form)

This can receive a bunch of arguments

onsuccess = lsquoflashrsquo - will show message_onsuccess in responseflash None - will do nothing can be afunction (lambda form pass)

onfailure = lsquoflashrsquo - will show message_onfailure in responseflash None - will do nothing can be afunction (lambda form pass)

onchange = lsquoflashrsquo - will show message_onchange in responseflash None - will do nothing can be afunction (lambda form pass)

message_onsuccess message_onfailure message_onchange next = where to redirect in case of success anyother kwargs will be passed for formaccepts( )

xml()generates the xml for this component

class gluonhtmlH1(components attributes)Bases gluonhtmlDIV

tag = h1

class gluonhtmlH2(components attributes)Bases gluonhtmlDIV

tag = h2

class gluonhtmlH3(components attributes)Bases gluonhtmlDIV

tag = h3

class gluonhtmlH4(components attributes)Bases gluonhtmlDIV

tag = h4

class gluonhtmlH5(components attributes)Bases gluonhtmlDIV

tag = h5

class gluonhtmlH6(components attributes)Bases gluonhtmlDIV

tag = h6

class gluonhtmlHEAD(components attributes)Bases gluonhtmlDIV

tag = head

class gluonhtmlHR(components attributes)Bases gluonhtmlDIV

tag = hr

class gluonhtmlHTML(components attributes)Bases gluonhtmlDIV

42 Chapter 13 html Module

web2py Documentation Release 2146-stable

There are four predefined document type definitions They can be specified in the lsquodoctypersquo parameter

bull lsquostrictrsquo enables strict doctype

bull lsquotransitionalrsquo enables transitional doctype (default)

bull lsquoframesetrsquo enables frameset doctype

bull lsquohtml5rsquo enables HTML 5 doctype

bull any other string will be treated as userrsquos own doctype

lsquolangrsquo parameter specifies the language of the document Defaults to lsquoenrsquo

See also DIV

frameset = ltDOCTYPE HTML PUBLIC -W3CDTD HTML 401 FramesetEN httpwwww3orgTRhtml4framesetdtdgtn

html5 = ltDOCTYPE HTMLgtn

strict = ltDOCTYPE HTML PUBLIC -W3CDTD HTML 401EN httpwwww3orgTRhtml4strictdtdgtn

tag = html

transitional = ltDOCTYPE HTML PUBLIC -W3CDTD HTML 401 TransitionalEN httpwwww3orgTRhtml4loosedtdgtn

xml()generates the xml for this component

class gluonhtmlI(components attributes)Bases gluonhtmlDIV

tag = i

class gluonhtmlIFRAME(components attributes)Bases gluonhtmlDIV

tag = iframe

class gluonhtmlIMG(components attributes)Bases gluonhtmlDIV

tag = img

class gluonhtmlINPUT(components attributes)Bases gluonhtmlDIV

INPUT Component

Takes two special attributes value= and requires=

Parameters

bull value ndash used to pass the initial value for the input field value differs from _value becauseit works for checkboxes radio textarea and selectoption too For a checkbox value shouldbe lsquorsquo or lsquoonrsquo For a radio or selectoption value should be the _value of the checkedselecteditem

bull requires ndash should be None or a validator or a list of validators for the value of the field

Examples

gtgtgt INPUT(_type=text _name=name value=Max)xml()ltinput name=name type=text value=Max gt

gtgtgt INPUT(_type=checkbox _name=checkbox value=on)xml()ltinput checked=checked name=checkbox type=checkbox value=on gt

131 Template helpers 43

web2py Documentation Release 2146-stable

gtgtgt INPUT(_type=radio _name=radio _value=yes value=yes)xml()ltinput checked=checked name=radio type=radio value=yes gt

gtgtgt INPUT(_type=radio _name=radio _value=no value=yes)xml()ltinput name=radio type=radio value=no gt

tag = input

xml()generates the xml for this component

class gluonhtmlLABEL(components attributes)Bases gluonhtmlDIV

tag = label

class gluonhtmlLEGEND(components attributes)Bases gluonhtmlDIV

tag = legend

class gluonhtmlLI(components attributes)Bases gluonhtmlDIV

tag = li

class gluonhtmlLINK(components attributes)Bases gluonhtmlDIV

tag = link

class gluonhtmlOL(components attributes)Bases gluonhtmlUL

tag = ol

class gluonhtmlUL(components attributes)Bases gluonhtmlDIV

UL Component

If subcomponents are not LI-components they will be wrapped in a LI

tag = ul

class gluonhtmlMARKMIN(text extra=None allowed=None sep=rsquoprsquo url=None environ-ment=None latex=rsquogooglersquo autolinks=rsquodefaultrsquo protolinks=rsquodefaultrsquoclass_prefix=rdquo id_prefix=rsquomarkmin_rsquo kwargs)

Bases gluonhtmlXmlComponent

For documentation httpweb2pycomexamplesstaticmarkminhtml

flatten()

xml()

class gluonhtmlMENU(data args)Bases gluonhtmlDIV

Used to build menus

Parameters

bull _class ndash defaults to lsquoweb2py-menu web2py-menu-verticalrsquo

bull ul_class ndash defaults to lsquoweb2py-menu-verticalrsquo

44 Chapter 13 html Module

web2py Documentation Release 2146-stable

bull li_class ndash defaults to lsquoweb2py-menu-expandrsquo

bull li_first ndash defaults to lsquoweb2py-menu-firstrsquo

bull li_last ndash defaults to lsquoweb2py-menu-lastrsquo

Use like

menu = MENU([[name False URL() [submenu]] ])=menu

serialize(data level=0)

serialize_mobile(data select=None prefix=rdquo)

tag = ul

xml()generates the xml for this component

class gluonhtmlMETA(components attributes)Bases gluonhtmlDIV

tag = meta

class gluonhtmlOBJECT(components attributes)Bases gluonhtmlDIV

tag = object

class gluonhtmlOPTION(components attributes)Bases gluonhtmlDIV

tag = option

class gluonhtmlP(components attributes)Bases gluonhtmlDIV

Will replace n by ltbr gt if the cr2br attribute is provided

see also DIV

tag = p

xml()generates the xml for this component

class gluonhtmlPRE(components attributes)Bases gluonhtmlDIV

tag = pre

class gluonhtmlSCRIPT(components attributes)Bases gluonhtmlDIV

tag = script

xml()generates the xml for this component

class gluonhtmlOPTGROUP(components attributes)Bases gluonhtmlDIV

tag = optgroup

131 Template helpers 45

web2py Documentation Release 2146-stable

class gluonhtmlSELECT(components attributes)Bases gluonhtmlINPUT

Examples

gtgtgt from validators import IS_IN_SETgtgtgt SELECT(yes no _name=selector value=yes requires=IS_IN_SET([yes no]))xml()ltselect name=selectorgtltoption selected=selected value=yesgtyesltoptiongtrarr˓ltoption value=nogtnoltoptiongtltselectgt

tag = select

class gluonhtmlSPAN(components attributes)Bases gluonhtmlDIV

tag = span

class gluonhtmlSTRONG(components attributes)Bases gluonhtmlDIV

tag = strong

class gluonhtmlSTYLE(components attributes)Bases gluonhtmlDIV

tag = style

xml()generates the xml for this component

class gluonhtmlTABLE(components attributes)Bases gluonhtmlDIV

TABLE Component

If subcomponents are not TRTBODYTHEADTFOOT-components they will be wrapped in a TR

tag = table

gluonhtmlTAGTAG factory

Examples

gtgtgt print TAGfirst(TAGsecond(test) _key = 3)ltfirst key=3gtltsecondgttestltsecondgtltfirstgt

class gluonhtmlTD(components attributes)Bases gluonhtmlDIV

tag = td

class gluonhtmlTEXTAREA(components attributes)Bases gluonhtmlINPUT

Examples

TEXTAREA(_name=sometext value=blah 100 requires=IS_NOT_EMPTY())

lsquoblah blah blah rsquo will be the content of the textarea field

tag = textarea

46 Chapter 13 html Module

web2py Documentation Release 2146-stable

class gluonhtmlTH(components attributes)Bases gluonhtmlDIV

tag = th

class gluonhtmlTHEAD(components attributes)Bases gluonhtmlDIV

tag = thead

class gluonhtmlTBODY(components attributes)Bases gluonhtmlDIV

tag = tbody

class gluonhtmlTFOOT(components attributes)Bases gluonhtmlDIV

tag = tfoot

class gluonhtmlTITLE(components attributes)Bases gluonhtmlDIV

tag = title

class gluonhtmlTR(components attributes)Bases gluonhtmlDIV

TR Component

If subcomponents are not TDTH-components they will be wrapped in a TD

tag = tr

class gluonhtmlTT(components attributes)Bases gluonhtmlDIV

tag = tt

gluonhtmlURL(a=None c=None f=None r=None args=None vars=None an-chor=rdquo extension=None env=None hmac_key=None hash_vars=Truesalt=None user_signature=None scheme=None host=None port=None en-code_embedded_slash=False url_encode=True language=None)

generates a url lsquoacfrsquo corresponding to application a controller c and function f If r=request is passed a c fare set respectively to rapplication rcontroller rfunction

The more typical usage is

URL(lsquoindexrsquo)

that generates a url for the index function within the present application and controller

Parameters

bull a ndash application (default to current if r is given)

bull c ndash controller (default to current if r is given)

bull f ndash function (default to current if r is given)

bull r ndash request (optional)

bull args ndash any arguments (optional) Additional ldquopathrdquo elements

bull vars ndash any variables (optional) Querystring elements

bull anchor ndash anchorname without (optional)

131 Template helpers 47

web2py Documentation Release 2146-stable

bull extension ndash force an extension

bull hmac_key ndash key to use when generating hmac signature (optional)

bull hash_vars ndash which of the vars to include in our hmac signature True (default) - hash allvars False - hash none of the vars iterable - hash only the included vars [lsquokey1rsquorsquokey2rsquo]

bull salt ndash salt hashing with this string

bull user_signature ndash signs automatically the URL in such way that only the user canaccess the URL (use with URLverify or authrequires_signature())

bull scheme ndash URI scheme (True lsquohttprsquo or lsquohttpsrsquo etc) forces absolute URL (optional)

bull host ndash string to force absolute URL with host (True means http_host)

bull port ndash optional port number (forces absolute URL)

bull encode_embedded_slash ndash encode slash characters included in args

bull url_encode ndash encode characters included in vars

Raises SyntaxError ndash when no application controller or function is available or when a CRLFis found in the generated url

Examples

gtgtgt str(URL(a=a c=c f=f args=[x y z] vars=p1 q2 anchor=1))acfxyzp=1ampq=21

gtgtgt str(URL(a=a c=c f=f args=[x y z] vars=p(13) q2 anchor=1))acfxyzp=1ampp=3ampq=21

gtgtgt str(URL(a=a c=c f=f args=[x y z] vars=p(31) q2 anchor=1))acfxyzp=3ampp=1ampq=21

gtgtgt str(URL(a=a c=c f=f anchor=1+2))acf12B2

gtgtgt str(URL(a=a c=c f=f args=[x y z] vars=p(13) q2 anchor=1 hmac_key=key))acfxyzp=1ampp=3ampq=2amp_signature=a32530f0d0caa80964bb92aad2bedf8a4486a31f1

gtgtgt str(URL(a=a c=c f=f args=[wx yz]))acfwxyz

gtgtgt str(URL(a=a c=c f=f args=[wx yz] encode_embedded_slash=True))acfw2Fxy2Fz

gtgtgt str(URL(a=a c=c f=f args=[(id)d] url_encode=False))acf(id)d

gtgtgt str(URL(a=a c=c f=f args=[(id)d] url_encode=True))acf2528id29d

48 Chapter 13 html Module

web2py Documentation Release 2146-stable

gtgtgt str(URL(a=a c=c f=f vars=id (id)d url_encode=False))acfid=(id)d

gtgtgt str(URL(a=a c=c f=f vars=id (id)d url_encode=True))acfid=2528id29d

gtgtgt str(URL(a=a c=c f=f anchor=(id)d url_encode=False))acf(id)d

gtgtgt str(URL(a=a c=c f=f anchor=(id)d url_encode=True))acf2528id29d

class gluonhtmlXHTML(components attributes)Bases gluonhtmlDIV

This is XHTML version of the HTML helper

There are three predefined document type definitions They can be specified in the lsquodoctypersquo parameter

bull lsquostrictrsquo enables strict doctype

bull lsquotransitionalrsquo enables transitional doctype (default)

bull lsquoframesetrsquo enables frameset doctype

bull any other string will be treated as userrsquos own doctype

lsquolangrsquo parameter specifies the language of the document and the xml document Defaults to lsquoenrsquo

lsquoxmlnsrsquo parameter specifies the xml namespace Defaults to lsquohttpwwww3org1999xhtmlrsquo

See also DIV

frameset = ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 FramesetEN httpwwww3orgTRxhtml1DTDxhtml1-framesetdtdgtn

strict = ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 StrictEN httpwwww3orgTRxhtml1DTDxhtml1-strictdtdgtn

tag = html

transitional = ltDOCTYPE html PUBLIC -W3CDTD XHTML 10 TransitionalEN httpwwww3orgTRxhtml1DTDxhtml1-transitionaldtdgtn

xml()generates the xml for this component

xmlns = httpwwww3org1999xhtml

class gluonhtmlXML(text sanitize=False permitted_tags=[rsquoarsquo rsquobrsquo rsquoblockquotersquo rsquobrrsquo rsquoirsquo rsquolirsquo rsquoolrsquorsquoulrsquo rsquoprsquo rsquocitersquo rsquocodersquo rsquoprersquo rsquoimgrsquo rsquoh1rsquo rsquoh2rsquo rsquoh3rsquo rsquoh4rsquo rsquoh5rsquo rsquoh6rsquo rsquotablersquo rsquotrrsquorsquotdrsquo rsquodivrsquo rsquostrongrsquo rsquospanrsquo] allowed_attributes=rsquoarsquo [rsquohrefrsquo rsquotitlersquo rsquotargetrsquo]rsquoblockquotersquo [rsquotypersquo] rsquoimgrsquo [rsquosrcrsquo rsquoaltrsquo] rsquotdrsquo [rsquocolspanrsquo])

Bases gluonhtmlXmlComponent

use it to wrap a string that contains XMLHTML so that it will not be escaped by the template

Examples

gtgtgt XML(lth1gtHellolth1gt)xml()lth1gtHellolth1gt

elements(args kargs)to be considered experimental since the behavior of this method is questionable another option could beTAG(selftext)elements(args kwargs)

131 Template helpers 49

web2py Documentation Release 2146-stable

flatten(render=None)returns the text stored by the XML object rendered by the render function

xml()

gluonhtmlxmlescape(data quote=True)Returns an escaped string of the provided data

Parameters

bull data ndash the data to be escaped

bull quote ndash optional (default False)

gluonhtmlembed64(filename=None file=None data=None extension=rsquoimagegifrsquo)helper to encode the provided (binary) data into base64

Parameters

bull filename ndash if provided opens and reads this file in lsquorbrsquo mode

bull file ndash if provided reads this file

bull data ndash if provided uses the provided data

50 Chapter 13 html Module

CHAPTER 14

http Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

141 HTTP statuses helpers

exception gluonhttpHTTP(status body=rdquo cookies=None headers)Bases exceptionsException

Raises an HTTP response

Parameters

bull status ndash usually an integer If itrsquos a well known status code the ERROR message will beautomatically added A string can also be passed as 510 Foo Bar and in that case the statuscode and the error message will be parsed accordingly

bull body ndash what to return as body If left as is will return the error code and the status messagein the body itself

bull cookies ndash pass cookies along (usually not needed)

bull headers ndash pass headers as usual dict mapping

cookies2headers(cookies)

messagecompose a message describing this exception

ldquostatus defined_status [web2py_error]rdquo

message elements that are not defined are omitted

to(responder env=None)

51

web2py Documentation Release 2146-stable

gluonhttpredirect(location=rdquo how=303 client_side=False headers=None)Raises a redirect (303)

Parameters

bull location ndash the url where to redirect

bull how ndash what HTTP status code to use when redirecting

bull client_side ndash if set to True it triggers a reload of the entire page when the fragmenthas been loaded as a component

52 Chapter 14 http Module

CHAPTER 15

languages Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)Plural subsystem is created by Vladyslav Kozlovskyy (Ukraine) ltdbdevelopgmailcomgt

151 Translation system

class gluonlanguagestranslator(langpath http_accept_language)Bases object

This class is instantiated by gluoncompileappbuild_environment as the T object

Example

Tforce(None) turns off translation Tforce(lsquofr itrsquo) forces web2py to translate using frpy or itpy

T(ldquoHello Worldrdquo) translates ldquoHello Worldrdquo using the selected file

Note

bull there is no need to force since by default T uses http_accept_language to determine a translation file

bull en and en-en are considered different languages

bull if language xx-yy is not found force() probes other similar languages using such algorithm xx-yypy -gtxxpy -gt xx-yypy -gt xxpy

M(message symbols= language=None lazy=None filter=None ftag=None ns=None)Gets cached translated markmin-message with inserted parametes if lazy==True lazyT object is returned

apply_filter(message symbols= filter=None ftag=None)

53

web2py Documentation Release 2146-stable

force(languages)Selects language(s) for translation

if a list of languages is passed as a parameter the first language from this list that matches the ones fromthe possible_languages dictionary will be selected

default language will be selected if none of them matches possible_languages

get_possible_languages()Gets list of all possible languages for current application

get_possible_languages_info(lang=None)Returns info for selected language or dictionary with all possible languages info from APPlanguagespyIt Returns

bull a tuple containing

langcode langname langfile_mtimepluraldict_fname pluraldict_mtimeprules_langcode npluralsget_plural_id construct_plural_form

or None

bull if lang is NOT defined a dictionary with all possible languages

langcode(from filename)( langcode language code from langcodelangname

language name in national spelling from langnamelangfile_mtime m_time of language filepluraldict_fname name of plural dictionary file or None (when

rarr˓defaultpy is not exist)pluraldict_mtime m_time of plural dictionary file or 0 if file is

rarr˓not existprules_langcode code of plural rules language or defaultnplurals nplurals for current languageget_plural_id get_plural_id() for current languageconstruct_plural_form) construct_plural_form() for current

rarr˓language

Parameters lang (str) ndash language

get_t(message prefix=rdquo)Use to add a comment into a translation string the comment can be useful do discriminate differentpossible translations for the same string (for example different locations)

T( hello world ) -gt hello world T( hello world token) -gt hello world T(hello world token) -gt hello world

the notation is ignored in multiline strings and strings that start with This is needed to allow markminsyntax to be translated

params_substitution(message symbols)Substitutes parameters from symbols into message using also parse placeholders for plural-formsprocessing

Returns string with parameters

54 Chapter 15 languages Module

web2py Documentation Release 2146-stable

Note symbols MUST BE OR tuple OR dict of parameters

plural(word n)Gets plural form of word for number n invoked from T()TM() in tag

Note ldquowordrdquo MUST be defined in current language (Taccepted_language)

Parameters

bull word (str) ndash word in singular

bull n (numeric) ndash number plural form created for

Returns word in appropriate singularplural form

Return type word (str)

set_current_languages(languages)Sets current AKA ldquodefaultrdquo languages Setting one of this languages makes the force() function to turntranslation off

translate(message symbols)Gets cached translated message with inserted parameters(symbols)

gluonlanguagesfindT(path language=rsquoenrsquo)

Note Must be run by the admin app

gluonlanguagesupdate_all_languages(application_path)

Note Must be run by the admin app

151 Translation system 55

web2py Documentation Release 2146-stable

56 Chapter 15 languages Module

CHAPTER 16

main Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

161 The gluon wsgi application

gluonmainwsgibase(environ responder)The gluon wsgi application The first function called when a page is requested (static or dynamic) It can becalled by pastehttpserver or by apache mod_wsgi (or any WSGI-compatible server)

bull fills request with info

bull the environment variables replacing lsquorsquo with lsquo_rsquo

bull adds web2py path and version info

bull compensates for fcgi missing path_info and query_string

bull validates the path in url

The url path must be either

1 for static pages

bull ltapplicationgtstaticltfilegt

2 for dynamic pages

bull ltapplicationgt[ltcontrollergt[ltfunctiongt[ltsubgt]]][ltextensiongt]

The naming conventions are

bull application controller function and extension may only contain [a-zA-Z0-9_]

57

web2py Documentation Release 2146-stable

bull file and sub may also contain lsquo-lsquo lsquo=rsquo lsquorsquo and lsquorsquo

gluonmainsave_password(password port)Used by main() to save the password in the parameters_portpy file

gluonmainappfactory(wsgiapp=ltfunction wsgibasegt logfilename=rsquohttpserverlogrsquo pro-filer_dir=None profilerfilename=None)

generates a wsgi application that does logging and profiling and calls wsgibase

Parameters

bull wsgiapp ndash the base application

bull logfilename ndash where to store apache-compatible requests log

bull profiler_dir ndash where to store profile files

class gluonmainHttpServer(ip=rsquo127001rsquo port=8000 password=rdquopid_filename=rsquohttpserverpidrsquo log_filename=rsquohttpserverlogrsquoprofiler_dir=None ssl_certificate=None ssl_private_key=Nonessl_ca_certificate=None min_threads=None max_threads=Noneserver_name=None request_queue_size=5 timeout=10socket_timeout=1 shutdown_timeout=None path=None inter-faces=None)

Bases object

the web2py web server (Rocket)

start()start the web server

stop(stoplogging=False)stop cron and the web server

58 Chapter 16 main Module

CHAPTER 17

messageboxhandler Module

class gluonmessageboxhandlerMessageBoxHandlerBases loggingHandler

emit(record)Do whatever it takes to actually log the specified logging record

This version is intended to be implemented by subclasses and so raises a NotImplementedError

class gluonmessageboxhandlerNotifySendHandlerBases loggingHandler

emit(record)Do whatever it takes to actually log the specified logging record

This version is intended to be implemented by subclasses and so raises a NotImplementedError

59

web2py Documentation Release 2146-stable

60 Chapter 17 messageboxhandler Module

CHAPTER 18

myregex Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

181 Useful regexes

61

web2py Documentation Release 2146-stable

62 Chapter 18 myregex Module

CHAPTER 19

newcron Module

This file is part of the web2py Web FrameworkCreated by Attila Csipa ltweb2pycsipainrsgtModified by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

Cron-style interface

class gluonnewcronToken(path)Bases object

acquire(startup=False)Returns the time when the lock is acquired or None if cron already running

lock is implemented by writing a pickle (start stop) in cronmaster start is time when cron job starts andstop is time when cron completed stop == 0 if job started but did not yet complete if a cron job startedwithin less than 60 seconds acquire returns None if a cron job started before 60 seconds and did not stopa warning is issue ldquoStale cronmaster detectedrdquo

release()Writes into cronmaster the time when cron job was completed

gluonnewcronabsolute_path_link(path)Returns an absolute path for the destination of a symlink

gluonnewcroncrondance(applications_parent ctype=rsquosoftrsquo startup=False apps=None)

class gluonnewcroncronlauncher(cmd shell=True)Bases threadingThread

run()Method representing the threadrsquos activity

You may override this method in a subclass The standard run() method invokes the callable object passedto the objectrsquos constructor as the target argument if any with sequential and keyword arguments takenfrom the args and kwargs arguments respectively

63

web2py Documentation Release 2146-stable

class gluonnewcronextcron(applications_parent apps=None)Bases threadingThread

run()Method representing the threadrsquos activity

You may override this method in a subclass The standard run() method invokes the callable object passedto the objectrsquos constructor as the target argument if any with sequential and keyword arguments takenfrom the args and kwargs arguments respectively

class gluonnewcronhardcron(applications_parent)Bases threadingThread

launch()

run()Method representing the threadrsquos activity

You may override this method in a subclass The standard run() method invokes the callable object passedto the objectrsquos constructor as the target argument if any with sequential and keyword arguments takenfrom the args and kwargs arguments respectively

gluonnewcronparsecronline(line)

gluonnewcronrangetolist(s period=rsquominrsquo)

class gluonnewcronsoftcron(applications_parent)Bases threadingThread

run()Method representing the threadrsquos activity

You may override this method in a subclass The standard run() method invokes the callable object passedto the objectrsquos constructor as the target argument if any with sequential and keyword arguments takenfrom the args and kwargs arguments respectively

gluonnewcronstopcron()Graceful shutdown of cron

64 Chapter 19 newcron Module

CHAPTER 20

portalocker Module

Cross-platform (posixnt) API for flock-style file locking

Synopsis

import portalockerfile = open(somefile r+)portalockerlock(file portalockerLOCK_EX)fileseek(12)filewrite(foo)fileclose()

If you know what yoursquore doing you may choose to

portalockerunlock(file)

before closing the file but why

Methods

lock( file flags )unlock( file )

Constants

LOCK_EXLOCK_SHLOCK_NB

I learned the win32 technique for locking files from sample code provided by John Nielsen ltnielsenjfmy-dejacomgtin the documentation that accompanies the win32 modules

Author Jonathan Feinberg ltjdfpoboxcomgt Version $Id portalockerpyv 13 20010529 184755 AdministratorExp $

class gluonportalockerLockedFile(filename mode=rsquorbrsquo)Bases object

65

web2py Documentation Release 2146-stable

close()

read(size=None)

readline()

readlines()

write(data)

gluonportalockerlock(file flags)

gluonportalockerread_locked(filename)

gluonportalockerunlock(file)

gluonportalockerwrite_locked(filename data)

66 Chapter 20 portalocker Module

CHAPTER 21

recfile Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

211 Generates names for cache and session files

gluonrecfileexists(filename path=None)

gluonrecfilegenerate(filename depth=2 base=512)

gluonrecfileopen(filename mode=rsquorrsquo path=None)

gluonrecfileremove(filename path=None)

67

web2py Documentation Release 2146-stable

68 Chapter 21 recfile Module

CHAPTER 22

restricted Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

221 Restricted environment to execute applicationrsquos code

exception gluonrestrictedRestrictedError(layer=rdquo code=rdquo output=rdquo environ-ment=None)

Bases exceptionsException

Class used to wrap an exception that occurs in the restricted environment below The traceback is used to logthe exception and generate a ticket

load(request app ticket_id)Loads a logged exception

log(request)Logs the exception

gluonrestrictedrestricted(code environment=None layer=rsquoUnknownrsquo)Runs code in environment and returns the output If an exception occurs in code it raises a RestrictedErrorcontaining the traceback Layer is passed to RestrictedError to identify where the error occurred

class gluonrestrictedTicketStorage(db=None tablename=rsquoweb2py_ticketrsquo)Bases gluonstorageStorage

Defines the ticket object and the default values of its members (None)

load(request app ticket_id)

store(request ticket_id ticket_data)Stores the ticket It will figure out if this must be on disk or in db

gluonrestrictedcompile2(code layer)The +n is necessary else compile fails when code ends in a comment

69

web2py Documentation Release 2146-stable

70 Chapter 22 restricted Module

CHAPTER 23

rewrite Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

gluonrewrite parses incoming URLs and formats outgoing URLs for gluonhtmlURL

In addition it rewrites both incoming and outgoing URLs based on the (optional) user-supplied routespy which alsoallows for rewriting of certain error messages

routespy supports two styles of URL rewriting depending on whether lsquoroutersrsquo is defined Refer to routerexamplepyand routesexamplepy for additional documentation

class gluonrewriteMapUrlIn(request=None env=None)Bases object

Logic for mapping incoming URLs

arg0Returns first arg

harg0Returns first arg with optional hyphen mapping

map_app()Determines application name

map_controller()Identifies controller

map_function()Handles functionextension

map_language()Handles language (no hyphen mapping)

71

web2py Documentation Release 2146-stable

map_prefix()Strips path prefix if present in its entirety

map_root_static()Handles root-static files (no hyphen mapping)

a root-static file is one whose incoming URL expects it to be at the root typically robotstxt amp faviconico

map_static()Handles static files file_match but no hyphen mapping

pop_arg_if(dopop)Conditionally removes first arg and returns new first arg

sluggify()

update_request()Updates request from self Builds envrequest_uri Makes lower-case versions of http headers in env

validate_args()Checks args against validation pattern

class gluonrewriteMapUrlOut(request env application controller function args other schemehost port language)

Bases object

Logic for mapping outgoing URLs

acf()Converts components to applangcontrollerfunction

build_acf()Builds acf from components

omit_acf()Omits what we can of acf

omit_lang()Omits language if possible

gluonrewritecompile_regex(k v env=None)Preprocess and compile the regular expressions in routes_appinout The resulting regex will match a pattern ofthe form

[remote address][protocol][host][method] [path]

We allow abbreviated regexes on input here we try to complete them

gluonrewritefilter_err(status application=rsquoapprsquo ticket=rsquotktrsquo)doctestunittest interface to routes_onerror

gluonrewritefilter_url(url method=rsquogetrsquo remote=rsquo0000rsquo out=False app=False lang=Nonedomain=(None None) env=False scheme=None host=Noneport=None language=None)

doctestunittest interface to regex_filter_in() and regex_filter_out()

gluonrewritefixup_missing_path_info(environ)

gluonrewriteget_effective_router(appname)Returns a private copy of the effective router for the specified application

gluonrewriteinvalid_url(routes)

72 Chapter 23 rewrite Module

web2py Documentation Release 2146-stable

gluonrewriteload(routes=rsquoroutespyrsquo app=None data=None rdict=None)load read (if file) and parse routes store results in params (called from mainpy at web2py initialization time)If data is present itrsquos used instead of the routespy contents If rdict is present it must be a dict to be used forrouters (unit test)

gluonrewriteload_routers(all_apps)Load-time post-processing of routers

gluonrewritelog_rewrite(string)Log rewrite activity under control of routespy

gluonrewritemap_url_in(request env app=False)Routes incoming URL

gluonrewritemap_url_out(request env application controller function args other scheme hostport language=None)

Supply acf (or alangcf) portion of outgoing url

The basic rule is that we can only make transformations that map_url_in can reverse

Suppose that the incoming arguments are acfargslang and that the router defaults are da dc df dl

We can perform these transformations trivially if args=[] and lang=None or dl

dadcdf =gt adcdf =gt aacdf =gt ac

We would also like to be able to strip the default application or applicationcontroller from URLs with func-tionargs present thus

dacfargs =gt cfargsdadcfargs =gt fargs

We use [applications] and [controllers] and functions to suppress ambiguous omissions

We assume that language names do not collide with acf names

gluonrewriteregex_filter_in(e)Regex rewrite incoming URL

gluonrewriteregex_filter_out(url e=None)Regex rewrite outgoing URL

gluonrewriteregex_select(env=None app=None request=None)Selects a set of regex rewrite params for the current request

gluonrewriteregex_uri(e regexes tag default=None)Filters incoming URI against a list of regexes

gluonrewriteregex_url_in(request environ)Rewrites and parses incoming URL

gluonrewritesluggify(key)

gluonrewritetry_redirect_on_error(http_object request ticket=None)Called from mainwsgibase to rewrite the http response

gluonrewritetry_rewrite_on_error(http_response request environ ticket=None)Called from mainwsgibase to rewrite the http response

gluonrewriteurl_in(request environ)Parses and rewrites incoming URL

73

web2py Documentation Release 2146-stable

gluonrewriteurl_out(request environ application controller function args other scheme hostport language=None)

Assembles and rewrites outgoing URL

74 Chapter 23 rewrite Module

CHAPTER 24

sanitizer Module

From httpaspnactivestatecomASPNCookbookPythonRecipe496942Submitter Josh Goldfoot (other recipes)Last Updated 20060805Version 10

241 Cross-site scripting (XSS) defense

gluonsanitizersanitize(text permitted_tags=[rsquoarsquo rsquobrsquo rsquoblockquotersquo rsquobrrsquo rsquoirsquo rsquolirsquo rsquoolrsquo rsquoulrsquorsquoprsquo rsquocitersquo rsquocodersquo rsquoprersquo rsquoimgrsquo rsquoh1rsquo rsquoh2rsquo rsquoh3rsquo rsquoh4rsquo rsquoh5rsquo rsquoh6rsquo rsquota-blersquo rsquotbodyrsquo rsquotheadrsquo rsquotfootrsquo rsquotrrsquo rsquotdrsquo rsquodivrsquo rsquostrongrsquo rsquospanrsquo] al-lowed_attributes=rsquoarsquo [rsquohrefrsquo rsquotitlersquo] rsquoblockquotersquo [rsquotypersquo] rsquoimgrsquo[rsquosrcrsquo rsquoaltrsquo] rsquotdrsquo [rsquocolspanrsquo] escape=True)

75

web2py Documentation Release 2146-stable

76 Chapter 24 sanitizer Module

CHAPTER 25

scheduler Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

251 Background processes made simple

class gluonschedulerJobGraph(db job_name)Bases object

Experimental dependencies amongs tasks

add_deps(task_parent task_child)Create a dependency between task_parent and task_child

validate(job_name=None)Validate if all tasks job_name can be completed

Checks if there are no mutual dependencies among tasks Commits at the end if successfull or it rollbacksthe entire transaction Handle with care

class gluonschedulerMetaSchedulerBases threadingThread

Base class documenting schedulerrsquos base methods

async(task)Start the background process

Parameters task ndash a Task object

Returns

containing

77

web2py Documentation Release 2146-stable

(okresultoutput)(errorexceptionNone)(timeoutNoneNone)(terminatedNoneNone)

Return type tuple

die()Forces termination of the worker process along with any running task

give_up()Waits for any running task to be executed then exits the worker process

loop()Main loop fetching tasks and starting executorrsquos background processes

pop_task()Fetches a task ready to be executed

report_task(task task_report)Creates a task report

run()This is executed by the main thread to send heartbeats

send_heartbeat(counter)

sleep()

start_heartbeats()

terminate_process()Terminates any running tasks (internal use only)

class gluonschedulerScheduler(db tasks=None migrate=True worker_name=Nonegroup_names=None heartbeat=3 max_empty_runs=0discard_results=False utc_time=False)

Bases gluonschedulerMetaScheduler

Scheduler object

Parameters

bull db ndash DAL connection where Scheduler will create its tables

bull tasks (dict) ndash either a dict containing namendashgtfunc or None If None functions will besearched in the environment

bull migrate (bool) ndash turn migration onoff for the Schedulerrsquos tables

bull worker_name (str) ndash force worker_name to identify each process Leave it to None toautoassign a name (hostnamepid)

bull group_names (list) ndash process tasks belonging to this group defaults to [lsquomainrsquo] if noth-ing gets passed

bull heartbeat (int) ndash how many seconds the worker sleeps between one execution and thefollowing one Indirectly sets how many seconds will pass between checks for new tasks

bull max_empty_runs (int) ndash how many loops are allowed to pass without processing anytasks before exiting the process 0 to keep always the process alive

78 Chapter 25 scheduler Module

web2py Documentation Release 2146-stable

bull discard_results (bool) ndash Scheduler stores executionsrsquos details into the sched-uler_run table By default only if there is a result the details are kept Turning this toTrue means discarding results even for tasks that return something

bull utc_time (bool) ndash do all datetime calculations assuming UTC as the timezone Remem-ber to pass start_time and stop_time to tasks accordingly

adj_hibernation()Used to increase the ldquosleeprdquo interval for DISABLED workers

assign_tasks(db)Assign task to workers that can then pop them from the queue

Deals with group_name(s) logic in order to assign linearly tasks to available workers for those groups

being_a_ticker()Elect a TICKER process that assigns tasks to available workers

Does its best to elect a worker that is not busy processing other tasks to allow a proper distribution of tasksamong all active workers ASAP

define_tables(db migrate)Define Scheduler tables structure

disable(group_names=None limit=None worker_name=None)Set DISABLED on the workers processing group_names tasks

A DISABLED worker will be kept alive but it wonrsquot be able to process any waiting tasks essentiallyputting it to sleep By default all group_names of Schedulerrsquos instantation are selected

get_workers(only_ticker=False)Returns a dict holding worker_name columns representing all ldquoregisteredrdquo workers only_ticker re-turns only the workers running as a TICKER if there are any

kill(group_names=None limit=None worker_name=None)Sets KILL as worker status The worker will be killed even if itrsquos processing a task

loop(worker_name=None)Main loop

This works basically as a neverending loop that

bull checks if the worker is ready to process tasks (is not DISABLED)

bull pops a task from the queue

bull if there is a task

ndash spawns the executor background process

ndash waits for the process to be finished

ndash sleeps heartbeat seconds

bull if there is not a task

ndash checks for max_empty_runs

ndash sleeps heartbeat seconds

now()Shortcut that fetches current time based on UTC preferences

pop_task(db)Grab a task ready to be executed from the queue

251 Background processes made simple 79

web2py Documentation Release 2146-stable

queue_task(function pargs=[] pvars= kwargs)Queue tasks This takes care of handling the validation of all parameters

Parameters

bull function ndash the function (anything callable with a __name__)

bull pargs ndash ldquorawrdquo args to be passed to the function Automatically jsonified

bull pvars ndash ldquorawrdquo kwargs to be passed to the function Automatically jsonified

bull kwargs ndash all the parameters available (basically every scheduler_task column) If argsand vars are here they should be jsonified already and they will override pargs and pvars

Returns a dict just as a normal validate_and_insert() plus a uuid key holding the uuid of thequeued task If validation is not passed ( ie some parameters are invalid) both id and uuidwill be None and yoursquoll get an ldquoerrorrdquo dict holding the errors found

report_task(task task_report)Take care of storing the result according to preferences

Deals with logic for repeating tasks

resume(group_names=None limit=None worker_name=None)Wakes a worker up (it will be able to process queued tasks)

send_heartbeat(counter)Coordination among available workers

It - sends the heartbeat - elects a ticker among available workers (the only process that

effectively dispatch tasks to workers)

bull deals with workerrsquos statuses

bull does ldquohousecleaningrdquo for dead workers

bull triggers tasks assignment to workers

set_requirements(scheduler_task)Called to set defaults for lazy_tables connections

set_worker_status(group_names=None action=rsquoACTIVErsquo exclude=None limit=Noneworker_name=None)

Internal function to set workerrsquos status

sleep()Calculate the number of seconds to sleep

stop_task(ref)Shortcut for task termination

If the task is RUNNING it will terminate it meaning that status will be set as FAILED

If the task is QUEUED its stop_time will be set as to ldquonowrdquo the enabled flag will be set to False andthe status to STOPPED

Parameters ref ndash can be

bull an integer lookup will be done by scheduler_taskid

bull a string lookup will be done by scheduler_taskuuid

Returns

bull 1 if task was stopped (meaning an update has been done)

80 Chapter 25 scheduler Module

web2py Documentation Release 2146-stable

bull None if task was not found or if task was not RUNNING or QUEUED

Note Experimental

task_status(ref output=False)Retrieves task status and optionally the result of the task

Parameters

bull ref ndash can be

ndash an integer lookup will be done by scheduler_taskid

ndash a string lookup will be done by scheduler_taskuuid

ndash a Query lookup as you wish eg

dbscheduler_tasktask_name == test1

bull output (bool) ndash if True fetch also the scheduler_run record

Returns a single Row object for the last queued task If output == True returns also the lastscheduler_run record The scheduler_run record is fetched by a left join so it can have allfields == None

terminate(group_names=None limit=None worker_name=None)Sets TERMINATE as worker status The worker will wait for any currently running tasks to be executedand then it will exit gracefully

static total_seconds(td)Backport for py26

update_dependencies(db task_id)Unblock execution paths for Jobs

wrapped_assign_tasks(db)Commodity function to call assign_tasks and trap exceptions

If an exception is raised assume it happened because of database contention and retries assign_task after05 seconds

wrapped_pop_task()Commodity function to call pop_task and trap exceptions

If an exception is raised assume it happened because of database contention and retries pop_task after 05seconds

wrapped_report_task(task task_report)Commodity function to call report_task and trap exceptions

If an exception is raised assume it happened because of database contention and retries pop_task after 05seconds

class gluonschedulerTYPE(myclass=lttype rsquolistrsquogt parse=False)Bases object

Validator that checks whether field is valid json and validates its type Used for args and vars of the sched-uler_task table

class gluonschedulerTask(app function timeout args=rsquo[]rsquo vars=rsquorsquo kwargs)Bases object

251 Background processes made simple 81

web2py Documentation Release 2146-stable

Defines a ldquotaskrdquo object that gets passed from the main thread to the executorrsquos one

class gluonschedulerTaskReport(status result=None output=None tb=None)Bases object

Defines a ldquotask reportrdquo object that gets passed from the executorrsquos thread to the main one

gluonschedulerexecutor(queue task out)The function used to execute tasks in the background process

gluonschedulermain()allows to run worker without python web2pypy by simply

python gluonschedulerpy

82 Chapter 25 scheduler Module

CHAPTER 26

serializers Module

This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

gluonserializerscast_keys(o cast=lttype rsquostrrsquogt encoding=rsquoutf-8rsquo)Builds a new object with ltcastgt type keys Use this function if you are in Python lt 265 This avoids syntaxerrors when unpacking dictionary arguments

Parameters

bull o ndash is the object input

bull cast ndash (defaults to str) is an object type or function which supports conversion such as

converted = cast(o)

bull encoding ndash (defaults to utf-8) is the encoding for unicode keys This is not used forcustom cast functions

gluonserializerscsv(value)

gluonserializerscustom_json(o)

gluonserializersics(events title=None link=None timeshift=0 calname=True ignored)

gluonserializersjson(value default=ltfunction custom_jsongt)

gluonserializersloads_json(o unicode_keys=True kwargs)

gluonserializersloads_yaml(data)

gluonserializersrss(feed)

gluonserializerssafe_encode(text)

gluonserializersxml(value encoding=rsquoUTF-8rsquo key=rsquodocumentrsquo quote=True)

gluonserializersxml_rec(value key quote=True)

gluonserializersyaml(data)

83

web2py Documentation Release 2146-stable

84 Chapter 26 serializers Module

CHAPTER 27

settings Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

85

web2py Documentation Release 2146-stable

86 Chapter 27 settings Module

CHAPTER 28

shell Module

This file is part of the web2py Web FrameworkDeveloped by Massimo Di Pierro ltmdipierrocsdepauledugtlimodou ltlimodougmailcomgt and srackham ltsrackhamgmailcomgtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

281 Web2py environment in the shell

gluonshelldie(msg)

gluonshellenable_autocomplete_and_history(adir env)

gluonshellenv(a import_models=False c=None f=None dir=rdquo extra_request=)Returns web2py execution environment for application (a) controller (c) function (f) If import_models is Truethe exec all application models into the environment

extra_request allows you to pass along any extra variables to the request object before your models get executedThis was mainly done to support web2py_utilstest_runner however you can use it with any wrapper scripts thatneed access to the web2py environment

gluonshellexec_environment(pyfile=rdquo request=None response=None session=None)Environment builder and module loader

Builds a web2py environment and optionally executes a Python file into the environment

A Storage dictionary containing the resulting environment is returned The working directory must be web2pyroot ndash this is the web2py default

gluonshellexec_pythonrc()

gluonshellexecute_from_command_line(argv=None)

gluonshellget_usage()

87

web2py Documentation Release 2146-stable

gluonshellparse_path_info(path_info av=False)Parses path info formatted like acf where c and f are optional and a leading is accepted Return tuple (a c f)If invalid path_info a is set to None If c or f are omitted they are set to None If av=True parse args and vars

gluonshellrun(appname plain=False import_models=False startfile=None bpython=Falsepython_code=False cronjob=False)

Start interactive shell or run Python script (startfile) in web2py controller environment appname is formattedlike

bull a web2py application name

bull ac exec the controller c into the application environment

gluonshelltest(testpath import_models=True verbose=False)Run doctests in web2py environment testpath is formatted like

bull a tests all controllers in application a

bull ac tests controller c in application a

bull acf test function f in controller c application a

Where a c and f are application controller and function names respectively If the testpath is a file name the fileis tested If a controller is specified models are executed by default

88 Chapter 28 shell Module

CHAPTER 29

sql Module

This file is part of the web2py Web FrameworkDeveloped by Massimo Di Pierro ltmdipierrocsdepauledugtlimodou ltlimodougmailcomgt and srackham ltsrackhamgmailcomgtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

291 Just for backward compatibility

class gluonsqlDAL(uri=rsquosqlitedummydbrsquo pool_size=0 folder=None db_codec=rsquoUTF-8rsquo check_reserved=None migrate=True fake_migrate=False mi-grate_enabled=True fake_migrate_all=False decode_credentials=Falsedriver_args=None adapter_args=None attempts=5 auto_import=False big-int_id=False debug=False lazy_tables=False db_uid=None do_connect=Trueafter_connection=None tables=None ignore_field_case=True en-tity_quoting=False table_hash=None)

Bases pydalhelpersclassesSerializable pydalhelpersclassesBasicStorage

An instance of this class represents a database connection

Parameters

bull uri (str) ndash contains information for connecting to a database Defaults tolsquosqlitedummydbrsquo

Note experimental you can specify a dictionary as uri parameter ie with

db = DAL(uri sqlitestoragesqlitetables )

for an example of dict input you can check the output of the scaffolding db model with

dbas_dict()

89

web2py Documentation Release 2146-stable

Note that for compatibility with Python older than version 265 you should cast your dictinput keys to str due to a syntax limitation on kwarg names for proper DAL dictionary inputyou can use one of

obj = serializerscast_keys(dict [encoding=utf-8])or else (for parsing json input)obj = serializersloads_json(data unicode_keys=False)

bull pool_size ndash How many open connections to make to the database object

bull folder ndash where table files will be created Automatically set within web2py Use anexplicit path when using DAL outside web2py

bull db_codec ndash string encoding of the database (default lsquoUTF-8rsquo)

bull table_hash ndash database identifier with tables If your connection hash change you canstill using old tables if they have db_hash as prefix

bull check_reserved ndash list of adapters to check tablenames and column names againstsqlnosql reserved keywords Defaults to None

ndash rsquocommonrsquo List of sql keywords that are common to all database types such as ldquoSELECTINSERTrdquo (recommended)

ndash rsquoallrsquo Checks against all known SQL keywords

ndash rsquoltadapternamegtrdquo Checks against the specific adapters list of keywords

ndash rsquoltadapternamegt_nonreservedrsquo Checks against the specific adapters list of nonreservedkeywords (if available)

bull migrate ndash sets default migrate behavior for all tables

bull fake_migrate ndash sets default fake_migrate behavior for all tables

bull migrate_enabled ndash If set to False disables ALL migrations

bull fake_migrate_all ndash If set to True fake migrates ALL tables

bull attempts ndash Number of times to attempt connecting

bull auto_import ndash If set to True tries import automatically table definitions from thedatabases folder (works only for simple models)

bull bigint_id ndash If set turn on bigint instead of int for id and reference fields

bull lazy_tables ndash delays table definition until table access

bull after_connection ndash can a callable that will be executed after the connection

Example

Use as

db = DAL(sqlitetestdb)

or

90 Chapter 29 sql Module

web2py Documentation Release 2146-stable

db = DAL(uri tables []) experimental

dbdefine_table(tablename Field(fieldname1)Field(fieldname2))

class Field(fieldname type=rsquostringrsquo length=None default=ltfunction ltlambdagtgt re-quired=False requires=ltfunction ltlambdagtgt ondelete=rsquoCASCADErsquo not-null=False unique=False uploadfield=True widget=None label=None com-ment=None writable=True readable=True update=None authorize=Noneautodelete=False represent=None uploadfolder=None uploadseparate=Falseuploadfs=None compute=None custom_store=None custom_retrieve=Nonecustom_retrieve_file_properties=None custom_delete=None filter_in=None fil-ter_out=None custom_qualifier=None map_none=None rname=None)

Bases pydalobjectsExpression pydalhelpersclassesSerializable

Lazyalias of FieldMethod

Methodalias of FieldMethod

Virtualalias of FieldVirtual

as_dict(flat=False sanitize=True)

clone(point_self_references_to=False args)

count(distinct=None)

formatter(value)

retrieve(name path=None nameonly=False)If nameonly==True return (filename fullfilename) instead of (filename stream)

retrieve_file_properties(name path=None)

set_attributes(args attributes)

sqlsafe

sqlsafe_name

store(file filename=None path=None)

validate(value)

class Row(args kwargs)Bases pydalhelpersclassesBasicStorage

A dictionary that lets you do d[lsquoarsquo] as well as da this is only used to store a Row

as_dict(datetime_to_str=False custom_types=None)

as_json(mode=rsquoobjectrsquo default=None colnames=None serialize=True kwargs)serializes the row to a JSON object kwargs are passed to as_dict method only ldquoobjectrdquo mode sup-ported

serialize = False used by Rowsas_json

TODO return array mode with query column order

mode and colnames are not implemented

as_xml(row_name=rsquorowrsquo colnames=None indent=rsquo rsquo)

291 Just for backward compatibility 91

web2py Documentation Release 2146-stable

get(key default=None)

class Table(db tablename fields args)Bases pydalhelpersclassesSerializable pydalhelpersclassesBasicStorage

Represents a database table

Example

You can create a table as db = DAL( ) dbdefine_table(lsquousersrsquo Field(lsquonamersquo))

And then

dbusersinsert(name=me) print dbusers_insert() to see SQLdbusersdrop()

as_dict(flat=False sanitize=True)

bulk_insert(items)here items is a list of dictionaries

drop(mode=rdquo)

fields

import_from_csv_file(csvfile id_map=None null=rsquoltNULLgtrsquo unique=rsquouuidrsquoid_offset=None args kwargs)

Import records from csv file Column headers must have same names as table fields Field lsquoidrsquo isignored If column names read lsquotablefilersquo the lsquotablersquo prefix is ignored

bull lsquouniquersquo argument is a field which must be unique (typically a uuid field)bull lsquorestorersquo argument is default False if set True will remove old values in table firstbull lsquoid_maprsquo if set to None will not map ids

The import will keep the id numbers in the restored table This assumes that there is an field of typeid that is integer and in incrementing order Will keep the id numbers in restored table

insert(fields)

on(query)

sqlsafe

sqlsafe_alias

truncate(mode=None)

update(args kwargs)

update_or_insert(_key=ltfunction ltlambdagtgt values)

validate_and_insert(fields)

validate_and_update(_key=ltfunction ltlambdagtgt fields)

validate_and_update_or_insert(_key=ltfunction ltlambdagtgt fields)

with_alias(alias)

as_dict(flat=False sanitize=True)

can_join()

check_reserved_keyword(name)Validates name against SQL keywords Uses selfcheck_reserve which is a list of operators to use

close()

92 Chapter 29 sql Module

web2py Documentation Release 2146-stable

commit()

define_table(tablename fields args)

static distributed_transaction_begin(instances)

static distributed_transaction_commit(instances)

executesql(query placeholders=None as_dict=False fields=None colnames=Noneas_ordered_dict=False)

Executes an arbitrary query

Parameters

bull query (str) ndash the query to submit to the backend

bull placeholders ndash is optional and will always be None If using raw SQL with place-holders placeholders may be a sequence of values to be substituted in or (if supported bythe DB driver) a dictionary with keys matching named placeholders in your SQL

bull as_dict ndash will always be None when using DAL If using raw SQL can be set to Trueand the results cursor returned by the DB driver will be converted to a sequence of dic-tionaries keyed with the db field names Results returned with as_dict=True are the sameas those returned when applying to_list() to a DAL query If ldquoas_ordered_dictrdquo=True thebehaviour is the same as when ldquoas_dictrdquo=True with the keys (field names) guaranteed tobe in the same order as returned by the select name executed on the database

bull fields ndash list of DAL Fields that match the fields returned from the DB The Field objectsshould be part of one or more Table objects defined on the DAL object The ldquofieldsrdquo listcan include one or more DAL Table objects in addition to or instead of including Fieldobjects or it can be just a single table (not in a list) In that case the Field objects will beextracted from the table(s)

Note if either fields or colnames is provided the results will be converted to a DAL Rowsobject using the db_adapterparse() method

bull colnames ndash list of field names in tablenamefieldname format

Note It is also possible to specify both ldquofieldsrdquo and the associated ldquocolnamesrdquo In that case ldquofieldsrdquocan also include DAL Expression objects in addition to Field objects For Field objects in ldquofieldsrdquo theassociated ldquocolnamesrdquo must still be in tablenamefieldname format For Expression objects in ldquofieldsrdquo theassociated ldquocolnamesrdquo can be any arbitrary labels

DAL Table objects referred to by ldquofieldsrdquo or ldquocolnamesrdquo can be dummy tables and do not have to representany real tables in the database Also note that the ldquofieldsrdquo and ldquocolnamesrdquo must be in the same order asthe fields in the results cursor returned from the DB

export_to_csv_file(ofile args kwargs)

static get_instances()Returns a dictionary with uri as key with timings and defined tables

sqlitestoragesqlite dbstats [(select auth_useremail from auth_user 002009)]dbtables

defined [auth_cas auth_event auth_groupauth_membership auth_permission auth_user]

(continues on next page)

291 Just for backward compatibility 93

web2py Documentation Release 2146-stable

(continued from previous page)

lazy []

has_representer(name)

import_from_csv_file(ifile id_map=None null=rsquoltNULLgtrsquo unique=rsquouuidrsquomap_tablenames=None ignore_missing_tables=False args kwargs)

import_table_definitions(path migrate=False fake_migrate=False tables=None)

lazy_define_table(tablename fields args)

logger = ltloggingLogger objectgt

parse_as_rest(patterns args vars queries=None nested_select=True)

Example

Use as

dbdefine_table(personField(name)Field(info))dbdefine_table(pet

Field(ownedbydbperson)Field(name)Field(info)

)

requestrestful()def index()

def GET(argsvars)patterns = [

friends[person]personnamefieldpersonnamepets[petownedby]personnamepets[petownedby]petnamepersonnamepets[petownedby]petnamefield(dogs[pet] dbpetinfo==dog)(dogs[pet]petnamestartswith dbpetinfo==dog)]

parser = dbparse_as_rest(patternsargsvars)if parserstatus == 200

return dict(content=parserresponse)else

raise HTTP(parserstatusparsererror)

def POST(table_namevars)if table_name == person

return dbpersonvalidate_and_insert(vars)elif table_name == pet

return dbpetvalidate_and_insert(vars)else

raise HTTP(400)return locals()

represent(name args kwargs)

representers = rows_render ltfunction represent at 0x7fcf10dcdb18gt rows_xml ltclass gluonsqlhtmlSQLTABLEgt

94 Chapter 29 sql Module

web2py Documentation Release 2146-stable

rollback()

serializers = json ltfunction custom_json at 0x7fcf11069488gt xml ltfunction xml at 0x7fcf11069578gt

static set_folder(folder)

smart_query(fields text)

tables

uuid()

validators = None

validators_method(field)Field type validation using web2pyrsquos validators mechanism

makes sure the content of a field is in line with the declared fieldtype

where(query=None ignore_common_filters=None)

class gluonsqlField(fieldname type=rsquostringrsquo length=None default=ltfunction ltlambdagtgtrequired=False requires=ltfunction ltlambdagtgt ondelete=rsquoCASCADErsquonotnull=False unique=False uploadfield=True widget=None label=Nonecomment=None writable=True readable=True update=None autho-rize=None autodelete=False represent=None uploadfolder=None upload-separate=False uploadfs=None compute=None custom_store=Nonecustom_retrieve=None custom_retrieve_file_properties=None cus-tom_delete=None filter_in=None filter_out=None custom_qualifier=Nonemap_none=None rname=None)

Bases pydalobjectsExpression pydalhelpersclassesSerializable

LazyRepresents a database field

Example

Usage

a = Field(name string length=32 default=None required=Falserequires=IS_NOT_EMPTY() ondelete=CASCADEnotnull=False unique=Falseuploadfield=True widget=None label=None comment=Noneuploadfield=True True means store on disk

a_field_name means store in this field in db False means file content will be discarded

writable=True readable=True update=None authorize=Noneautodelete=False represent=None uploadfolder=Noneuploadseparate=False upload to separate directories by uuid_keys

first 2 character and tablenamefieldname False - old behavior True - put uploaded file in ltuploaddirgtlttablenamegtltfieldnamegtuuid_key[2] directory)

uploadfs=None a pyfilesystem where to store upload)

to be used as argument of DALdefine_table

alias of FieldMethod

291 Just for backward compatibility 95

web2py Documentation Release 2146-stable

Methodalias of FieldMethod

Virtualalias of FieldVirtual

as_dict(flat=False sanitize=True)

clone(point_self_references_to=False args)

count(distinct=None)

formatter(value)

retrieve(name path=None nameonly=False)If nameonly==True return (filename fullfilename) instead of (filename stream)

retrieve_file_properties(name path=None)

set_attributes(args attributes)

sqlsafe

sqlsafe_name

store(file filename=None path=None)

validate(value)

96 Chapter 29 sql Module

CHAPTER 30

sqlhtml Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

Holds

bull SQLFORM provide a form for a table (withwithout record)

bull SQLTABLE provides a table for a set of records

bull form_factory provides a SQLFORM for an non-db backed table

class gluonsqlhtmlAutocompleteWidget(request field id_field=None db=None or-derby=None limitby=(0 10) distinct=False key-word=rsquo_autocomplete_(tablename)s_(fieldname)srsquomin_length=2 help_fields=Nonehelp_string=None at_beginning=True)

Bases object

callback()

class gluonsqlhtmlBooleanWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates an INPUT checkbox tag

see also FormWidgetwidget

class gluonsqlhtmlCacheRepresenterBases object

class gluonsqlhtmlCheckboxesWidgetBases gluonsqlhtmlOptionsWidget

classmethod widget(field value attributes)Generates a TABLE tag including INPUT checkboxes (multiple allowed)

97

web2py Documentation Release 2146-stable

see also FormWidgetwidget

class gluonsqlhtmlDateWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlDatetimeWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlDecimalWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlDoubleWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlExportClass(rows)Bases object

content_type = None

export()

file_ext = None

label = None

represented()

class gluonsqlhtmlExporterCSV(rows)Bases gluonsqlhtmlExportClass

content_type = textcsv

export()

file_ext = csv

label = CSV

class gluonsqlhtmlExporterCSV_hidden(rows)Bases gluonsqlhtmlExportClass

content_type = textcsv

export()

file_ext = csv

label = CSV

class gluonsqlhtmlExporterHTML(rows)Bases gluonsqlhtmlExportClass

content_type = texthtml

export()

file_ext = html

label = HTML

class gluonsqlhtmlExporterJSON(rows)Bases gluonsqlhtmlExportClass

content_type = applicationjson

export()

file_ext = json

98 Chapter 30 sqlhtml Module

web2py Documentation Release 2146-stable

label = JSON

class gluonsqlhtmlExporterTSV(rows)Bases gluonsqlhtmlExportClass

content_type = texttab-separated-values

export()

file_ext = csv

label = TSV

class gluonsqlhtmlExporterXML(rows)Bases gluonsqlhtmlExportClass

content_type = textxml

export()

file_ext = xml

label = XML

class gluonsqlhtmlFormWidgetBases object

Helper for SQLFORM to generate form input fields (widget) related to the fieldtype

classmethod widget(field value attributes)Generates the widget for the field

When serialized will provide an INPUT tag

bull id = tablename_fieldname

bull class = fieldtype

bull name = fieldname

Parameters

bull field ndash the field needing the widget

bull value ndash value

bull attributes ndash any other attributes to be applied

class gluonsqlhtmlIntegerWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlJSONWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates a TEXTAREA for JSON notation

see also FormWidgetwidget

class gluonsqlhtmlListWidgetBases gluonsqlhtmlStringWidget

classmethod widget(field value attributes)Generates an INPUT text tag

see also FormWidgetwidget

99

web2py Documentation Release 2146-stable

class gluonsqlhtmlMultipleOptionsWidgetBases gluonsqlhtmlOptionsWidget

classmethod widget(field value size=5 attributes)Generates a SELECT tag including OPTIONs (multiple options allowed)

see also FormWidgetwidget

Parameters size ndash optional param (default=5) to indicate how many rows must be shown

class gluonsqlhtmlOptionsWidgetBases gluonsqlhtmlFormWidget

static has_options(field)Checks if the field has selectable options

Parameters field ndash the field needing checking

Returns True if the field has options

classmethod widget(field value attributes)Generates a SELECT tag including OPTIONs (only 1 option allowed)

see also FormWidgetwidget

class gluonsqlhtmlPasswordWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates a INPUT password tag If a value is present it will be shown as a number of lsquorsquo not related tothe length of the actual value

see also FormWidgetwidget

class gluonsqlhtmlRadioWidgetBases gluonsqlhtmlOptionsWidget

classmethod widget(field value attributes)Generates a TABLE tag including INPUT radios (only 1 option allowed)

see also FormWidgetwidget

class gluonsqlhtmlSQLFORM(table record=None deletable=False linkto=None upload=Nonefields=None labels=None col3= submit_button=rsquoSubmitrsquodelete_label=rsquoCheck to deletersquo showid=True readonly=False com-ments=True keepopts=[] ignore_rw=False record_id=Noneformstyle=None buttons=[rsquosubmitrsquo] separator=None ex-tra_fields=None attributes)

Bases gluonhtmlFORM

SQLFORM is used to map a table (and a current record) into an HTML form

Given a Table like dbtable

Generates an insert form

SQLFORM(dbtable)

Generates an update form

record=dbtable[some_id]SQLFORM(dbtable record)

Generates an update with a delete button

100 Chapter 30 sqlhtml Module

web2py Documentation Release 2146-stable

SQLFORM(dbtable record deletable=True)

Parameters

bull table ndash Table object

bull record ndash either an int if the id is an int or the record fetched from the table

bull deletable ndash adds the delete checkbox

bull linkto ndash the URL of a controllerfunction to access referencedby records

bull upload ndash the URL of a controllerfunction to download an uploaded file

bull fields ndash a list of fields that should be placed in the form default is all

bull labels ndash a dictionary with labels for each field keys are the field names

bull col3 ndash a dictionary with content for an optional third column (right of each field) keys arefield names

bull submit_button ndash text to show in the submit button

bull delete_label ndash text to show next to the delete checkbox

bull showid ndash shows the id of the record

bull readonly ndash doesnrsquot allow for any modification

bull comments ndash show comments (stored in col3 or in Field definition)

bull ignore_rw ndash overrides readablewritable attributes

bull record_id ndash used to create session key against CSRF

bull formstyle ndash what to use to generate the form layout

bull buttons ndash override buttons as you please (will be also stored in formcustomsubmit)

bull separator ndash character as separator between labels and inputs

any named optional attribute is passed to the ltformgt tag for example _class _id _style _action _method etc

AUTOTYPES = lttype intgt (integer ltgluonvalidatorsIS_INT_IN_RANGE object at 0x7fcf10deb210gt) lttype floatgt (double ltgluonvalidatorsIS_FLOAT_IN_RANGE object at 0x7fcf10deb250gt) lttype unicodegt (string None) lttype boolgt (boolean None) lttype strgt (string None) lttype listgt (liststring None) lttype datetimedatetimegt (datetime ltgluonvalidatorsIS_DATETIME object at 0x7fcf10deb310gt) lttype datetimedategt (date ltgluonvalidatorsIS_DATE object at 0x7fcf10deb2d0gt)

FIELDKEY_DELETE_RECORD = delete_record

FIELDNAME_REQUEST_DELETE = delete_this_record

ID_LABEL_SUFFIX = __label

ID_ROW_SUFFIX = __row

accepts(request_vars session=None formname=rsquo(tablename)s(record_id)srsquo keepvalues=Noneonvalidation=None dbio=True hideerror=False detect_record_change=False kwargs)

Similar to FORMaccepts but also does insert update or delete in DAL If detect_record_change is Truethan

bull formrecord_changed = False (record is properly validatedsubmitted)

bull formrecord_changed = True (record cannot be submitted because changed)

If detect_record_change == False than

bull formrecord_changed = None

assert_status(status request_vars)

101

web2py Documentation Release 2146-stable

static build_query(fields keywords)

createform(xfields)

static dictform(dictionary kwargs)

static factory(fields attributes)Generates a SQLFORM for the given fields

Internally will build a non-database based data model to hold the fields

formstyles = bootstrap ltfunction formstyle_bootstrap at 0x7fcf10de99b0gt bootstrap3_inline ltfunction _inner at 0x7fcf10de9b90gt bootstrap3_stacked ltfunction formstyle_bootstrap3_stacked at 0x7fcf10de9a28gt divs ltfunction formstyle_divs at 0x7fcf10de9848gt inline ltfunction formstyle_inline at 0x7fcf10de98c0gt table2cols ltfunction formstyle_table2cols at 0x7fcf10de97d0gt table3cols ltfunction formstyle_table3cols at 0x7fcf10dcdde8gt ul ltfunction formstyle_ul at 0x7fcf10de9938gt

static grid(query fields=None field_id=None left=None headers= or-derby=None groupby=None searchable=True sortable=True pagi-nate=20 deletable=True editable=True details=True selectable=None cre-ate=True csv=True links=None links_in_grid=True upload=rsquoltdefaultgtrsquoargs=[] user_signature=True maxtextlengths= maxtextlength=20 on-validation=None onfailure=None oncreate=None onupdate=None on-delete=None sorter_icons=(ltgluonhtmlXML objectgt ltgluonhtmlXMLobjectgt) ui=rsquoweb2pyrsquo showbuttontext=True _class=rsquoweb2py_gridrsquo form-name=rsquoweb2py_gridrsquo search_widget=rsquodefaultrsquo advanced_search=True ig-nore_rw=False formstyle=None exportclasses=None formargs= cre-ateargs= editargs= viewargs= selectable_submit_button=rsquoSubmitrsquobuttons_placement=rsquorightrsquo links_placement=rsquorightrsquo noconfirm=Falsecache_count=None client_side_delete=False ignore_common_filters=Noneauto_pagination=True use_cursor=False)

static search_menu(fields search_options=None prefix=rsquow2prsquo)

static smartdictform(session name filename=None query=None kwargs)

static smartgrid(table constraints=None linked_tables=None links=None links_in_grid=Trueargs=None user_signature=True divider=rsquogtrsquo breadcrumbs_class=rdquokwargs)

Builds a system of SQLFORMgrid(s) between any referenced tables

Parameters

bull table ndash main table

bull constraints (dict) ndash lsquotablersquoquery that limits which records can be accessible

bull links (dict) ndash like lsquotablenamersquo[lambda row A( ) ] that will add buttons whentable tablename is displayed

bull linked_tables (list) ndash list of tables to be linked

Example

given you defined a model as

dbdefine_table(person Field(name) format=(name)s)dbdefine_table(dog

Field(name) Field(owner dbperson) format=(name)s)dbdefine_table(comment Field(body) Field(dog dbdog))if db(dbperson)isempty()

from gluoncontribpopulate import populatepopulate(dbperson 300)populate(dbdog 300)populate(dbcomment 1000)

102 Chapter 30 sqlhtml Module

web2py Documentation Release 2146-stable

in a controller you can do

authrequires_login()def index()

form=SQLFORMsmartgrid(db[requestargs(0) or person])return dict(form=form)

widgets = autocomplete ltclass gluonsqlhtmlAutocompleteWidgetgt blob None boolean ltclass gluonsqlhtmlBooleanWidgetgt checkboxes ltclass gluonsqlhtmlCheckboxesWidgetgt date ltclass gluonsqlhtmlDateWidgetgt datetime ltclass gluonsqlhtmlDatetimeWidgetgt decimal ltclass gluonsqlhtmlDecimalWidgetgt double ltclass gluonsqlhtmlDoubleWidgetgt integer ltclass gluonsqlhtmlIntegerWidgetgt json ltclass gluonsqlhtmlJSONWidgetgt list ltclass gluonsqlhtmlListWidgetgt multiple ltclass gluonsqlhtmlMultipleOptionsWidgetgt options ltclass gluonsqlhtmlOptionsWidgetgt password ltclass gluonsqlhtmlPasswordWidgetgt radio ltclass gluonsqlhtmlRadioWidgetgt string ltclass gluonsqlhtmlStringWidgetgt text ltclass gluonsqlhtmlTextWidgetgt time ltclass gluonsqlhtmlTimeWidgetgt upload ltclass gluonsqlhtmlUploadWidgetgt

class gluonsqlhtmlSQLTABLE(sqlrows linkto=None upload=None orderby=None headers=truncate=16 columns=None th_link=rdquo extracolumns=None se-lectid=None renderstyle=False cid=None colgroup=False at-tributes)

Bases gluonhtmlTABLE

Given with a Rows object as returned by a db()select() generates an html table with the rows

Parameters

bull sqlrows ndash the Rows object

bull linkto ndash URL (or lambda to generate a URL) to edit individual records

bull upload ndash URL to download uploaded files

bull orderby ndash Add an orderby link to column headers

bull headers ndash dictionary of headers to headers redefinions headers can also be a string to gen-erate the headers from data for now only headers=rdquofieldnamecapitalizerdquo headers=rdquolabelsrdquoand headers=None are supported

bull truncate ndash length at which to truncate text in table cells Defaults to 16 characters

bull columns ndash a list or dict contaning the names of the columns to be shown Defaults to all

bull th_link ndash base link to support orderby headers

bull extracolumns ndash a list of dicts

bull selectid ndash The id you want to select

bull renderstyle ndash Boolean render the style with the table

bull cid ndash use this cid for all links

bull colgroup ndash FIXME

Extracolumns example

[labelA(Extra _href=)class class name of the headerwidth width in pixels or contentlambda row rc A(Edit _href=editsrowid)selected False agregate class selected to this column]

style()

class gluonsqlhtmlStringWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates an INPUT text tag

see also FormWidgetwidget

103

web2py Documentation Release 2146-stable

class gluonsqlhtmlTextWidgetBases gluonsqlhtmlFormWidget

classmethod widget(field value attributes)Generates a TEXTAREA tag

see also FormWidgetwidget

class gluonsqlhtmlTimeWidgetBases gluonsqlhtmlStringWidget

class gluonsqlhtmlUploadWidgetBases gluonsqlhtmlFormWidget

DEFAULT_WIDTH = 150px

DELETE_FILE = delete

GENERIC_DESCRIPTION = file download

ID_DELETE_SUFFIX = __delete

static is_image(value)Tries to check if the filename provided references to an image

Checking is based on filename extension Currently recognized gif png jp(e)g bmp

Parameters value ndash filename

classmethod represent(field value download_url=None)How to represent the file

bull with download url and if it is an image ltA href= gtltIMG gtltAgt

bull otherwise with download url ltA href= gtfileltAgt

bull otherwise file

Parameters

bull field ndash the field

bull value ndash the field value

bull download_url ndash url for the file download (default = None)

classmethod widget(field value download_url=None attributes)generates a INPUT file tag

Optionally provides an A link to the file including a checkbox so the file can be deleted

All is wrapped in a DIV

see also FormWidgetwidget

Parameters

bull field ndash the field

bull value ndash the field value

bull download_url ndash url for the file download (default = None)

gluonsqlhtmladd_class(a b)

104 Chapter 30 sqlhtml Module

web2py Documentation Release 2146-stable

gluonsqlhtmlform_factory(fields attributes)Generates a SQLFORM for the given fields

Internally will build a non-database based data model to hold the fields

gluonsqlhtmlformstyle_bootstrap(form fields)bootstrap 23x format form layout

gluonsqlhtmlformstyle_bootstrap3_inline_factory(col_label_size=3)bootstrap 3 horizontal form layout

Note Experimental

gluonsqlhtmlformstyle_bootstrap3_stacked(form fields)bootstrap 3 format form layout

Note Experimental

gluonsqlhtmlformstyle_divs(form fields)divs only

gluonsqlhtmlformstyle_inline(form fields)divs only but inline

gluonsqlhtmlformstyle_table2cols(form fields)2 column table

gluonsqlhtmlformstyle_table3cols(form fields)3 column table - default

gluonsqlhtmlformstyle_ul(form fields)unordered list

gluonsqlhtmlrepresent(field value record)

gluonsqlhtmlsafe_float(x)

gluonsqlhtmlsafe_int(x)

gluonsqlhtmlshow_if(cond)

105

web2py Documentation Release 2146-stable

106 Chapter 30 sqlhtml Module

CHAPTER 31

storage Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

Provides

bull List like list but returns None instead of IndexOutOfBounds

bull Storage like dictionary allowing also for objfoo for obj[lsquofoorsquo]

class gluonstorageListBases list

Like a regular python list but callable When a(i) is called if i is out of bounds returns None instead of IndexError

class gluonstorageStorageBases dict

A Storage object is like a dictionary except objfoo can be used in addition to obj[lsquofoorsquo] and setting objfoo =None deletes item foo

Example

gtgtgt o = Storage(a=1)gtgtgt print oa1

gtgtgt o[a]1

gtgtgt oa = 2gtgtgt print o[a]2

gtgtgt del oa

(continues on next page)

107

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt print oaNone

getfirst(key default=None)Returns the first value of a list or the value itself when given a requestvars style key

If the value is a list its first item will be returned otherwise the value will be returned as-is

Example output for a query string of x=abcampy=abcampy=def

gtgtgt request = Storage()gtgtgt requestvars = Storage()gtgtgt requestvarsx = abcgtgtgt requestvarsy = [abc def]gtgtgt requestvarsgetfirst(x)abcgtgtgt requestvarsgetfirst(y)abcgtgtgt requestvarsgetfirst(z)

getlast(key default=None)Returns the last value of a list or value itself when given a requestvars style key

If the value is a list the last item will be returned otherwise the value will be returned as-is

Simulated output with a query string of x=abcampy=abcampy=def

gtgtgt request = Storage()gtgtgt requestvars = Storage()gtgtgt requestvarsx = abcgtgtgt requestvarsy = [abc def]gtgtgt requestvarsgetlast(x)abcgtgtgt requestvarsgetlast(y)defgtgtgt requestvarsgetlast(z)

getlist(key)Returns a Storage value as a list

If the value is a list it will be returned as-is If object is None an empty list will be returned Otherwise[value] will be returned

Example output for a query string of x=abcampy=abcampy=def

gtgtgt request = Storage()gtgtgt requestvars = Storage()gtgtgt requestvarsx = abcgtgtgt requestvarsy = [abc def]gtgtgt requestvarsgetlist(x)[abc]gtgtgt requestvarsgetlist(y)[abc def]gtgtgt requestvarsgetlist(z)[]

class gluonstorageSettingsBases gluonstorageStorage

108 Chapter 31 storage Module

web2py Documentation Release 2146-stable

class gluonstorageMessages(T)Bases gluonstorageSettings

class gluonstorageStorageListBases gluonstorageStorage

Behaves like Storage but missing elements defaults to [] instead of None

gluonstorageload_storage(filename)

gluonstoragesave_storage(storage filename)

109

web2py Documentation Release 2146-stable

110 Chapter 31 storage Module

CHAPTER 32

streamer Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

321 Facilities to handle file streaming

gluonstreamerstream_file_or_304_or_206(static_file chunk_size=65536 request=Noneheaders= status=200 error_message=None)

gluonstreamerstreamer(stream chunk_size=65536 bytes=None)

111

web2py Documentation Release 2146-stable

112 Chapter 32 streamer Module

CHAPTER 33

template Module

This file is part of the web2py Web FrameworkLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)Author Thadeus BurgessContributors- Massimo Di Pierro for creating the original gluontemplatepy- Jonathan Lundell for extensively testing the regex on Jython- Limodou (creater of uliweb) who inspired the block-element support for web2py

331 Templating syntax

class gluontemplateBlockNode(name=rdquo pre_extend=False delimiters=(rsquorsquo rsquorsquo))Bases gluontemplateNode

Block Container

This Node can contain other Nodes and will render in a hierarchical order of when nodes were added

ie

block test This is default block test

end

append(node)Adds an element to the nodes

Parameters node ndash Node object or string to append

extend(other)Extends the list of nodes with another BlockNode class

Parameters other ndash BlockNode or Content object to extend from

113

web2py Documentation Release 2146-stable

output(blocks)Merges all nodes into a single string

Parameters blocks ndash Dictionary of blocks that are extending from this template

class gluontemplateContent(name=rsquoContentBlockrsquo pre_extend=False)Bases gluontemplateBlockNode

Parent Container ndash Used as the root level BlockNode

Contains functions that operate as such

Parameters name ndash Unique name for this BlockNode

append(node)Adds a node to list If it is a BlockNode then we assign a block for it

clear_content()

extend(other)Extends the objects list of nodes with another objects nodes

insert(other index=0)Inserts object at index

You may pass a list of objects and have them inserted

class gluontemplateDummyResponse

write(data escape=True)

class gluontemplateNOESCAPE(text)A little helper to avoid escaping

xml()

class gluontemplateNode(value=None pre_extend=False)Bases object

Basic Container Object

class gluontemplateSuperNode(name=rdquo pre_extend=False)Bases gluontemplateNode

class gluontemplateTemplateParser(text name=rsquoParserContainerrsquo context=path=rsquoviewsrsquo writer=rsquoresponsewritersquo lexers=delimiters=(rsquorsquo rsquorsquo) _super_nodes=[])

Bases object

Parse all blocks

Parameters

bull text ndash text to parse

bull context ndash context to parse in

bull path ndash folder path to templates

bull writer ndash string of writer class to use

bull lexers ndash dict of custom lexers to use

bull delimiters ndash for example (lsquolsquorsquorsquo)

114 Chapter 33 template Module

web2py Documentation Release 2146-stable

bull _super_nodes ndash a list of nodes to check for inclusion this should only be set byldquoselfextendrdquo It contains a list of SuperNodes from a child template that need to be han-dled

default_delimiters = ( )

extend(filename)Extends filename Anything not declared in a block defined by the parent will be placed in the parenttemplates include block

include(content filename)Includes filename here

parse(text)

r_multiline = lt_sreSRE_Pattern objectgt

r_tag = lt_sreSRE_Pattern objectgt

re_block = lt_sreSRE_Pattern objectgt

re_pass = lt_sreSRE_Pattern objectgt

re_unblock = lt_sreSRE_Pattern objectgt

reindent(text)Reindents a string of unindented python code

to_string()Returns the parsed template with correct indentation

Used to make it easier to port to python3

gluontemplateget_parsed(text)Returns the indented python code of text Useful for unit testing

gluontemplateoutput_aux(node blocks)

gluontemplateparse_template(filename path=rsquoviewsrsquo context= lexers= delimiters=(rsquorsquorsquorsquo))

Parameters

bull filename ndash can be a view filename in the views folder or an input stream

bull path ndash is the path of a views folder

bull context ndash is a dictionary of symbols used to render the template

bull lexers ndash dict of custom lexers to use

bull delimiters ndash opening and closing tags

gluontemplaterender(content=rsquohello worldrsquo stream=None filename=None path=None con-text= lexers= delimiters=(rsquorsquo rsquorsquo) writer=rsquoresponsewritersquo)

Generic render function

Parameters

bull content ndash default content

bull stream ndash file-like obj to read template from

bull filename ndash where to find template

bull path ndash base path for templates

bull context ndash env

331 Templating syntax 115

web2py Documentation Release 2146-stable

bull lexers ndash custom lexers to use

bull delimiters ndash opening and closing tags

bull writer ndash where to inject the resulting stream

Example

gtgtgt render()hello worldgtgtgt render(content=abc)abcgtgtgt render(content=abc)abcgtgtgt render(content=abc)abcgtgtgt render(content=anbc)anbcgtgtgt render(content=abcde)abcdegtgtgt render(content=anc)ancgtgtgt render(content=ac)acgtgtgt render(content=for i in range(a)=iltbr gtpassrarr˓context=dict(a=5))0ltbr gt1ltbr gt2ltbr gt3ltbr gt4ltbr gtgtgtgt render(content=for i in range(a)=iltbr gtpassrarr˓context=dict(a=5)delimiters=())0ltbr gt1ltbr gt2ltbr gt3ltbr gt4ltbr gtgtgtgt render(content==hellonworld)hellonworldgtgtgt render(content=for i in range(3)n=inpass)012

116 Chapter 33 template Module

CHAPTER 34

tools Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

341 Auth Mail PluginManager and various utilities

class gluontoolsMail(server=None sender=None login=None tls=True)Bases object

Class for configuring and sending emails with alternative text html body multiple attachments and encryptionsupport

Works with SMTP and Google App Engine

Parameters

bull server ndash SMTP server address in addressport notation

bull sender ndash sender email address

bull login ndash sender login name and password in loginpassword notation or None if no authen-tication is required

bull tls ndash enablesdisables encryption (True by default)

In Google App Engine use

server=gae

For sake of backward compatibility all fields are optional and default to None however to be able to send emailsat least server and sender must be specified They are available under following fields

117

web2py Documentation Release 2146-stable

mailsettingsservermailsettingssendermailsettingsloginmailsettingstimeout = 60 seconds (default)

When server is lsquologgingrsquo email is logged but not sent (debug mode)

Optionally you can use PGP encryption or X509

mailsettingscipher_type = Nonemailsettingsgpg_home = Nonemailsettingssign = Truemailsettingssign_passphrase = Nonemailsettingsencrypt = Truemailsettingsx509_sign_keyfile = Nonemailsettingsx509_sign_certfile = Nonemailsettingsx509_sign_chainfile = Nonemailsettingsx509_nocerts = Falsemailsettingsx509_crypt_certfiles = None

cipher_type Nonegpg - need a python-pyme package and gpgme libx509 - smime

gpg_home you can set a GNUPGHOME environment variableto specify home of gnupg

sign sign the message (True or False)sign_passphrase passphrase for key signingencrypt encrypt the message (True or False) It defaults

to True x509 only

x509_sign_keyfile the signers private key filename orstring containing the key (PEM format)

x509_sign_certfile the signers certificate filename orstring containing the cert (PEM format)

x509_sign_chainfile sets the optional all-in-one file where youcan assemble the certificates of CertificationAuthorities (CA) which form the certificatechain of email certificate It can be astring containing the certs to (PEM format)

x509_nocerts if True then no attached certificate in mailx509_crypt_certfiles the certificates file or strings to encrypt

the messages with can be a file name string or a list of file names strings (PEM format)

Examples

Create Mail object with authentication data for remote server

mail = Mail(examplecom25 meexamplecom mepassword)

Notice for GAE users attachments have an automatic content_id=rsquoattachment-irsquo where i is progressive num-ber in this way the can be referenced from the HTML as ltimg src=rdquocidattachment-0rdquo gt etc

118 Chapter 34 tools Module

web2py Documentation Release 2146-stable

class Attachment(payload filename=None content_id=None content_type=Noneencoding=rsquoutf-8rsquo)

Bases emailmimebaseMIMEBase

Email attachment

Parameters

bull payload ndash path to file or file-like object with read() method

bull filename ndash name of the attachment stored in message if set to None it will be fetchedfrom payload path file-like object payload must have explicit filename specified

bull content_id ndash id of the attachment automatically contained within lt and gt

bull content_type ndash content type of the attachment if set to None it will be fetched fromfilename using gluoncontenttype module

bull encoding ndash encoding of all strings passed to this function (except attachment body)

Content ID is used to identify attachments within the html body in example attached image with contentID lsquophotorsquo may be used in html message as a source of img tag ltimg src=rdquocidphotordquo gt

Example Create attachment from text file

attachment = MailAttachment(pathtofiletxt)

Content-Type textplainMIME-Version 10Content-Disposition attachment filename=filetxtContent-Transfer-Encoding base64

SOMEBASE64CONTENT=

Create attachment from image file with custom filename and cid

attachment = MailAttachment(pathtofilepngfilename=photopngcontent_id=photo)

Content-Type imagepngMIME-Version 10Content-Disposition attachment filename=photopngContent-Id ltphotogtContent-Transfer-Encoding base64

SOMEOTHERBASE64CONTENT=

send(to subject=rsquo[no subject]rsquo message=rsquo[no message]rsquo attachments=None cc=None bcc=Nonereply_to=None sender=None encoding=rsquoutf-8rsquo raw=False headers= from_address=Nonecipher_type=None sign=None sign_passphrase=None encrypt=None x509_sign_keyfile=Nonex509_sign_chainfile=None x509_sign_certfile=None x509_crypt_certfiles=Nonex509_nocerts=None)

Sends an email using data specified in constructor

Parameters

bull to ndash list or tuple of receiver addresses will also accept single object

bull subject ndash subject of the email

bull message ndash email body text depends on type of passed object

341 Auth Mail PluginManager and various utilities 119

web2py Documentation Release 2146-stable

ndash if 2-list or 2-tuple is passed first element will be source of plain text while second ofhtml text

ndash otherwise object will be the only source of plain text and html source will be set toNone

If text or html source is

ndash None content part will be ignored

ndash string content part will be set to it

ndash file-like object content part will be fetched from it using itrsquos read() method

bull attachments ndash list or tuple of MailAttachment objects will also accept single object

bull cc ndash list or tuple of carbon copy receiver addresses will also accept single object

bull bcc ndash list or tuple of blind carbon copy receiver addresses will also accept single object

bull reply_to ndash address to which reply should be composed

bull encoding ndash encoding of all strings passed to this method (including message bodies)

bull headers ndash dictionary of headers to refine the headers just before sending mail eg lsquoX-Mailerrsquo lsquoweb2py mailerrsquo

bull from_address ndash address to appear in the lsquoFromrsquo header this is not the envelopesender If not specified the sender will be used

bull cipher_type ndash gpg - need a python-pyme package and gpgme lib x509 - smime

bull gpg_home ndash you can set a GNUPGHOME environment variable to specify home ofgnupg

bull sign ndash sign the message (True or False)

bull sign_passphrase ndash passphrase for key signing

bull encrypt ndash encrypt the message (True or False) It defaults to True x509 only

bull x509_sign_keyfile ndash the signers private key filename or string containing the key(PEM format)

bull x509_sign_certfile ndash the signers certificate filename or string containing the cert(PEM format)

bull x509_sign_chainfile ndash sets the optional all-in-one file where you can assemblethe certificates of Certification Authorities (CA) which form the certificate chain of emailcertificate It can be a string containing the certs to (PEM format)

bull x509_nocerts ndash if True then no attached certificate in mail

bull x509_crypt_certfiles ndash the certificates file or strings to encrypt the messages withcan be a file name string or a list of file names strings (PEM format)

Examples

Send plain text message to single address

mailsend(youexamplecomMessage subjectPlain text body of the message)

120 Chapter 34 tools Module

web2py Documentation Release 2146-stable

Send html message to single address

mailsend(youexamplecomMessage subjectlthtmlgtPlain text body of the messagelthtmlgt)

Send text and html message to three addresses (two in cc)

mailsend(youexamplecomMessage subject(Plain text body lthtmlgthtml bodylthtmlgt)cc=[other1examplecom other2examplecom])

Send html only message with image attachment available from the message by lsquophotorsquo content id

mailsend(youexamplecomMessage subject(None lthtmlgtltimg src=cidphoto gtlthtmlgt)MailAttachment(pathtophotojpg

content_id=photo))

Send email with two attachments and no body text

mailsend(youexamplecomMessage subjectNone[MailAttachment(pathtofistfile)MailAttachment(pathtosecondfile)])

Returns True on success False on failure

Before return method updates two objectrsquos fields

bull selfresult return value of smtplibSMTPsendmail() or GAErsquos mailsend_mail() method

bull selferror Exception message or None if above was successful

class gluontoolsAuth(environment=None db=None mailer=True hmac_key=None con-troller=rsquodefaultrsquo function=rsquouserrsquo cas_provider=None signature=Truesecure=False csrf_prevention=True propagate_extension=Noneurl_index=None jwt=None host_names=None)

Bases object

accessible_query(name table user_id=None)Returns a query with all accessible records for user_id or the current logged in user this method does notwork on GAE because uses JOIN and IN

Example

Use as

db(authaccessible_query(read dbmytable))select(dbmytableALL)

add_group(role description=rdquo)Creates a group associated to a role

add_membership(group_id=None user_id=None role=None)Gives user_id membership of group_id or role if user is None than user_id is that of current logged in user

341 Auth Mail PluginManager and various utilities 121

web2py Documentation Release 2146-stable

add_permission(group_id name=rsquoanyrsquo table_name=rdquo record_id=0)Gives group_id lsquonamersquo access to lsquotable_namersquo and lsquorecord_idrsquo

allows_jwt(otherwise=None)

static archive(form archive_table=None current_record=rsquocurrent_recordrsquoarchive_current=False fields=None)

If you have a table (dbmytable) that needs full revision history you can just do

form = crudupdate(dbmytable myrecord onaccept=autharchive)

or

form = SQLFORM(dbmytable myrecord)process(onaccept=autharchive)

crudarchive will define a new table ldquomytable_archiverdquo and store a copy of the current record (ifarchive_current=True) or a copy of the previous record (if archive_current=False) in the newly createdtable including a reference to the current record

fields allows to specify extra fields that need to be archived

If you want to access such table you need to define it yourself in a model

dbdefine_table(mytable_archiveField(current_record dbmytable)dbmytable)

Notice such table includes all fields of dbmytable plus one current_record crudarchive does not times-tamp the stored record unless your original table has a fields like

dbdefine_table(Field(saved_on datetime

default=requestnow update=requestnow writable=False)Field(saved_by authuser

default=authuser_id update=authuser_id writable=False)

there is nothing special about these fields since they are filled before the record is archived

If you want to change the archive table name and the name of the reference field you can do for example

dbdefine_table(myhistoryField(parent_record dbmytable) dbmytable)

and use it as

form = crudupdate(dbmytable myrecordonaccept=lambda formcrudarchive(form

archive_table=dbrarr˓myhistory

current_record=parent_rarr˓record))

basic(basic_auth_realm=False)Performs basic login

Parameters basic_auth_realm ndash optional basic http authentication realm Can take str orunicode or function or callable or boolean

reads currentrequestenvhttp_authorization and returns basic_allowedbasic_accepteduser

122 Chapter 34 tools Module

web2py Documentation Release 2146-stable

if basic_auth_realm is defined is a callable itrsquos return value is used to set the basic authentication realm ifitrsquos a string its content is used instead Otherwise basic authentication realm is set to the application nameIf basic_auth_realm is None or False (the default) the behavior is to skip sending any challenge

bulk_register(max_emails=100)Creates a form for ther user to send invites to other users to join

cas_login(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt version=2)

cas_validate(version=2 proxy=False)

change_password(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form that lets the user change password

confirm_registration(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form to confirm user registration

default_messages = access_denied Insufficient privileges add_group_log Group (group_id)s created add_membership_log None add_permission_log None bulk_invite_body You have been invited to join (site)s click (link)s to complete the process bulk_invite_subject Invitation to join (site)s change_password_log User (id)s Password changed del_group_log Group (group_id)s deleted del_membership_log None del_permission_log None delete_label Check to delete email_sent Email sent email_taken This email already has an account email_verified Email verified function_disabled Function disabled group_description Group uniquely assigned to user (id)s has_membership_log None has_permission_log None impersonate_log User (id)s is impersonating (other_id)s invalid_email Invalid email invalid_login Invalid login invalid_password Invalid password invalid_reset_password Invalid reset password invalid_two_factor_code Incorrect code 0 more attempt(s) remaining invalid_user Invalid user invalid_username Invalid username is_empty Cannot be empty label_client_ip Client IP label_description Description label_email E-mail label_first_name First name label_group_id Group ID label_last_name Last name label_name Name label_origin Origin label_password Password label_record_id Record ID label_registration_id Registration identifier label_registration_key Registration key label_remember_me Remember me (for 30 days) label_reset_password_key Reset Password key label_role Role label_table_name Object or table name label_time_stamp Timestamp label_two_factor Authentication code label_user_id User ID label_username Username logged_in Logged in logged_out Logged out login_button Log In login_disabled Login disabled by administrator login_failed_log None login_log User (id)s Logged-in logout_log User (id)s Logged-out mismatched_password Password fields dont match new_password New password new_password_sent A new password was emailed to you old_password Old password password_change_button Change password password_changed Password changed password_reset_button Request reset password profile_log User (id)s Profile updated profile_save_button Apply changes profile_updated Profile updated register_button Sign Up register_log User (id)s Registered registration_pending Registration is pending approval registration_successful Registration successful registration_verifying Registration needs verification reset_password Click on the link (link)s to reset your password reset_password_log User (id)s Password reset reset_password_subject Password reset retrieve_password Your password is (password)s retrieve_password_log User (id)s Password retrieved retrieve_password_subject Password retrieve retrieve_two_factor_code Your temporary login code is 0 retrieve_two_factor_code_subject Two-step Login Authentication Code retrieve_username Your username is (username)s retrieve_username_log User (id)s Username retrieved retrieve_username_subject Username retrieve submit_button Submit two_factor_comment This code was emailed to you and is required for login unable_send_email Unable to send email unable_to_send_email Unable to send email username_sent Your username was emailed to you username_taken Username already taken verify_email Welcome (username)s Click on the link (link)s to verify your email verify_email_log User (id)s Verification email sent verify_email_subject Email verification verify_password Verify Password verify_password_comment please input your password againClass for authentication authorization role based access control

Includes

bull registration and profile

bull login and logout

bull username and password retrieval

bull event logging

bull role creation and assignment

bull user defined grouprole based permission

Parameters

bull environment ndash is there for legacy but unused (awful)

bull db ndash has to be the database where to create tables for authentication

bull mailer ndash Mail( ) or None (no mailer) or True (make a mailer)

bull hmac_key ndash can be a hmac_key or hmac_key=Authget_or_create_key()

bull controller ndash (where is the user action)

bull cas_provider ndash (delegate authentication to the URL CAS2)

Authentication Example

from gluoncontributils import mail=Mail()mailsettingsserver=smtpgmailcom587mailsettingssender=yousomewherecommailsettingslogin=usernamepasswordauth=Auth(db)authsettingsmailer=mail authsettings=authdefine_tables()def authentication()

return dict(form=auth())

341 Auth Mail PluginManager and various utilities 123

web2py Documentation Release 2146-stable

Exposes

bull http applicationcontrollerauthenticationlogin

bull http applicationcontrollerauthenticationlogout

bull http applicationcontrollerauthenticationregister

bull http applicationcontrollerauthenticationverify_email

bull http applicationcontrollerauthenticationretrieve_username

bull http applicationcontrollerauthenticationretrieve_password

bull http applicationcontrollerauthenticationreset_password

bull http applicationcontrollerauthenticationprofile

bull http applicationcontrollerauthenticationchange_password

On registration a group with role=new_userid is created and user is given membership of this group

You can create a group with

group_id=authadd_group(Manager can access the manage action)authadd_permission(group_id access to manage)

Here ldquoaccess to managerdquo is just a user defined string You can give access to a user

authadd_membership(group_id user_id)

If user id is omitted the logged in user is assumed

Then you can decorate any action

authrequires_permission(access to manage)def manage()

return dict()

You can restrict a permission to a specific table

authadd_permission(group_id edit dbsometable)authrequires_permission(edit dbsometable)

Or to a specific record

authadd_permission(group_id edit dbsometable 45)authrequires_permission(edit dbsometable 45)

If authorization is not granted calls

authsettingson_failed_authorization

Other options

authsettingsmailer=Noneauthsettingsexpiration=3600 seconds

these are messages that can be customized

124 Chapter 34 tools Module

web2py Documentation Release 2146-stable

default_settings = allow_basic_login False allow_basic_login_only False allow_delete_accounts False alternate_requires_registration False auth_manager_role None auth_two_factor_enabled False auth_two_factor_tries_left 3 bulk_register_enabled False captcha None cas_maps None client_side True create_user_groups user_(id)s email_case_sensitive True everybody_group_id None expiration 3600 formstyle None hideerror False keep_session_onlogin True keep_session_onlogout False label_separator None logging_enabled True login_after_password_change True login_after_registration False login_captcha None login_email_validate True login_userfield None logout_onlogout None long_expiration 2592000 manager_actions multi_login False on_failed_authentication ltfunction ltlambdagt at 0x7fcf0cf9f578gt ondelete CASCADE password_field password password_min_length 4 pre_registration_div None prevent_open_redirect_attacks True prevent_password_reset_attacks True profile_fields None register_captcha None register_fields None register_verify_password True registration_requires_approval False registration_requires_verification False remember_me_form True renew_session_onlogin True renew_session_onlogout True reset_password_requires_verification False retrieve_password_captcha None retrieve_username_captcha None showid False table_cas None table_cas_name auth_cas table_event None table_event_name auth_event table_group None table_group_name auth_group table_membership None table_membership_name auth_membership table_permission None table_permission_name auth_permission table_token_name auth_token table_user None table_user_name auth_user two_factor_authentication_group None update_fields [email] use_username False username_case_sensitive True wiki ltStorage gt

define_signature()

define_tables(username=None signature=None enable_tokens=False migrate=Nonefake_migrate=None)

To be called unless tables are defined manually

Examples

Use as

defines all needed tables and table files myprefix_auth_usertable authdefine_tables(migrate=myprefix_)

defines all needed tables without migrationtable filesauthdefine_tables(migrate=False)

del_group(group_id)Deletes a group

del_membership(group_id=None user_id=None role=None)Revokes membership from group_id to user_id if user_id is None than user_id is that of current logged inuser

del_permission(group_id name=rsquoanyrsquo table_name=rdquo record_id=0)Revokes group_id lsquonamersquo access to lsquotable_namersquo and lsquorecord_idrsquo

email_registration(subject body user)Sends and email invitation to a user informing they have been registered with the application

email_reset_password(user)

enable_record_versioning(tables archive_db=None archive_names=rsquo(tablename)s_archiversquocurrent_record=rsquocurrent_recordrsquo current_record_label=None)

Used to enable full record versioning (including auth tables)

auth = Auth(db)authdefine_tables(signature=True) define our own tablesdbdefine_table(mythingField(name)authsignature)authenable_record_versioning(tables=db)

tables can be the db (all table) or a list of tables only tables with modified_by and modified_on fiels (ascreated by authsignature) will have versioning Old record versions will be in table lsquomything_archiversquoautomatically defined

when you enable enable_record_versioning records are never deleted but marked with is_active=False

enable_record_versioning enables a common_filter for every table that filters out records with is_active =False

Note If you use authenable_record_versioning do not use autharchive or you will end up with dupli-cates autharchive does explicitly what enable_record_versioning does automatically

static get_or_create_key(filename=None alg=rsquosha512rsquo)

341 Auth Mail PluginManager and various utilities 125

web2py Documentation Release 2146-stable

get_or_create_user(keys update_fields=[rsquoemailrsquo] login=True get=True)Used for alternate login methods If the user exists already then password is updated If the user doesnrsquotyet exist then they are created

get_vars_next()

groups()Displays the groups and their roles for the logged in user

has_membership(group_id=None user_id=None role=None)Checks if user is member of group_id or role

has_permission(name=rsquoanyrsquo table_name=rdquo record_id=0 user_id=None group_id=None)Checks if user_id or current logged in user is member of a group that has lsquonamersquo permission on lsquota-ble_namersquo and lsquorecord_idrsquo if group_id is passed it checks whether the group has the permission

here()

id_group(role)Returns the group_id of the group specified by the role

impersonate(user_id=ltfunction ltlambdagtgt)To use this make a POST to http impersonate requestpost_varsuser_id=ltidgt

Set requestpost_varsuser_id to 0 to restore original user

requires impersonator is logged in and

has_permission(impersonate auth_user user_id)

is_impersonating()

is_logged_in()Checks if the user is logged in and returns TrueFalse If so user is in authuser as well as in ses-sionauthuser

jwt()To use JWT authentication 1) instantiate auth with

auth = Auth(db jwt = secret_keysecret)

where lsquosecretrsquo is your own secret string

2 Decorate functions that require login but should accept the JWT token credentials

authallows_jwt()authrequires_login()def myapi() return hello s authuseremail

Notice jwt is allowed but not required if user is logged in myapi is accessible

3 Use it

Now API users can obtain a token with

http appdefaultuserjwtusername= amppassword=

(returns json object with a token attribute) API users can refresh an existing token with

http appdefaultuserjwttoken=

they can authenticate themselves when calling http myapi by injecting a header

Authorization Bearer ltthe jwt tokengt

126 Chapter 34 tools Module

web2py Documentation Release 2146-stable

Any additional attributes in the jwt argument of Auth() below

auth = Auth(db jwt = )

are passed to the constructor of class AuthJWT Look there for documentation

log_event(description vars=None origin=rsquoauthrsquo)

Examples

Use as

authlog_event(description=this happened origin=auth)

login(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a login form

login_bare(username password)Logins user as specified by username (or email) and password

login_user(user)Logins the user = dbauth_user(id)

logout(next=ltfunction ltlambdagtgt onlogout=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)Logouts and redirects to login

logout_bare()

manage_tokens()

navbar(prefix=rsquoWelcomersquo action=None separators=(rsquo [ rsquo rsquo | rsquo rsquo ] rsquo) user_identifier=ltfunctionltlambdagtgt referrer_actions=ltfunction ltlambdagtgt mode=rsquodefaultrsquo)

Navbar with support for more templates This uses some code from the old navbar

Parameters mode ndash see options for list of

not_authorized()You can change the view for this page to make it look as you like

profile(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form that lets the user change hisher profile

random_password()

register(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a registration form

register_bare(fields)Registers a user as specified by username (or email) and a raw password

request_reset_password(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgtonaccept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form to reset the user password

requires(condition requires_login=True otherwise=None)Decorator that prevents access to action if not logged in

requires_login(otherwise=None)Decorator that prevents access to action if not logged in

341 Auth Mail PluginManager and various utilities 127

web2py Documentation Release 2146-stable

requires_login_or_token(otherwise=None)

requires_membership(role=None group_id=None otherwise=None)Decorator that prevents access to action if not logged in or if user logged in is not a member of group_idIf role is provided instead of group_id then the group_id is calculated

requires_permission(name table_name=rdquo record_id=0 otherwise=None)Decorator that prevents access to action if not logged in or if user logged in is not a member of any group(role) that has lsquonamersquo access to lsquotable_namersquo lsquorecord_idrsquo

requires_signature(otherwise=None hash_vars=True)Decorator that prevents access to action if not logged in or if user logged in is not a member of group_idIf role is provided instead of group_id then the group_id is calculated

reset_password(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form to reset the user password

reset_password_deprecated(next=ltfunction ltlambdagtgt onvalidation=ltfunctionltlambdagtgt onaccept=ltfunction ltlambdagtgt log=ltfunctionltlambdagtgt)

Returns a form to reset the user password (deprecated)

retrieve_password(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

retrieve_username(next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgt)

Returns a form to retrieve the user username (only if there is a username field)

run_login_onaccept()

select_host(host host_names=None)checks that host is valid ie in the list of glob host_names if the host is missing then is it selects the firstentry from host_names read more here httpsgithubcomweb2pyweb2pyissues1196

table_cas()

table_event()

table_group()

table_membership()

table_permission()

table_token()

table_user()

update_groups()

url(f=None args=None vars=None scheme=False)

user_group(user_id=None)Returns the group_id of the group uniquely associated to this user ie role=user[user_id]

user_group_role(user_id=None)

user_iduserid or None

verify_email(next=ltfunction ltlambdagtgt onaccept=ltfunction ltlambdagtgt log=ltfunctionltlambdagtgt)

Action used to verify the registration email

128 Chapter 34 tools Module

web2py Documentation Release 2146-stable

when_is_logged_in_bypass_next_in_url(next session)This function should be use when someone want to avoid asking for user credentials when loaded pagecontains ldquouserlogin_next=NEXT_COMPONENTrdquo in the URL is refresh but user is already authenti-cated

wiki(slug=None env=None render=rsquomarkminrsquo manage_permissions=False force_prefix=rdquo re-strict_search=False resolve=True extra=None menu_groups=None templates=None mi-grate=True controller=None function=None force_render=False groups=None)

wikimenu()To be used in menupy for app wide wiki menus

class gluontoolsRecaptcha(request=None public_key=rdquo private_key=rdquo use_ssl=False er-ror=None error_message=rsquoinvalidrsquo label=rsquoVerifyrsquo options=rdquocomment=rdquo ajax=False)

Bases gluonhtmlDIV

Examples

Use as

form = FORM(Recaptcha(public_key= private_key=))

or

form = SQLFORM()formappend(Recaptcha(public_key= private_key=))

API_SERVER = httpwwwgooglecomrecaptchaapi

API_SSL_SERVER = httpswwwgooglecomrecaptchaapi

VERIFY_SERVER = httpwwwgooglecomrecaptchaapiverify

xml()generates the xml for this component

class gluontoolsRecaptcha2(request=None public_key=rdquo private_key=rdquo er-ror_message=rsquoinvalidrsquo label=rsquoVerifyrsquo options=None com-ment=rdquo)

Bases gluonhtmlDIV

Experimental Creates a DIV holding the newer Recaptcha from Google (v2)

Parameters

bull request ndash the request If not passed uses current request

bull public_key ndash the public key Google gave you

bull private_key ndash the private key Google gave you

bull error_message ndash the error message to show if verification fails

bull label ndash the label to use

bull options (dict) ndash takes these parameters

ndash hl

ndash theme

ndash type

341 Auth Mail PluginManager and various utilities 129

web2py Documentation Release 2146-stable

ndash tabindex

ndash callback

ndash expired-callback

see httpsdevelopersgooglecomrecaptchadocsdisplay for docs about those

bull comment ndash the comment

Examples

Use as

form = FORM(Recaptcha2(public_key= private_key=))

or

form = SQLFORM()formappend(Recaptcha2(public_key= private_key=))

to protect the login page instead use

from gluontools import Recaptcha2authsettingscaptcha = Recaptcha2(request public_key= private_key=)

API_URI = httpswwwgooglecomrecaptchaapijs

VERIFY_SERVER = httpswwwgooglecomrecaptchaapisiteverify

xml()generates the xml for this component

class gluontoolsCrud(environment db=None controller=rsquodefaultrsquo)Bases object

static archive(form archive_table=None current_record=rsquocurrent_recordrsquo)

create(table next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onaccept=ltfunctionltlambdagtgt log=ltfunction ltlambdagtgt message=ltfunction ltlambdagtgt form-name=ltfunction ltlambdagtgt attributes)

delete(table record_id next=ltfunction ltlambdagtgt message=ltfunction ltlambdagtgt)

get_format(field)

get_query(field op value refsearch=False)

has_permission(name table record=0)

log_event(message vars)

read(table record)

rows(table query=None fields=None orderby=None limitby=None)

search(tables args)Creates a search form and its results for a table rubric Examples

Use as

130 Chapter 34 tools Module

web2py Documentation Release 2146-stable

form results = crudsearch(dbtestqueries = [equals not equal contains]query_labels=equalsEquals

not equalNot equalfields = [idchildren]field_labels =

idIDchildrenChildrenzero=Please choosequery = (dbtestid gt 0)amp(dbtestid = 3) )

select(table query=None fields=None orderby=None limitby=None headers=None attr)

tables()

update(table record next=ltfunction ltlambdagtgt onvalidation=ltfunction ltlambdagtgt onac-cept=ltfunction ltlambdagtgt ondelete=ltfunction ltlambdagtgt log=ltfunction ltlambdagtgtmessage=ltfunction ltlambdagtgt deletable=ltfunction ltlambdagtgt formname=ltfunctionltlambdagtgt attributes)

url(f=None args=None vars=None)This should point to the controller that exposes download and crud

class gluontoolsService(environment=None)Bases object

exception JsonRpcException(code info)Bases exceptionsException

amfrpc(f)

Example

Use as

service = Service()serviceamfrpcdef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget httpappdefaultcallamfrpcmyfunctiona=helloampb=world

amfrpc3(domain=rsquodefaultrsquo)

Example

Use as

service = Service()serviceamfrpc3(domain)def myfunction(a b)

return a + bdef call()

return service()

341 Auth Mail PluginManager and various utilities 131

web2py Documentation Release 2146-stable

Then call it with

wget http appdefaultcallamfrpc3myfunctiona=helloampb=world

csv(f)

Example

Use as

service = Service()servicecsvdef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget httpappdefaultcallcsvmyfunctiona=3ampb=4

error()

json(f)

Example

Use as

service = Service()servicejsondef myfunction(a b)

return [a b]def call()

return service()

Then call it with

wget http appdefaultcalljsonmyfunctiona=helloampb=world

jsonrpc(f)

Example

Use as

service = Service()servicejsonrpcdef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget http appdefaultcalljsonrpcmyfunctiona=helloampb=world

132 Chapter 34 tools Module

web2py Documentation Release 2146-stable

jsonrpc2(f)

Example

Use as

service = Service()servicejsonrpc2def myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget ndashpost-data lsquoldquojsonrpcrdquo ldquo20rdquo ldquoidrdquo 1 ldquomethodrdquo ldquomyfunctionrdquo ldquoparamsrdquo ldquoardquo 1 ldquobrdquo2rsquo http appdefaultcalljsonrpc2

jsonrpc_errors = -32700 (Parse error Invalid JSON was received by the server An error occurred on the server while parsing the JSON text) -32603 (Internal error Internal JSON-RPC error) -32602 (Invalid params Invalid method parameter(s)) -32601 (Method not found The method does not exist is not available) -32600 (Invalid Request The JSON sent is not a valid Request object) -32099 (Server error Reserved for implementation-defined server-errors)

rss(f)

Example

Use as

service = Service()servicerssdef myfunction()

return dict(title= link= description=created_on= entries=[dict(title= link=

description= created_on=])def call()

return service()

Then call it with

wget http appdefaultcallrssmyfunction

run(f)

Example

Use as

service = Service()servicerundef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget httpappdefaultcallrunmyfunctiona=3ampb=4

341 Auth Mail PluginManager and various utilities 133

web2py Documentation Release 2146-stable

serve_amfrpc(version=0)

serve_csv(args=None)

serve_json(args=None)

serve_jsonrpc()

serve_jsonrpc2(data=None batch_element=False)

serve_rss(args=None)

serve_run(args=None)

serve_soap(version=rsquo11rsquo)

serve_xml(args=None)

serve_xmlrpc()

soap(name=None returns=None args=None doc=None)

Example

Use as

service = Service()servicesoap(MyFunctionreturns=resultintargs=aintbint)def myfunction(a b)

return a + bdef call()

return service()

Then call it with

from gluoncontribpysimplesoapclient import SoapClientclient = SoapClient(wsdl=httpappdefaultcallsoapWSDL)response = clientMyFunction(a=1b=2)return response[result]

It also exposes online generated documentation and xml example messages athttp appdefaultcallsoap

xml(f)

Example

Use as

service = Service()servicexmldef myfunction(a b)

return a + bdef call()

return service()

Then call it with

wget httpappdefaultcallxmlmyfunctiona=3ampb=4

134 Chapter 34 tools Module

web2py Documentation Release 2146-stable

xmlrpc(f)

Example

Use as

service = Service()servicexmlrpcdef myfunction(a b)

return a + bdef call()

return service()

The call it with

wget http appdefaultcallxmlrpcmyfunctiona=helloampb=world

class gluontoolsWiki(auth env=None render=rsquomarkminrsquo manage_permissions=Falseforce_prefix=rdquo restrict_search=False extra=None menu_groups=Nonetemplates=None migrate=True controller=None function=Nonegroups=None)

Bases object

automenu()adds the menu if not present

can_edit(page=None)

can_manage()

can_read(page)

can_search()

can_see_menu()

cloud()

static component(text)In wiki docs allows componentcontrollerfunctionargs which renders as a LOAD( ajax=True)

create()

edit(slug from_template=0)

editmedia(slug)

everybody = everybody

first_paragraph(page)

fix_hostname(body)

get_renderer()

html_render(page)

markmin_base(body)

markmin_render(page)

media(id)

menu(controller=rsquodefaultrsquo function=rsquoindexrsquo)

341 Auth Mail PluginManager and various utilities 135

web2py Documentation Release 2146-stable

not_authorized(page=None)

pages()

preview(render)

read(slug force_render=False)

render_tags(tags)

rows_page = 25

search(tags=None query=None cloud=True preview=True limitby=(0 100) orderby=None)

class gluontoolsPluginManager(plugin=None defaults)Bases object

Plugin Manager is similar to a storage object but it is a single level singleton This means that multiple instanceswithin the same thread share the same attributes Its constructor is also special The first argument is the nameof the plugin you are defining The named arguments are parameters needed by the plugin with default valuesIf the parameters were previous defined the old values are used

Example

in some general configuration file

plugins = PluginManager()pluginsmeparam1=3

within the plugin model

_ = PluginManager(meparam1=5param2=6param3=7)

where the plugin is used

gtgtgt print pluginsmeparam13gtgtgt print pluginsmeparam26gtgtgt pluginsmeparam3 = 8gtgtgt print pluginsmeparam38

Here are some tests

gtgtgt a=PluginManager()gtgtgt ax=6gtgtgt b=PluginManager(check)gtgtgt print bx6gtgtgt b=PluginManager() reset settingsgtgtgt print bxltStorage gtgtgtgt bx=7gtgtgt print ax7gtgtgt ayz=8gtgtgt print byz8

(continues on next page)

136 Chapter 34 tools Module

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt test_thread_separation()5gtgtgt plugins=PluginManager(medb=mydb)gtgtgt print pluginsmedbmydbgtgtgt print me in pluginsTruegtgtgt print pluginsmeinstalledTrue

instances =

keys()

gluontoolsfetch(url data=None headers=None cookie= user_agent=rsquoMozilla50rsquo)

gluontoolsgeocode(address)

gluontoolsreverse_geocode(lat lng lang=None)Try to get an approximate address for a given latitude longitude

gluontoolsprettydate(d T=ltfunction ltlambdagtgt utc=False)

341 Auth Mail PluginManager and various utilities 137

web2py Documentation Release 2146-stable

138 Chapter 34 tools Module

CHAPTER 35

utf8 Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)Created by Vladyslav Kozlovskyy (Ukraine) ltdbdevelopcopygmailcomgtfor Web2py project

351 Utilities and class for UTF8 strings managing

class gluonutf8Utf8Bases str

Class for utf8 string storing and manipulations

The base presupposition of this class usage is ldquoALL strings in the application are either of utf-8 or unicodetype even when simple str type is used UTF-8 is only a ldquopackedrdquo version of unicode so Utf-8 and unicodestrings are interchangeablerdquo

CAUTION This class is slower than strunicode Do NOT use it inside intensive loops Simply decode string(s)to unicode before loop and encode it back to utf-8 string(s) after intensive calculation

You can see the benefit of this class in doctests() below

capitalize()rarr stringReturn a copy of the string S with only its first character capitalized

center(width[ fillchar ])rarr stringReturn S centered in a string of length width Padding is done using the specified fill character (default isa space)

count(sub[ start[ end ]])rarr intReturn the number of non-overlapping occurrences of substring sub in string S[startend] Optional argu-ments start and end are interpreted as in slice notation

139

web2py Documentation Release 2146-stable

decode([encoding[ errors]])rarr objectDecodes S using the codec registered for encoding encoding defaults to the default encoding errors maybe given to set a different error handling scheme Default is lsquostrictrsquo meaning that encoding errors raise aUnicodeDecodeError Other possible values are lsquoignorersquo and lsquoreplacersquo as well as any other name registeredwith codecsregister_error that is able to handle UnicodeDecodeErrors

encode([encoding[ errors]])rarr objectEncodes S using the codec registered for encoding encoding defaults to the default encoding errors maybe given to set a different error handling scheme Default is lsquostrictrsquo meaning that encoding errors raise aUnicodeEncodeError Other possible values are lsquoignorersquo lsquoreplacersquo and lsquoxmlcharrefreplacersquo as well as anyother name registered with codecsregister_error that is able to handle UnicodeEncodeErrors

endswith(suffix[ start[ end ]])rarr boolReturn True if S ends with the specified suffix False otherwise With optional start test S beginning atthat position With optional end stop comparing S at that position suffix can also be a tuple of strings totry

expandtabs([tabsize])rarr stringReturn a copy of S where all tab characters are expanded using spaces If tabsize is not given a tab size of8 characters is assumed

find(sub[ start[ end ]])rarr intReturn the lowest index in S where substring sub is found such that sub is contained within S[startend]Optional arguments start and end are interpreted as in slice notation

Return -1 on failure

format(args kwargs)rarr stringReturn a formatted version of S using substitutions from args and kwargs The substitutions are identifiedby braces (lsquolsquo and lsquorsquo)

index(sub[ start[ end ]])rarr intLike Sfind() but raise ValueError when the substring is not found

isalnum()rarr boolReturn True if all characters in S are alphanumeric and there is at least one character in S False otherwise

isalpha()rarr boolReturn True if all characters in S are alphabetic and there is at least one character in S False otherwise

isdigit()rarr boolReturn True if all characters in S are digits and there is at least one character in S False otherwise

islower()rarr boolReturn True if all cased characters in S are lowercase and there is at least one cased character in S Falseotherwise

isspace()rarr boolReturn True if all characters in S are whitespace and there is at least one character in S False otherwise

istitle()rarr boolReturn True if S is a titlecased string and there is at least one character in S ie uppercase characters mayonly follow uncased characters and lowercase characters only cased ones Return False otherwise

isupper()rarr boolReturn True if all cased characters in S are uppercase and there is at least one cased character in S Falseotherwise

join(iterable)rarr stringReturn a string which is the concatenation of the strings in the iterable The separator between elements isS

140 Chapter 35 utf8 Module

web2py Documentation Release 2146-stable

ljust(width[ fillchar ])rarr stringReturn S left-justified in a string of length width Padding is done using the specified fill character (defaultis a space)

lower()rarr stringReturn a copy of the string S converted to lowercase

lstrip([chars])rarr string or unicodeReturn a copy of the string S with leading whitespace removed If chars is given and not None removecharacters in chars instead If chars is unicode S will be converted to unicode before stripping

partition(sep) -gt (head sep tail)Search for the separator sep in S and return the part before it the separator itself and the part after it Ifthe separator is not found return S and two empty strings

replace(old new[ count ])rarr stringReturn a copy of string S with all occurrences of substring old replaced by new If the optional argumentcount is given only the first count occurrences are replaced

rfind(sub[ start[ end ]])rarr intReturn the highest index in S where substring sub is found such that sub is contained within S[startend]Optional arguments start and end are interpreted as in slice notation

Return -1 on failure

rindex(sub[ start[ end ]])rarr intLike Srfind() but raise ValueError when the substring is not found

rjust(width[ fillchar ])rarr stringReturn S right-justified in a string of length width Padding is done using the specified fill character (defaultis a space)

rpartition(sep) -gt (head sep tail)Search for the separator sep in S starting at the end of S and return the part before it the separator itselfand the part after it If the separator is not found return two empty strings and S

rsplit([sep[ maxsplit ]])rarr list of stringsReturn a list of the words in the string S using sep as the delimiter string starting at the end of the stringand working to the front If maxsplit is given at most maxsplit splits are done If sep is not specified or isNone any whitespace string is a separator

rstrip([chars])rarr string or unicodeReturn a copy of the string S with trailing whitespace removed If chars is given and not None removecharacters in chars instead If chars is unicode S will be converted to unicode before stripping

split([sep[ maxsplit ]])rarr list of stringsReturn a list of the words in the string S using sep as the delimiter string If maxsplit is given at mostmaxsplit splits are done If sep is not specified or is None any whitespace string is a separator and emptystrings are removed from the result

splitlines(keepends=False)rarr list of stringsReturn a list of the lines in S breaking at line boundaries Line breaks are not included in the resulting listunless keepends is given and true

startswith(prefix[ start[ end ]])rarr boolReturn True if S starts with the specified prefix False otherwise With optional start test S beginning atthat position With optional end stop comparing S at that position prefix can also be a tuple of strings totry

strip([chars])rarr string or unicodeReturn a copy of the string S with leading and trailing whitespace removed If chars is given and not None

351 Utilities and class for UTF8 strings managing 141

web2py Documentation Release 2146-stable

remove characters in chars instead If chars is unicode S will be converted to unicode before stripping

swapcase()rarr stringReturn a copy of the string S with uppercase characters converted to lowercase and vice versa

title()rarr stringReturn a titlecased version of S ie words start with uppercase characters all remaining cased charactershave lowercase

translate(table[ deletechars])rarr stringReturn a copy of the string S where all characters occurring in the optional argument deletechars areremoved and the remaining characters have been mapped through the given translation table which mustbe a string of length 256 or None If the table argument is None no translation is applied and the operationsimply removes the characters in deletechars

upper()rarr stringReturn a copy of the string S converted to uppercase

zfill(width)rarr stringPad a numeric string S with zeros on the left to fill a field of the specified width The string S is nevertruncated

142 Chapter 35 utf8 Module

CHAPTER 36

utils Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

361 This file specifically includes utilities for security

gluonutilsAES_new(key IV=None)Returns an AES cipher object and random IV if None specified

gluonutilscompare(a b)Compares two strings and not vulnerable to timing attacks

gluonutilsfast_urandom16(urandom=[] locker=lt_RLock owner=None count=0gt)This is 4x faster than calling osurandom(16) and prevents the ldquotoo many files openrdquo issue with concurrent accessto osurandom()

gluonutilsget_callable_argspec(fn)

gluonutilsget_digest(value)Returns a hashlib digest algorithm from a string

gluonutilsgetipaddrinfo(host)Filter out non-IP and bad IP addresses from getaddrinfo

gluonutilsinitialize_urandom()This function and the web2py_uuid follow from the following discussionhttpgroupsgooglecomgroupweb2py-developersbrowse_threadthread7fd5789a7da3f09

At startup web2py compute a unique ID that identifies the machine by adding uuidgetnode() + int(timetime() 1e3)

This is a 48-bit number It converts the number into 16 8-bit tokens It uses this value to initialize the entropysource (lsquodevurandomrsquo) and to seed random

143

web2py Documentation Release 2146-stable

If osrandom() is not supported it falls back to using random and issues a warning

gluonutilsis_loopback_ip_address(ip=None addrinfo=None)Determines whether the address appears to be a loopback address This assumes that the IP is valid

gluonutilsis_valid_ip_address(address)

Examples

Better than a thousand words

gtgtgt is_valid_ip_address(1270)Falsegtgtgt is_valid_ip_address(127001)Truegtgtgt is_valid_ip_address(20016601)True

gluonutilsmd5_hash(text)Generates a md5 hash with the given text

gluonutilspad(s n=32 padchar=rsquo rsquo)

gluonutilspbkdf2_hex(data salt iterations=1000 keylen=24 hashfunc=None)

gluonutilssecure_dumps(data encryption_key hash_key=None compression_level=None)

gluonutilssecure_loads(data encryption_key hash_key=None compression_level=None)

gluonutilssimple_hash(text key=rdquo salt=rdquo digest_alg=rsquomd5rsquo)Generates hash with the given text using the specified digest hashing algorithm

gluonutilsweb2py_uuid(ctokens=(12807810588179607998L 787762416516532974))This function follows from the following discussion httpgroupsgooglecomgroupweb2py-developersbrowse_threadthread7fd5789a7da3f09

It works like uuiduuid4 except that tries to use osurandom() if possible and it XORs the output with the tokensuniquely associated with this machine

144 Chapter 36 utils Module

CHAPTER 37

validators Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)Thanks to ga2arch for help with IS_IN_DB and IS_NOT_IN_DB on GAE

371 Validators

class gluonvalidatorsANY_OF(subs)Bases gluonvalidatorsValidator

Tests if any of the validators in a list returns successfully

gtgtgt ANY_OF([IS_EMAIL()IS_ALPHANUMERIC()])(abco)(abco None)gtgtgt ANY_OF([IS_EMAIL()IS_ALPHANUMERIC()])(abco)(abco None)gtgtgt ANY_OF([IS_EMAIL()IS_ALPHANUMERIC()])(abco)(abco enter only letters numbers and underscore)gtgtgt ANY_OF([IS_ALPHANUMERIC()IS_EMAIL()])(abco)(abco enter a valid email address)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

class gluonvalidatorsCLEANUP(regex=None)Bases gluonvalidatorsValidator

Examples

Use as

145

web2py Documentation Release 2146-stable

INPUT(_type=text _name=name requires=CLEANUP())

removes special characters on validation

REGEX_CLEANUP = lt_sreSRE_Pattern objectgt

class gluonvalidatorsCRYPT(key=None digest_alg=rsquopbkdf2(1000 20 sha512)rsquo min_length=0error_message=rsquoToo shortrsquo salt=True max_length=1024)

Bases object

Examples

Use as

INPUT(_type=text _name=name requires=CRYPT())

encodes the value on validation with a digest

If no arguments are provided CRYPT uses the MD5 algorithm If the key argument is provided the HMAC+MD5algorithm is used If the digest_alg is specified this is used to replace the MD5 with for example SHA512 Thedigest_alg can be the name of a hashlib algorithm as a string or the algorithm itself

min_length is the minimal password length (default 4) - IS_STRONG for serious security error_message is themessage if password is too short

Notice that an empty password is accepted but invalid It will not allow login back Stores junk as hashedpassword

Specify an algorithm or by default we will use sha512

Typical available algorithms md5 sha1 sha224 sha256 sha384 sha512

If salt it hashes a password with a salt If salt is True this method will automatically generate one Either caseit returns an encrypted password string in the following format

ltalgorithmgt$ltsaltgt$lthashgt

Important hashed password is returned as a LazyCrypt object and computed only if needed The LasyCryptobject also knows how to compare itself with an existing salted password

Supports standard algorithms

gtgtgt for alg in (md5sha1sha256sha384sha512) print str(CRYPT(digest_alg=algsalt=True)(test)[0])md5$$sha1$$sha256$$sha384$$sha512$$

The syntax is always alg$salt$hash

Supports for pbkdf2

gtgtgt alg = pbkdf2(100020sha512)gtgtgt print str(CRYPT(digest_alg=algsalt=True)(test)[0])pbkdf2(100020sha512)$$

An optional hmac_key can be specified and it is used as salt prefix

146 Chapter 37 validators Module

web2py Documentation Release 2146-stable

gtgtgt a = str(CRYPT(digest_alg=md5key=mykeysalt=True)(test)[0])gtgtgt print amd5$$

Even if the algorithm changes the hash can still be validated

gtgtgt CRYPT(digest_alg=sha1key=mykeysalt=True)(test)[0] == aTrue

If no salt is specified CRYPT can guess the algorithms from length

gtgtgt a = str(CRYPT(digest_alg=sha1salt=False)(test)[0])gtgtgt asha1$$a94a8fe5ccb19ba61c4c0873d391e987982fbbd3gtgtgt CRYPT(digest_alg=sha1salt=False)(test)[0] == aTruegtgtgt CRYPT(digest_alg=sha1salt=False)(test)[0] == a[6]Truegtgtgt CRYPT(digest_alg=md5salt=False)(test)[0] == aTruegtgtgt CRYPT(digest_alg=md5salt=False)(test)[0] == a[6]True

class gluonvalidatorsIS_ALPHANUMERIC(error_message=rsquoEnter only letters numbers andunderscorersquo)

Bases gluonvalidatorsIS_MATCH

Example

Used as

INPUT(_type=text _name=name requires=IS_ALPHANUMERIC())

gtgtgt IS_ALPHANUMERIC()(1)(1 None)gtgtgt IS_ALPHANUMERIC()()( None)gtgtgt IS_ALPHANUMERIC()(A_a)(A_a None)gtgtgt IS_ALPHANUMERIC()()( enter only letters numbers and underscore)

class gluonvalidatorsIS_DATE_IN_RANGE(minimum=None maximum=None format=rsquoY-m-drsquo error_message=None)

Bases gluonvalidatorsIS_DATE

Examples

Use as

gtgtgt v = IS_DATE_IN_RANGE(minimum=datetimedate(200811)rarr˓ maximum=datetimedate(20091231)rarr˓ format=mdYerror_message=Oops)

(continues on next page)

371 Validators 147

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt v(03032008)(datetimedate(2008 3 3) None)

gtgtgt v(03032010)(03032010 oops)

gtgtgt v(datetimedate(200833))(datetimedate(2008 3 3) None)

gtgtgt v(datetimedate(201033))(datetimedate(2010 3 3) oops)

class gluonvalidatorsIS_DATE(format=rsquoY-m-drsquo error_message=rsquoEnter date as (for-mat)srsquo)

Bases gluonvalidatorsValidator

Examples

Use as

INPUT(_type=text _name=name requires=IS_DATE())

date has to be in the ISO8960 format YYYY-MM-DD

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

class gluonvalidatorsIS_DATETIME_IN_RANGE(minimum=None maximum=Noneformat=rsquoY-m-d HMSrsquo er-ror_message=None timezone=None)

Bases gluonvalidatorsIS_DATETIME

Examples

Use as

gtgtgt v = IS_DATETIME_IN_RANGE( minimum=datetimerarr˓datetime(2008111220) maximum=datetimerarr˓datetime(200912311220) format=mdY HMrarr˓error_message=Oops)gtgtgt v(03032008 1240)(datetimedatetime(2008 3 3 12 40) None)

gtgtgt v(03032010 1034)(03032010 1034 oops)

gtgtgt v(datetimedatetime(20083300))(datetimedatetime(2008 3 3 0 0) None)

gtgtgt v(datetimedatetime(20103300))(datetimedatetime(2010 3 3 0 0) oops)

148 Chapter 37 validators Module

web2py Documentation Release 2146-stable

class gluonvalidatorsIS_DATETIME(format=rsquoY-m-d HMSrsquo er-ror_message=rsquoEnter date and time as (format)srsquotimezone=None)

Bases gluonvalidatorsValidator

Examples

Use as

INPUT(_type=text _name=name requires=IS_DATETIME())

datetime has to be in the ISO8960 format YYYY-MM-DD hhmmss timezome must be None or apytztimezone(ldquoAmericaChicagordquo) object

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

isodatetime = Y-m-d HMS

static nice(format)

class gluonvalidatorsIS_DECIMAL_IN_RANGE(minimum=None maximum=None er-ror_message=None dot=rsquorsquo)

Bases gluonvalidatorsValidator

Determines that the argument is (or can be represented as) a Python Decimal and that it falls within the specifiedinclusive range The comparison is made with Python Decimal arithmetic

The minimum and maximum limits can be None meaning no lower or upper limit respectively

Example

Used as

INPUT(_type=text _name=name requires=IS_DECIMAL_IN_RANGE(0 10))

gtgtgt IS_DECIMAL_IN_RANGE(15)(4)(Decimal(4) None)gtgtgt IS_DECIMAL_IN_RANGE(15)(4)(Decimal(4) None)gtgtgt IS_DECIMAL_IN_RANGE(15)(1)(Decimal(1) None)gtgtgt IS_DECIMAL_IN_RANGE(15)(525)(525 enter a number between 1 and 5)gtgtgt IS_DECIMAL_IN_RANGE(5256)(525)(Decimal(525) None)gtgtgt IS_DECIMAL_IN_RANGE(5256)(525)(Decimal(525) None)gtgtgt IS_DECIMAL_IN_RANGE(15)(60)(60 enter a number between 1 and 5)gtgtgt IS_DECIMAL_IN_RANGE(15)(35)(Decimal(35) None)gtgtgt IS_DECIMAL_IN_RANGE(1555)(35)(Decimal(35) None)gtgtgt IS_DECIMAL_IN_RANGE(1555)(65)(65 enter a number between 15 and 55)

(continues on next page)

371 Validators 149

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_DECIMAL_IN_RANGE(15None)(65)(Decimal(65) None)gtgtgt IS_DECIMAL_IN_RANGE(15None)(05)(05 enter a number greater than or equal to 15)gtgtgt IS_DECIMAL_IN_RANGE(None55)(45)(Decimal(45) None)gtgtgt IS_DECIMAL_IN_RANGE(None55)(65)(65 enter a number less than or equal to 55)gtgtgt IS_DECIMAL_IN_RANGE()(65)(Decimal(65) None)gtgtgt IS_DECIMAL_IN_RANGE(099)(123123)(123123 enter a number between 0 and 99)gtgtgt IS_DECIMAL_IN_RANGE(099)(123123)(123123 enter a number between 0 and 99)gtgtgt IS_DECIMAL_IN_RANGE(099)(1234)(Decimal(1234) None)gtgtgt IS_DECIMAL_IN_RANGE()(abc)(abc enter a number)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

class gluonvalidatorsIS_EMAIL(banned=None forced=None error_message=rsquoEnter a validemail addressrsquo)

Bases gluonvalidatorsValidator

Checks if fieldrsquos value is a valid email address Can be set to disallow or force addresses from certain domain(s)

Email regex adapted from httphaackedcomarchive20070821i-knew-how-to-validate-an-email-address-until-iaspx generally following the RFCs except that we disallow quoted strings and permit underscores and leadingnumerics in subdomain labels

Parameters

bull banned ndash regex text for disallowed address domains

bull forced ndash regex text for required address domains

Both arguments can also be custom objects with a match(value) method

Example

Check for valid email address

INPUT(_type=text _name=namerequires=IS_EMAIL())

Check for valid email address that canrsquot be from a com domain

INPUT(_type=text _name=namerequires=IS_EMAIL(banned=^com(|)$))

Check for valid email address that must be from a edu domain

INPUT(_type=text _name=namerequires=IS_EMAIL(forced=^edu(|)$))

(continues on next page)

150 Chapter 37 validators Module

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_EMAIL()(abcom)(abcom None)gtgtgt IS_EMAIL()(abcdefcom)(abcdefcom None)gtgtgt IS_EMAIL()(abc3defcom)(abc3defcom None)gtgtgt IS_EMAIL()(abcdefus)(abcdefus None)gtgtgt IS_EMAIL()(abcd_-fus)(abcd_-fus None)gtgtgt IS_EMAIL()(defcom) missing name(defcom enter a valid email address)gtgtgt IS_EMAIL()(abcdefcom) quoted name(abcdefcom enter a valid email address)gtgtgt IS_EMAIL()(abc+defcom) no (abc+defcom enter a valid email address)gtgtgt IS_EMAIL()(abcdefx) one-char TLD(abcdefx enter a valid email address)gtgtgt IS_EMAIL()(abcdef12) numeric TLD(abcdef12 enter a valid email address)gtgtgt IS_EMAIL()(abcdefcom) double-dot in domain(abcdefcom enter a valid email address)gtgtgt IS_EMAIL()(abcdefcom) dot starts domain(abcdefcom enter a valid email address)gtgtgt IS_EMAIL()(abcdefc_m) underscore in TLD(abcdefc_m enter a valid email address)gtgtgt IS_EMAIL()(NotAnEmail) missing (NotAnEmail enter a valid email address)gtgtgt IS_EMAIL()(abcNotAnEmail) missing TLD(abcNotAnEmail enter a valid email address)gtgtgt IS_EMAIL()(customerdepartmentexamplecom)(customerdepartmentexamplecom None)gtgtgt IS_EMAIL()($A12345examplecom)($A12345examplecom None)gtgtgt IS_EMAIL()(defxyzabcexamplecom)(defxyzabcexamplecom None)gtgtgt IS_EMAIL()(_YosemiteSamexamplecom)(_YosemiteSamexamplecom None)gtgtgt IS_EMAIL()(~examplecom)(~examplecom None)gtgtgt IS_EMAIL()(woolyexamplecom) dot starts name(woolyexamplecom enter a valid email address)gtgtgt IS_EMAIL()(woolyexamplecom) adjacent dots in name(woolyexamplecom enter a valid email address)gtgtgt IS_EMAIL()(pootietangexamplecom) dot ends name(pootietangexamplecom enter a valid email address)gtgtgt IS_EMAIL()(examplecom) name is bare dot(examplecom enter a valid email address)gtgtgt IS_EMAIL()(ImaFoolexamplecom)(ImaFoolexamplecom None)gtgtgt IS_EMAIL()(Ima Foolexamplecom) space in name(Ima Foolexamplecom enter a valid email address)gtgtgt IS_EMAIL()(localguylocalhost) localhost as domain(localguylocalhost None)

regex = lt_sreSRE_Pattern object at 0x2e0e160gt

371 Validators 151

web2py Documentation Release 2146-stable

regex_proposed_but_failed = lt_sreSRE_Pattern object at 0x2e100d0gt

class gluonvalidatorsIS_LIST_OF_EMAILS(error_message=rsquoInvalid emails srsquo)Bases object

Example

Used as

Field(emailsliststringwidget=SQLFORMwidgetstextwidgetrequires=IS_LIST_OF_EMAILS()represent=lambda vr SPAN([A(x_href=mailto+x)

rarr˓for x in (v or [])]))

formatter(value row=None)

split_emails = lt_sreSRE_Pattern objectgt

class gluonvalidatorsIS_EMPTY_OR(other null=None empty_regex=None)Bases gluonvalidatorsValidator

Dummy class for testing IS_EMPTY_OR

gtgtgt IS_EMPTY_OR(IS_EMAIL())(abcdefcom)(abcdefcom None)gtgtgt IS_EMPTY_OR(IS_EMAIL())( )(None None)gtgtgt IS_EMPTY_OR(IS_EMAIL() null=abc)( )(abc None)gtgtgt IS_EMPTY_OR(IS_EMAIL() null=abc empty_regex=def)(def)(abc None)gtgtgt IS_EMPTY_OR(IS_EMAIL())(abc)(abc enter a valid email address)gtgtgt IS_EMPTY_OR(IS_EMAIL())( abc )(abc enter a valid email address)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

set_self_id(id)

class gluonvalidatorsIS_EXPR(expression error_message=rsquoInvalid expressionrsquo environ-ment=None)

Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=namerequires=IS_EXPR(5 lt int(value) lt 10))

The argument of IS_EXPR must be python condition

152 Chapter 37 validators Module

web2py Documentation Release 2146-stable

gtgtgt IS_EXPR(int(value) lt 2)(1)(1 None)

gtgtgt IS_EXPR(int(value) lt 2)(2)(2 invalid expression)

class gluonvalidatorsIS_FLOAT_IN_RANGE(minimum=None maximum=None er-ror_message=None dot=rsquorsquo)

Bases gluonvalidatorsValidator

Determines that the argument is (or can be represented as) a float and that it falls within the specified inclusiverange The comparison is made with native arithmetic

The minimum and maximum limits can be None meaning no lower or upper limit respectively

Example

Used as

INPUT(_type=text _name=name requires=IS_FLOAT_IN_RANGE(0 10))

gtgtgt IS_FLOAT_IN_RANGE(15)(4)(40 None)gtgtgt IS_FLOAT_IN_RANGE(15)(4)(40 None)gtgtgt IS_FLOAT_IN_RANGE(15)(1)(10 None)gtgtgt IS_FLOAT_IN_RANGE(15)(525)(525 enter a number between 1 and 5)gtgtgt IS_FLOAT_IN_RANGE(15)(60)(60 enter a number between 1 and 5)gtgtgt IS_FLOAT_IN_RANGE(15)(35)(35 None)gtgtgt IS_FLOAT_IN_RANGE(1None)(35)(35 None)gtgtgt IS_FLOAT_IN_RANGE(None5)(35)(35 None)gtgtgt IS_FLOAT_IN_RANGE(1None)(05)(05 enter a number greater than or equal to 1)gtgtgt IS_FLOAT_IN_RANGE(None5)(65)(65 enter a number less than or equal to 5)gtgtgt IS_FLOAT_IN_RANGE()(65)(65 None)gtgtgt IS_FLOAT_IN_RANGE()(abc)(abc enter a number)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

class gluonvalidatorsIS_IMAGE(extensions=(rsquobmprsquo rsquogifrsquo rsquojpegrsquo rsquopngrsquo) maxsize=(1000010000) minsize=(0 0) error_message=rsquoInvalid imagersquo)

Bases gluonvalidatorsValidator

Checks if file uploaded through file input was saved in one of selected image formats and has dimensions (widthand height) within given boundaries

371 Validators 153

web2py Documentation Release 2146-stable

Does not check for maximum file size (use IS_LENGTH for that) Returns validation failure if no data wasuploaded

Supported file formats BMP GIF JPEG PNG

Code parts taken from httpmailpythonorgpipermailpython-list2007-June617126html

Parameters

bull extensions ndash iterable containing allowed lowercase image file extensions

bull extension of uploaded file counts as jpeg) ((jpg) ndash

bull maxsize ndash iterable containing maximum width and height of the image

bull minsize ndash iterable containing minimum width and height of the image

Use (-1 -1) as minsize to pass image size check

Examples

Check if uploaded file is in any of supported image formats

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_IMAGE())

Check if uploaded file is either JPEG or PNG

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_IMAGE(extensions=(lsquojpegrsquo lsquopngrsquo)))

Check if uploaded file is PNG with maximum size of 200x200 pixels

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_IMAGE(extensions=(lsquopngrsquo) maxsize=(200200)))

class gluonvalidatorsIS_IN_DB(dbset field label=None error_message=rsquoValue not indatabasersquo orderby=None groupby=None distinct=Nonecache=None multiple=False zero=rdquo sort=False_and=None left=None delimiter=None auto_add=False)

Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=namerequires=IS_IN_DB(db dbmytablemyfield zero=))

used for reference fields rendered as a dropbox

build_set()

maybe_add(table fieldname value)

options(zero=True)

set_self_id(id)

class gluonvalidatorsIS_IN_SET(theset labels=None error_message=rsquoValue not allowedrsquomultiple=False zero=rdquo sort=False)

Bases gluonvalidatorsValidator

154 Chapter 37 validators Module

web2py Documentation Release 2146-stable

Example

Used as

INPUT(_type=text _name=namerequires=IS_IN_SET([max john]zero=))

The argument of IS_IN_SET must be a list or set

gtgtgt IS_IN_SET([max john])(max)(max None)gtgtgt IS_IN_SET([max john])(massimo)(massimo value not allowed)gtgtgt IS_IN_SET([max john] multiple=True)((max john))((max john) None)gtgtgt IS_IN_SET([max john] multiple=True)((bill john))((bill john) value not allowed)gtgtgt IS_IN_SET((id1id2) [first labelsecond label])(id1) Traditionalrarr˓way(id1 None)gtgtgt IS_IN_SET(id1first label id2second label)(id1)(id1 None)gtgtgt import itertoolsgtgtgt IS_IN_SET(itertoolschain([135][246]))(1)(1 None)gtgtgt IS_IN_SET([(id1first label) (id2second label)])(id1) Redundantrarr˓way(id1 None)

options(zero=True)

class gluonvalidatorsIS_INT_IN_RANGE(minimum=None maximum=None er-ror_message=None)

Bases gluonvalidatorsValidator

Determines that the argument is (or can be represented as) an int and that it falls within the specified range Therange is interpreted in the Pythonic way so the test is min lt= value lt max

The minimum and maximum limits can be None meaning no lower or upper limit respectively

Example

Used as

INPUT(_type=text _name=name requires=IS_INT_IN_RANGE(0 10))

gtgtgt IS_INT_IN_RANGE(15)(4)(4 None)gtgtgt IS_INT_IN_RANGE(15)(4)(4 None)gtgtgt IS_INT_IN_RANGE(15)(1)(1 None)gtgtgt IS_INT_IN_RANGE(15)(5)(5 enter an integer between 1 and 4)gtgtgt IS_INT_IN_RANGE(15)(5)(5 enter an integer between 1 and 4)gtgtgt IS_INT_IN_RANGE(15)(35)

(continues on next page)

371 Validators 155

web2py Documentation Release 2146-stable

(continued from previous page)

(35 enter an integer between 1 and 4)gtgtgt IS_INT_IN_RANGE(None5)(4)(4 None)gtgtgt IS_INT_IN_RANGE(None5)(6)(6 enter an integer less than or equal to 4)gtgtgt IS_INT_IN_RANGE(1None)(4)(4 None)gtgtgt IS_INT_IN_RANGE(1None)(0)(0 enter an integer greater than or equal to 1)gtgtgt IS_INT_IN_RANGE()(6)(6 None)gtgtgt IS_INT_IN_RANGE()(abc)(abc enter an integer)

class gluonvalidatorsIS_IPV4(minip=rsquo0000rsquo maxip=rsquo255255255255rsquo invert=Falseis_localhost=None is_private=None is_automatic=Noneerror_message=rsquoEnter valid IPv4 addressrsquo)

Bases gluonvalidatorsValidator

Checks if fieldrsquos value is an IP version 4 address in decimal form Can be set to force addresses from certainrange

IPv4 regex taken from httpregexlibcomREDetailsaspxregexp_id=1411

Parameters

bull minip ndash lowest allowed address accepts

ndash str eg 19216801

ndash list or tuple of octets eg [192 168 0 1]

bull maxip ndash highest allowed address same as above

bull invert ndash True to allow addresses only from outside of given range note that range bound-aries are not matched this way

bull is_localhost ndash localhost address treatment

ndash None (default) indifferent

ndash True (enforce) query address must match localhost address (127001)

ndash False (forbid) query address must not match localhost address

bull is_private ndash same as above except that query address is checked against two addressranges 1721600 - 17231255255 and 19216800 - 192168255255

bull is_automatic ndash same as above except that query address is checked against one addressrange 16925400 - 169254255255

Minip and maxip may also be lists or tuples of addresses in all above forms (str int list tuple) allowing setupof multiple address ranges

minip = (minip1 minip2 minipN)| | || | |

maxip = (maxip1 maxip2 maxipN)

Longer iterable will be truncated to match length of shorter one

156 Chapter 37 validators Module

web2py Documentation Release 2146-stable

Examples

Check for valid IPv4 address

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV4())

Check for valid IPv4 address belonging to specific range

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV4(minip=lsquo10020000rsquomaxip=lsquo100200255255rsquo))

Check for valid IPv4 address belonging to either 10011000 - 100110255255 or 2005000 - 200500255address range

INPUT(_type=rsquotextrsquo _name=rsquonamersquo

requires=IS_IPV4(minip=(lsquo10011000rsquo lsquo2005000rsquo) maxip=(lsquo100110255255rsquolsquo200500255rsquo)))

Check for valid IPv4 address belonging to private address space

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV4(is_private=True))

Check for valid IPv4 address that is not a localhost address

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV4(is_localhost=False))

gtgtgt IS_IPV4()(1234)(1234 None)gtgtgt IS_IPV4()(255255255255)(255255255255 None)gtgtgt IS_IPV4()(1234 )(1234 enter valid IPv4 address)gtgtgt IS_IPV4()(12345)(12345 enter valid IPv4 address)gtgtgt IS_IPV4()(123123)(123123 enter valid IPv4 address)gtgtgt IS_IPV4()(1111234)(1111234 enter valid IPv4 address)gtgtgt IS_IPV4()(0111234)(0111234 enter valid IPv4 address)gtgtgt IS_IPV4()(256234)(256234 enter valid IPv4 address)gtgtgt IS_IPV4()(300234)(300234 enter valid IPv4 address)gtgtgt IS_IPV4(minip=1234 maxip=1234)(1234)(1234 None)gtgtgt IS_IPV4(minip=1235 maxip=1239 error_message=Bad ip)(1rarr˓234)(1234 bad ip)gtgtgt IS_IPV4(maxip=1234 invert=True)(127001)(127001 None)gtgtgt IS_IPV4(maxip=1234 invert=True)(1234)(1234 enter valid IPv4 address)gtgtgt IS_IPV4(is_localhost=True)(127001)(127001 None)gtgtgt IS_IPV4(is_localhost=True)(1234)(1234 enter valid IPv4 address)gtgtgt IS_IPV4(is_localhost=False)(127001)(127001 enter valid IPv4 address)

(continues on next page)

371 Validators 157

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_IPV4(maxip=100000 is_localhost=True)(127001)(127001 enter valid IPv4 address)

automatic = (2851995648L 2852061183L)

localhost = 2130706433

numbers = (16777216 65536 256 1)

private = ((2886729728L 2886795263L) (3232235520L 3232301055L))

regex = lt_sreSRE_Pattern object at 0x2e26320gt

class gluonvalidatorsIS_IPV6(is_private=None is_link_local=None is_reserved=Noneis_multicast=None is_routeable=None is_6to4=Noneis_teredo=None subnets=None error_message=rsquoEnter validIPv6 addressrsquo)

Bases gluonvalidatorsValidator

Checks if fieldrsquos value is an IP version 6 address First attempts to use the ipaddress library and falls back tocontribipaddrpy from Google (httpscodegooglecompipaddr-py)

Parameters

bull is_private ndash None (default) indifferent True (enforce) address must be in fc007range False (forbid) address must NOT be in fc007 range

bull is_link_local ndash Same as above but uses fe8010 range

bull is_reserved ndash Same as above but uses IETF reserved range

bull is_mulicast ndash Same as above but uses ff008 range

bull is_routeable ndash Similar to above but enforces not private link_local reserved or multi-cast

bull is_6to4 ndash Same as above but uses 200216 range

bull is_teredo ndash Same as above but uses 200132 range

bull subnets ndash value must be a member of at least one from list of subnets

Examples

Check for valid IPv6 address

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV6())

Check for valid IPv6 address is a link_local address

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV6(is_link_local=True))

Check for valid IPv6 address that is Internet routeable

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV6(is_routeable=True))

Check for valid IPv6 address in specified subnet

INPUT(_type=rsquotextrsquo _name=rsquonamersquo requires=IS_IPV6(subnets=[lsquo200132rsquo])

158 Chapter 37 validators Module

web2py Documentation Release 2146-stable

gtgtgt IS_IPV6()(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPV6()(19216811)(19216811 enter valid IPv6 address)gtgtgt IS_IPV6(error_message=Bad ip)(19216811)(19216811 bad ip)gtgtgt IS_IPV6(is_link_local=True)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPV6(is_link_local=False)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(is_link_local=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(is_multicast=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(is_multicast=True)(ff00126c8ffafe22b3af)(ff00126c8ffafe22b3af None)gtgtgt IS_IPV6(is_routeable=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af None)gtgtgt IS_IPV6(is_routeable=True)(ff00126c8ffafe22b3af)(ff00126c8ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(subnets=200132)(20018ffafe22b3af)(20018ffafe22b3af None)gtgtgt IS_IPV6(subnets=fb008)(20018ffafe22b3af)(20018ffafe22b3af enter valid IPv6 address)gtgtgt IS_IPV6(subnets=[fc008200132])(20018ffafe22b3af)(20018ffafe22b3af None)gtgtgt IS_IPV6(subnets=invalidsubnet)(20018ffafe22b3af)(20018ffafe22b3af invalid subnet provided)

class gluonvalidatorsIS_IPADDRESS(minip=rsquo0000rsquo maxip=rsquo255255255255rsquo in-vert=False is_localhost=None is_private=Noneis_automatic=None is_ipv4=None is_link_local=Noneis_reserved=None is_multicast=Noneis_routeable=None is_6to4=None is_teredo=Nonesubnets=None is_ipv6=None error_message=rsquoEntervalid IP addressrsquo)

Bases gluonvalidatorsValidator

Checks if fieldrsquos value is an IP Address (v4 or v6) Can be set to force addresses from within a specific rangeChecks are done with the correct IS_IPV4 and IS_IPV6 validators

Uses ipaddress library if found falls back to PEP-3144 ipaddrpy from Google (in contrib)

Parameters

bull minip ndash lowest allowed address accepts str eg 19216801 list or tuple of octets eg[192 168 0 1]

bull maxip ndash highest allowed address same as above

bull invert ndash True to allow addresses only from outside of given range note that range bound-aries are not matched this way

IPv4 specific arguments

bull is_localhost localhost address treatment

ndash None (default) indifferent

ndash True (enforce) query address must match localhost address (127001)

371 Validators 159

web2py Documentation Release 2146-stable

ndash False (forbid) query address must not match localhost address

bull is_private same as above except that query address is checked against two address ranges 1721600 -17231255255 and 19216800 - 192168255255

bull is_automatic same as above except that query address is checked against one address range 16925400- 169254255255

bull is_ipv4 either

ndash None (default) indifferent

ndash True (enforce) must be an IPv4 address

ndash False (forbid) must NOT be an IPv4 address

IPv6 specific arguments

bull is_link_local Same as above but uses fe8010 range

bull is_reserved Same as above but uses IETF reserved range

bull is_mulicast Same as above but uses ff008 range

bull is_routeable Similar to above but enforces not private link_local reserved or multicast

bull is_6to4 Same as above but uses 200216 range

bull is_teredo Same as above but uses 200132 range

bull subnets value must be a member of at least one from list of subnets

bull is_ipv6 either

ndash None (default) indifferent

ndash True (enforce) must be an IPv6 address

ndash False (forbid) must NOT be an IPv6 address

Minip and maxip may also be lists or tuples of addresses in all above forms (str int list tuple) allowing setupof multiple address ranges

minip = (minip1 minip2 minipN)| | || | |

maxip = (maxip1 maxip2 maxipN)

Longer iterable will be truncated to match length of shorter one

gtgtgt IS_IPADDRESS()(19216815)(19216815 None)gtgtgt IS_IPADDRESS(is_ipv6=False)(19216815)(19216815 None)gtgtgt IS_IPADDRESS()(255255255255)(255255255255 None)gtgtgt IS_IPADDRESS()(19216815 )(19216815 enter valid IP address)gtgtgt IS_IPADDRESS()(192168115)(192168115 enter valid IP address)gtgtgt IS_IPADDRESS()(123123)(123123 enter valid IP address)gtgtgt IS_IPADDRESS()(1111234)(1111234 enter valid IP address)gtgtgt IS_IPADDRESS()(0111234)

(continues on next page)

160 Chapter 37 validators Module

web2py Documentation Release 2146-stable

(continued from previous page)

(0111234 enter valid IP address)gtgtgt IS_IPADDRESS()(256234)(256234 enter valid IP address)gtgtgt IS_IPADDRESS()(300234)(300234 enter valid IP address)gtgtgt IS_IPADDRESS(minip=19216810 maxip=1921681255)(1921681100)(1921681100 None)gtgtgt IS_IPADDRESS(minip=1235 maxip=1239 error_message=Bad ip)(123rarr˓4)(1234 bad ip)gtgtgt IS_IPADDRESS(maxip=1234 invert=True)(127001)(127001 None)gtgtgt IS_IPADDRESS(maxip=19216814 invert=True)(19216814)(19216814 enter valid IP address)gtgtgt IS_IPADDRESS(is_localhost=True)(127001)(127001 None)gtgtgt IS_IPADDRESS(is_localhost=True)(192168110)(192168110 enter valid IP address)gtgtgt IS_IPADDRESS(is_localhost=False)(127001)(127001 enter valid IP address)gtgtgt IS_IPADDRESS(maxip=100000 is_localhost=True)(127001)(127001 enter valid IP address)

gtgtgt IS_IPADDRESS()(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPADDRESS(is_ipv4=False)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPADDRESS()(fe80126c8ffafe22b3af )(fe80126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_ipv4=True)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_ipv6=True)(19216811)(19216811 enter valid IP address)gtgtgt IS_IPADDRESS(is_ipv6=True error_message=Bad ip)(19216811)(19216811 bad ip)gtgtgt IS_IPADDRESS(is_link_local=True)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af None)gtgtgt IS_IPADDRESS(is_link_local=False)(fe80126c8ffafe22b3af)(fe80126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_link_local=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_multicast=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(is_multicast=True)(ff00126c8ffafe22b3af)(ff00126c8ffafe22b3af None)gtgtgt IS_IPADDRESS(is_routeable=True)(2001126c8ffafe22b3af)(2001126c8ffafe22b3af None)gtgtgt IS_IPADDRESS(is_routeable=True)(ff00126c8ffafe22b3af)(ff00126c8ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(subnets=200132)(20018ffafe22b3af)(20018ffafe22b3af None)gtgtgt IS_IPADDRESS(subnets=fb008)(20018ffafe22b3af)(20018ffafe22b3af enter valid IP address)gtgtgt IS_IPADDRESS(subnets=[fc008200132])(20018ffafe22b3af)(20018ffafe22b3af None)gtgtgt IS_IPADDRESS(subnets=invalidsubnet)(20018ffafe22b3af)(20018ffafe22b3af invalid subnet provided)

371 Validators 161

web2py Documentation Release 2146-stable

class gluonvalidatorsIS_LENGTH(maxsize=255 minsize=0 error_message=rsquoEnter from(min)g to (max)g charactersrsquo)

Bases gluonvalidatorsValidator

Checks if length of fieldrsquos value fits between given boundaries Works for both text and file inputs

Parameters

bull maxsize ndash maximum allowed length size

bull minsize ndash minimum allowed length size

Examples

Check if text string is shorter than 33 characters

INPUT(_type=text _name=name requires=IS_LENGTH(32))

Check if password string is longer than 5 characters

INPUT(_type=password _name=name requires=IS_LENGTH(minsize=6))

Check if uploaded file has size between 1KB and 1MB

INPUT(_type=file _name=name requires=IS_LENGTH(1048576 1024))

Other examples

gtgtgt IS_LENGTH()()( None)gtgtgt IS_LENGTH()(1234567890)(1234567890 None)gtgtgt IS_LENGTH(maxsize=5 minsize=0)(1234567890) too long(1234567890 enter from 0 to 5 characters)gtgtgt IS_LENGTH(maxsize=50 minsize=20)(1234567890) too short(1234567890 enter from 20 to 50 characters)

class gluonvalidatorsIS_LIST_OF(other=None minimum=0 maximum=100 er-ror_message=None)

Bases gluonvalidatorsValidator

class gluonvalidatorsIS_LOWERBases gluonvalidatorsValidator

Converts to lower case

gtgtgt IS_LOWER()(ABC)(abc None)gtgtgt IS_LOWER()(Ntilde)(xc3xb1 None)

class gluonvalidatorsIS_MATCH(expression error_message=rsquoInvalid expressionrsquo strict=Falsesearch=False extract=False is_unicode=False)

Bases gluonvalidatorsValidator

Example

Used as

162 Chapter 37 validators Module

web2py Documentation Release 2146-stable

INPUT(_type=text _name=name requires=IS_MATCH(+))

The argument of IS_MATCH is a regular expression

gtgtgt IS_MATCH(+)(hello)(hello None)

gtgtgt IS_MATCH(hell)(hello)(hello None)

gtgtgt IS_MATCH(hell strict=False)(hello)(hello None)

gtgtgt IS_MATCH(hello)(shello)(shello invalid expression)

gtgtgt IS_MATCH(hello search=True)(shello)(shello None)

gtgtgt IS_MATCH(hello search=True strict=False)(shellox)(shellox None)

gtgtgt IS_MATCH(hello search=True strict=False)(shellox)(shellox None)

gtgtgt IS_MATCH(+)()( invalid expression)

class gluonvalidatorsIS_EQUAL_TO(expression error_message=rsquoNo matchrsquo)Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=password)INPUT(_type=text _name=password2

requires=IS_EQUAL_TO(requestvarspassword))

The argument of IS_EQUAL_TO is a string

gtgtgt IS_EQUAL_TO(aaa)(aaa)(aaa None)

gtgtgt IS_EQUAL_TO(aaa)(aab)(aab no match)

class gluonvalidatorsIS_NOT_EMPTY(error_message=rsquoEnter a valuersquo empty_regex=None)Bases gluonvalidatorsValidator

Example

Used as

371 Validators 163

web2py Documentation Release 2146-stable

INPUT(_type=text _name=name requires=IS_NOT_EMPTY())

gtgtgt IS_NOT_EMPTY()(1)(1 None)gtgtgt IS_NOT_EMPTY()(0)(0 None)gtgtgt IS_NOT_EMPTY()(x)(x None)gtgtgt IS_NOT_EMPTY()( x )(x None)gtgtgt IS_NOT_EMPTY()(None)(None enter a value)gtgtgt IS_NOT_EMPTY()()( enter a value)gtgtgt IS_NOT_EMPTY()( )( enter a value)gtgtgt IS_NOT_EMPTY()( nt)( enter a value)gtgtgt IS_NOT_EMPTY()([])([] enter a value)gtgtgt IS_NOT_EMPTY(empty_regex=def)(def)( enter a value)gtgtgt IS_NOT_EMPTY(empty_regex=de[fg])(deg)( enter a value)gtgtgt IS_NOT_EMPTY(empty_regex=def)(abc)(abc None)

class gluonvalidatorsIS_NOT_IN_DB(dbset field error_message=rsquoValue already indatabase or emptyrsquo allowed_override=[] ig-nore_common_filters=False)

Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=name requires=IS_NOT_IN_DB(db dbtable))

makes the field unique

set_self_id(id)

gluonvalidatorsIS_NULL_ORalias of gluonvalidatorsIS_EMPTY_OR

class gluonvalidatorsIS_SLUG(maxlen=80 check=False error_message=rsquoMust be slugrsquokeep_underscores=False)

Bases gluonvalidatorsValidator

converts arbitrary text string to a slug

gtgtgt IS_SLUG()(abc123)(abc123 None)gtgtgt IS_SLUG()(ABC123)(abc123 None)gtgtgt IS_SLUG()(abc-123)(abc-123 None)

(continues on next page)

164 Chapter 37 validators Module

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_SLUG()(abc--123)(abc-123 None)gtgtgt IS_SLUG()(abc 123)(abc-123 None)gtgtgt IS_SLUG()(abc _123)(abc-123 None)gtgtgt IS_SLUG()(-abc-)(abc None)gtgtgt IS_SLUG()(--a--b--_ -c--)(a-b-c None)gtgtgt IS_SLUG()(abcampamp123)(abc123 None)gtgtgt IS_SLUG()(abcampamp123ampampdef)(abc123def None)gtgtgt IS_SLUG()(ntilde)(n None)gtgtgt IS_SLUG(maxlen=4)(abc123)(abc1 None)gtgtgt IS_SLUG()(abc_123)(abc-123 None)gtgtgt IS_SLUG(keep_underscores=False)(abc_123)(abc-123 None)gtgtgt IS_SLUG(keep_underscores=True)(abc_123)(abc_123 None)gtgtgt IS_SLUG(check=False)(abc)(abc None)gtgtgt IS_SLUG(check=True)(abc)(abc None)gtgtgt IS_SLUG(check=False)(a bc)(a-bc None)gtgtgt IS_SLUG(check=True)(a bc)(a bc must be slug)

static urlify(value maxlen=80 keep_underscores=False)

class gluonvalidatorsIS_STRONG(min=None max=None upper=None lower=Nonenumber=None entropy=None special=Nonespecials=rsquo~$^amp()_+-=ltgt []|rsquo invalid=rsquorsquo error_message=None es=False)

Bases object

Examples

Use as

INPUT(_type=password _name=passwdrequires=IS_STRONG(min=10 special=2 upper=2))

enforces complexity requirements on a field

gtgtgt IS_STRONG(es=True)(Abcd1234)(Abcd1234Must include at least 1 of the following ~$^amp()_+-=ltgt[]|)gtgtgt IS_STRONG(es=True)(Abcd1234)(Abcd1234 None)

(continues on next page)

371 Validators 165

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_STRONG(es=True entropy=1)(a)(a None)gtgtgt IS_STRONG(es=True entropy=1 min=2)(a)(a Minimum length is 2)gtgtgt IS_STRONG(es=True entropy=100)(abc123)(abc123 Entropy (3235) less than required (100))gtgtgt IS_STRONG(es=True entropy=100)(and)(and Entropy (1457) less than required (100))gtgtgt IS_STRONG(es=True entropy=100)(aaa)(aaa Entropy (1442) less than required (100))gtgtgt IS_STRONG(es=True entropy=100)(a1d)(a1d Entropy (1597) less than required (100))gtgtgt IS_STRONG(es=True entropy=100)(antilded)(axc3xb1d Entropy (1813) less than required (100))

class gluonvalidatorsIS_TIME(error_message=rsquoEnter time as hhmmss (seconds am pm op-tional)rsquo)

Bases gluonvalidatorsValidator

Example

Use as

INPUT(_type=text _name=name requires=IS_TIME())

understands the following formats hhmmss [ampm] hhmm [ampm] hh [ampm]

[ampm] is optional lsquorsquo can be replaced by any other non-space non-digit

gtgtgt IS_TIME()(2130)(datetimetime(21 30) None)gtgtgt IS_TIME()(21-30)(datetimetime(21 30) None)gtgtgt IS_TIME()(2130)(datetimetime(21 30) None)gtgtgt IS_TIME()(213059)(datetimetime(21 30 59) None)gtgtgt IS_TIME()(530)(datetimetime(5 30) None)gtgtgt IS_TIME()(530 am)(datetimetime(5 30) None)gtgtgt IS_TIME()(530 pm)(datetimetime(17 30) None)gtgtgt IS_TIME()(530 whatever)(530 whatever enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()(530 20)(530 20 enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()(2430)(2430 enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()(2160)(2160 enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()(2130)(2130 enter time as hhmmss (seconds am pm optional))gtgtgt IS_TIME()()( enter time as hhmmss (seconds am pm optional))ugrave

166 Chapter 37 validators Module

web2py Documentation Release 2146-stable

class gluonvalidatorsIS_UPLOAD_FILENAME(filename=None extension=None lastdot=Truecase=1 error_message=rsquoEnter valid filenamersquo)

Bases gluonvalidatorsValidator

Checks if name and extension of file uploaded through file input matches given criteria

Does not ensure the file type in any way Returns validation failure if no data was uploaded

Parameters

bull filename ndash filename (before dot) regex

bull extension ndash extension (after dot) regex

bull lastdot ndash which dot should be used as a filename extension separator True means lastdot eg filepng -gt file png False means first dot eg filetargz -gt file targz

bull case ndash 0 - keep the case 1 - transform the string into lowercase (default) 2 - transform thestring into uppercase

If there is no dot present extension checks will be done against empty string and filename checks against wholevalue

Examples

Check if file has a pdf extension (case insensitive)

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_UPLOAD_FILENAME(extension=rsquopdfrsquo))

Check if file has a targz extension and name starting with backup

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_UPLOAD_FILENAME(filename=rsquobackuprsquo exten-sion=rsquotargzrsquo lastdot=False))

Check if file has no extension and name matching README (case sensitive)

INPUT(_type=rsquofilersquo _name=rsquonamersquo requires=IS_UPLOAD_FILENAME(filename=rsquo^README$rsquoextension=rsquo^$rsquo case=0)

class gluonvalidatorsIS_UPPERBases gluonvalidatorsValidator

Converts to upper case

gtgtgt IS_UPPER()(abc)(ABC None)gtgtgt IS_UPPER()(ntilde)(xc3x91 None)

class gluonvalidatorsIS_URL(error_message=rsquoEnter a valid URLrsquo mode=rsquohttprsquo al-lowed_schemes=None prepend_scheme=rsquohttprsquo al-lowed_tlds=None)

Bases gluonvalidatorsValidator

Rejects a URL string if any of the following is true

bull The string is empty or None

bull The string uses characters that are not allowed in a URL

bull The string breaks any of the HTTP syntactic rules

bull The URL scheme specified (if one is specified) is not lsquohttprsquo or lsquohttpsrsquo

371 Validators 167

web2py Documentation Release 2146-stable

bull The top-level domain (if a host name is specified) does not exist

(These rules are based on RFC 2616 httpwwwfaqsorgrfcsrfc2616html)

This function only checks the URLrsquos syntax It does not check that the URL points to a real document forexample or that it otherwise makes sense semantically This function does automatically prepend lsquohttprsquo infront of a URL in the case of an abbreviated URL (eg lsquogooglecarsquo)

If the parameter mode=rsquogenericrsquo is used then this functionrsquos behavior changes It then rejects a URL string ifany of the following is true

bull The string is empty or None

bull The string uses characters that are not allowed in a URL

bull The URL scheme specified (if one is specified) is not valid

(These rules are based on RFC 2396 httpwwwfaqsorgrfcsrfc2396html)

The list of allowed schemes is customizable with the allowed_schemes parameter If you exclude None fromthe list then abbreviated URLs (lacking a scheme such as lsquohttprsquo) will be rejected

The default prepended scheme is customizable with the prepend_scheme parameter If you set prepend_schemeto None then prepending will be disabled URLs that require prepending to parse will still be accepted but thereturn value will not be modified

IS_URL is compatible with the Internationalized Domain Name (IDN) standard specified in RFC 3490 (httptoolsietforghtmlrfc3490) As a result URLs can be regular strings or unicode strings If the URLrsquos domaincomponent (eg googleca) contains non-US-ASCII letters then the domain will be converted into Punycode(defined in RFC 3492 httptoolsietforghtmlrfc3492) IS_URL goes a bit beyond the standards and allowsnon-US-ASCII characters to be present in the path and query components of the URL as well These non-US-ASCII characters will be escaped using the standard lsquo20rsquo type syntax eg the unicode character with hexcode 0x4e86 will become lsquo4e86rsquo

Parameters

bull error_message ndash a string the error message to give the end user if the URL does notvalidate

bull allowed_schemes ndash a list containing strings or None Each element is a scheme theinputed URL is allowed to use

bull prepend_scheme ndash a string this scheme is prepended if itrsquos necessary to make the URLvalid

Code Examples

INPUT(_type=text _name=name requires=IS_URL())gtgtgt IS_URL()(abccom)(httpabccom None)

INPUT(_type=text _name=name requires=IS_URL(mode=generic))gtgtgt IS_URL(mode=generic)(abccom)(abccom None)

INPUT(_type=text _name=namerequires=IS_URL(allowed_schemes=[https] prepend_scheme=https))

gtgtgt IS_URL(allowed_schemes=[https] prepend_scheme=https)(httpsabccom)(httpsabccom None)

INPUT(_type=text _name=namerequires=IS_URL(prepend_scheme=https))

(continues on next page)

168 Chapter 37 validators Module

web2py Documentation Release 2146-stable

(continued from previous page)

gtgtgt IS_URL(prepend_scheme=https)(abccom)(httpsabccom None)

INPUT(_type=text _name=namerequires=IS_URL(mode=generic allowed_schemes=[ftps https]

prepend_scheme=https))gtgtgt IS_URL(mode=generic allowed_schemes=[ftps https] prepend_scheme=rarr˓https)(httpsabccom)(httpsabccom None)gtgtgt IS_URL(mode=generic allowed_schemes=[ftps https None] prepend_rarr˓scheme=https)(abccom)(abccom None)

author Jonathan Benn

class gluonvalidatorsIS_JSON(error_message=rsquoInvalid jsonrsquo native_json=False)Bases gluonvalidatorsValidator

Example

Used as

INPUT(_type=text _name=namerequires=IS_JSON(error_message=This is not a valid json input)

gtgtgt IS_JSON()(a 100)(ua 100 None)

gtgtgt IS_JSON()(spam1234)(spam1234 invalid json)

formatter(value)For some validators returns a formatted version (matching the validator) of value Otherwise just returnsthe value

371 Validators 169

web2py Documentation Release 2146-stable

170 Chapter 37 validators Module

CHAPTER 38

widget Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

381 The widget is called from web2py

class gluonwidgetIOBases object

write(data)

gluonwidgetcheck_existent_app(options appname)

gluonwidgetconsole()Defines the behavior of the console web2py execution

gluonwidgetget_code_for_scheduler(app options)

gluonwidgetget_url(host path=rsquorsquo proto=rsquohttprsquo port=80)

gluonwidgetrun_system_tests(options)Runs unittests for gluontests

gluonwidgetstart(cron=True)Starts server

gluonwidgetstart_browser(url startup=False)

gluonwidgetstart_schedulers(options)

class gluonwidgetweb2pyDialog(root options)Bases object

Main window dialog

171

web2py Documentation Release 2146-stable

checkTaskBar()Checks taskbar status

connect_pages()Connects pages

error(message)Shows error message

quit(justHide=False)Finishes the program execution

server_ready()

start()Starts web2py server

start_schedulers(app)

stop()Stops web2py server

try_start_scheduler(app)

try_stop_scheduler(app)

update(text)Updates app text

update_canvas()Updates canvas

update_schedulers(start=False)

172 Chapter 38 widget Module

CHAPTER 39

xmlrpc Module

This file is part of the web2py Web FrameworkCopyrighted by Massimo Di Pierro ltmdipierrocsdepauledugtLicense LGPLv3 (httpwwwgnuorglicenseslgplhtml)

gluonxmlrpchandler(request response methods)

173

web2py Documentation Release 2146-stable

174 Chapter 39 xmlrpc Module

CHAPTER 40

Indices and tables

bull genindex

bull modindex

bull search

175

web2py Documentation Release 2146-stable

176 Chapter 40 Indices and tables

Python Module Index

ggluonadmin 3gluoncache 7gluoncfs 9gluoncompileapp 11gluoncontenttype 15gluoncustom_import 17gluondal 19gluondebug 21gluondecoder 23gluonfileutils 25gluonglobals 27gluonhighlight 33gluonhtml 35gluonhttp 51gluonlanguages 53gluonmain 57gluonmessageboxhandler 59gluonmyregex 61gluonnewcron 63gluonportalocker 65gluonrecfile 67gluonrestricted 69gluonrewrite 71gluonsanitizer 75gluonscheduler 77gluonserializers 83gluonsettings 85gluonshell 87gluonsql 89gluonsqlhtml 97gluonstorage 107gluonstreamer 111gluontemplate 113gluontools 117gluonutf8 139gluonutils 143gluonvalidators 145gluonwidget 171

gluonxmlrpc 173

177

web2py Documentation Release 2146-stable

178 Python Module Index

Index

AA (class in gluonhtml) 35absolute_path_link() (in module gluonnewcron) 63abspath() (in module gluonfileutils) 25accepts() (gluonhtmlFORM method) 41accepts() (gluonsqlhtmlSQLFORM method) 101accessible_query() (gluontoolsAuth method) 121acf() (gluonrewriteMapUrlOut method) 72acquire() (gluonnewcronToken method) 63action() (gluoncacheCache method) 7add_button() (gluonhtmlFORM method) 41add_class() (in module gluonsqlhtml) 104add_deps() (gluonschedulerJobGraph method) 77add_group() (gluontoolsAuth method) 121add_membership() (gluontoolsAuth method) 121add_path_first() (in module gluonadmin) 3add_permission() (gluontoolsAuth method) 122adj_hibernation() (gluonschedulerScheduler method)

79AES_new() (in module gluonutils) 143allows_jwt() (gluontoolsAuth method) 122amfrpc() (gluontoolsService method) 131amfrpc3() (gluontoolsService method) 131ANY_OF (class in gluonvalidators) 145apath() (in module gluonadmin) 3API_SERVER (gluontoolsRecaptcha attribute) 129API_SSL_SERVER (gluontoolsRecaptcha attribute)

129API_URI (gluontoolsRecaptcha2 attribute) 130app_cleanup() (in module gluonadmin) 3app_compile() (in module gluonadmin) 3app_create() (in module gluonadmin) 4app_install() (in module gluonadmin) 4app_pack() (in module gluonadmin) 4app_pack_compiled() (in module gluonadmin) 4app_uninstall() (in module gluonadmin) 4append() (gluonhtmlDIV method) 37append() (gluontemplateBlockNode method) 113append() (gluontemplateContent method) 114

appfactory() (in module gluonmain) 58apply_filter() (gluonlanguagestranslator method) 53archive() (gluontoolsAuth static method) 122archive() (gluontoolsCrud static method) 130arg0 (gluonrewriteMapUrlIn attribute) 71as_dict() (gluonhtmlFORM method) 41as_dict() (gluonsqlDAL method) 92as_dict() (gluonsqlDALField method) 91as_dict() (gluonsqlDALRow method) 91as_dict() (gluonsqlDALTable method) 92as_dict() (gluonsqlField method) 96as_json() (gluonhtmlFORM method) 41as_json() (gluonsqlDALRow method) 91as_xml() (gluonhtmlFORM method) 41as_xml() (gluonsqlDALRow method) 91as_yaml() (gluonhtmlFORM method) 41assert_status() (gluonhtmlFORM method) 41assert_status() (gluonsqlhtmlSQLFORM method) 101assign_tasks() (gluonschedulerScheduler method) 79ASSIGNJS() (in module gluonhtml) 35async() (gluonschedulerMetaScheduler method) 77Auth (class in gluontools) 121AutocompleteWidget (class in gluonsqlhtml) 97autoDetectXMLEncoding() (in module gluondecoder)

23autokey (gluoncacheCache attribute) 8automatic (gluonvalidatorsIS_IPV4 attribute) 158automenu() (gluontoolsWiki method) 135AUTOTYPES (gluonsqlhtmlSQLFORM attribute) 101

BB (class in gluonhtml) 36basic() (gluontoolsAuth method) 122BEAUTIFY (class in gluonhtml) 36being_a_ticker() (gluonschedulerScheduler method) 79BlockNode (class in gluontemplate) 113BODY (class in gluonhtml) 36body (gluonglobalsRequest attribute) 28BooleanWidget (class in gluonsqlhtml) 97BR (class in gluonhtml) 36

179

web2py Documentation Release 2146-stable

build_acf() (gluonrewriteMapUrlOut method) 72build_environment() (in module gluoncompileapp) 12build_query() (gluonsqlhtmlSQLFORM static method)

101build_set() (gluonvalidatorsIS_IN_DB method) 154bulk_insert() (gluonsqlDALTable method) 92bulk_register() (gluontoolsAuth method) 123BUTTON (class in gluonhtml) 36

CCache (class in gluoncache) 7CacheRepresenter (class in gluonsqlhtml) 97callback() (gluonsqlhtmlAutocompleteWidget method)

97can_edit() (gluontoolsWiki method) 135can_join() (gluonsqlDAL method) 92can_manage() (gluontoolsWiki method) 135can_read() (gluontoolsWiki method) 135can_search() (gluontoolsWiki method) 135can_see_menu() (gluontoolsWiki method) 135capitalize() (gluonutf8Utf8 method) 139cas_login() (gluontoolsAuth method) 123cas_validate() (gluontoolsAuth method) 123cast_keys() (in module gluonserializers) 83CAT (class in gluonhtml) 36CENTER (class in gluonhtml) 36center() (gluonutf8Utf8 method) 139change_password() (gluontoolsAuth method) 123check_credentials() (in module gluonfileutils) 26check_existent_app() (in module gluonwidget) 171check_interaction() (in module gluondebug) 22check_new_version() (in module gluonadmin) 4check_reserved_keyword() (gluonsqlDAL method) 92CheckboxesWidget (class in gluonsqlhtml) 97checkTaskBar() (gluonwidgetweb2pyDialog method)

171cleanpath() (in module gluonfileutils) 25CLEANUP (class in gluonvalidators) 145clear() (gluonglobalsSession method) 30clear_content() (gluontemplateContent method) 114clear_interaction() (gluondebugWebDebugger method)

21clear_session_cookies() (gluonglobalsSession method)

30clone() (gluonsqlDALField method) 91clone() (gluonsqlField method) 96close() (gluonportalockerLockedFile method) 65close() (gluonsqlDAL method) 92cloud() (gluontoolsWiki method) 135CODE (class in gluonhtml) 36COL (class in gluonhtml) 37COLGROUP (class in gluonhtml) 37commit() (gluonsqlDAL method) 92communicate() (in module gluondebug) 22

compare() (in module gluonutils) 143compile2() (in module gluonrestricted) 69compile_application() (in module gluoncompileapp) 12compile_controllers() (in module gluoncompileapp) 12compile_models() (in module gluoncompileapp) 12compile_regex() (in module gluonrewrite) 72compile_views() (in module gluoncompileapp) 12component() (gluontoolsWiki static method) 135compute_uuid() (gluonglobalsRequest method) 28confirm() (gluonhtmlFORM static method) 41confirm_registration() (gluontoolsAuth method) 123connect() (gluonglobalsSession method) 30connect_pages() (gluonwidgetweb2pyDialog method)

172console() (in module gluonwidget) 171Content (class in gluontemplate) 114content_type (gluonsqlhtmlExportClass attribute) 98content_type (gluonsqlhtmlExporterCSV attribute) 98content_type (gluonsqlhtmlExporterCSV_hidden

attribute) 98content_type (gluonsqlhtmlExporterHTML attribute)

98content_type (gluonsqlhtmlExporterJSON attribute) 98content_type (gluonsqlhtmlExporterTSV attribute) 99content_type (gluonsqlhtmlExporterXML attribute) 99contenttype() (in module gluoncontenttype) 15cookies2headers() (gluonhttpHTTP method) 51count() (gluonsqlDALField method) 91count() (gluonsqlField method) 96count() (gluonutf8Utf8 method) 139create() (gluontoolsCrud method) 130create() (gluontoolsWiki method) 135create_missing_app_folders() (in module gluonadmin) 5create_missing_folders() (in module gluonadmin) 5createform() (gluonsqlhtmlSQLFORM method) 102crondance() (in module gluonnewcron) 63cronlauncher (class in gluonnewcron) 63Crud (class in gluontools) 130CRYPT (class in gluonvalidators) 146csv() (gluontoolsService method) 132csv() (in module gluonserializers) 83custom_import_install() (in module

gluoncustom_import) 17custom_importer() (in module gluoncustom_import) 17custom_json() (in module gluonserializers) 83CustomImportException 17

DDAL (class in gluonsql) 89DALField (class in gluonsql) 91DALRow (class in gluonsql) 91DALTable (class in gluonsql) 92DatetimeWidget (class in gluonsqlhtml) 98DateWidget (class in gluonsqlhtml) 98

180 Index

web2py Documentation Release 2146-stable

DecimalWidget (class in gluonsqlhtml) 98decode() (gluonutf8Utf8 method) 139decoder() (in module gluondecoder) 23default_delimiters (gluontemplateTemplateParser

attribute) 115default_messages (gluontoolsAuth attribute) 123default_settings (gluontoolsAuth attribute) 124DEFAULT_WIDTH (gluonsqlhtmlUploadWidget

attribute) 104define_signature() (gluontoolsAuth method) 125define_table() (gluonsqlDAL method) 93define_tables() (gluonschedulerScheduler method) 79define_tables() (gluontoolsAuth method) 125del_group() (gluontoolsAuth method) 125del_membership() (gluontoolsAuth method) 125del_permission() (gluontoolsAuth method) 125delete() (gluontoolsCrud method) 130DELETE_FILE (gluonsqlhtmlUploadWidget attribute)

104dictform() (gluonsqlhtmlSQLFORM static method) 102die() (gluonschedulerMetaScheduler method) 78die() (in module gluonshell) 87disable() (gluonschedulerScheduler method) 79distributed_transaction_begin() (gluonsqlDAL static

method) 93distributed_transaction_commit() (gluonsqlDAL static

method) 93DIV (class in gluonhtml) 37do_continue() (gluondebugWebDebugger method) 21do_exec() (gluondebugWebDebugger method) 21do_next() (gluondebugWebDebugger method) 21do_quit() (gluondebugWebDebugger method) 21do_return() (gluondebugWebDebugger method) 21do_step() (gluondebugWebDebugger method) 21DoubleWidget (class in gluonsqlhtml) 98download() (gluonglobalsResponse method) 28drop() (gluonsqlDALTable method) 92DummyResponse (class in gluontemplate) 114

Eedit() (gluontoolsWiki method) 135editmedia() (gluontoolsWiki method) 135element() (gluonhtmlDIV method) 38elements() (gluonhtmlDIV method) 38elements() (gluonhtmlXML method) 49EM (class in gluonhtml) 40email_registration() (gluontoolsAuth method) 125email_reset_password() (gluontoolsAuth method) 125EMBED (class in gluonhtml) 40embed64() (in module gluonhtml) 50emit() (gluonmessageboxhandlerMessageBoxHandler

method) 59emit() (gluonmessageboxhandlerNotifySendHandler

method) 59

enable_autocomplete_and_history() (in modulegluonshell) 87

enable_record_versioning() (gluontoolsAuth method)125

encode() (gluonutf8Utf8 method) 140endswith() (gluonutf8Utf8 method) 140env() (in module gluonshell) 87error() (gluontoolsService method) 132error() (gluonwidgetweb2pyDialog method) 172everybody (gluontoolsWiki attribute) 135exception() (gluondebugWebDebugger method) 21exec_environment() (in module gluonshell) 87exec_pythonrc() (in module gluonshell) 87execute_from_command_line() (in module gluonshell)

87executesql() (gluonsqlDAL method) 93executor() (in module gluonscheduler) 82exists() (in module gluonrecfile) 67expandtabs() (gluonutf8Utf8 method) 140export() (gluonsqlhtmlExportClass method) 98export() (gluonsqlhtmlExporterCSV method) 98export() (gluonsqlhtmlExporterCSV_hidden method)

98export() (gluonsqlhtmlExporterHTML method) 98export() (gluonsqlhtmlExporterJSON method) 98export() (gluonsqlhtmlExporterTSV method) 99export() (gluonsqlhtmlExporterXML method) 99export_to_csv_file() (gluonsqlDAL method) 93ExportClass (class in gluonsqlhtml) 98ExporterCSV (class in gluonsqlhtml) 98ExporterCSV_hidden (class in gluonsqlhtml) 98ExporterHTML (class in gluonsqlhtml) 98ExporterJSON (class in gluonsqlhtml) 98ExporterTSV (class in gluonsqlhtml) 99ExporterXML (class in gluonsqlhtml) 99extcron (class in gluonnewcron) 63extend() (gluontemplateBlockNode method) 113extend() (gluontemplateContent method) 114extend() (gluontemplateTemplateParser method) 115

Ffactory() (gluonsqlhtmlSQLFORM static method) 102fast_urandom16() (in module gluonutils) 143fetch() (in module gluontools) 137Field (class in gluonsql) 95FIELDKEY_DELETE_RECORD

(gluonsqlhtmlSQLFORM attribute) 101FIELDNAME_REQUEST_DELETE

(gluonsqlhtmlSQLFORM attribute) 101fields (gluonsqlDALTable attribute) 92FIELDSET (class in gluonhtml) 40file_ext (gluonsqlhtmlExportClass attribute) 98file_ext (gluonsqlhtmlExporterCSV attribute) 98

Index 181

web2py Documentation Release 2146-stable

file_ext (gluonsqlhtmlExporterCSV_hidden attribute)98

file_ext (gluonsqlhtmlExporterHTML attribute) 98file_ext (gluonsqlhtmlExporterJSON attribute) 98file_ext (gluonsqlhtmlExporterTSV attribute) 99file_ext (gluonsqlhtmlExporterXML attribute) 99filter_err() (in module gluonrewrite) 72filter_url() (in module gluonrewrite) 72find() (gluonutf8Utf8 method) 140find_exposed_functions() (in module gluoncompileapp)

12findT() (in module gluonlanguages) 55first_paragraph() (gluontoolsWiki method) 135fix_hostname() (gluontoolsWiki method) 135fix_newlines() (in module gluonfileutils) 26fixup_missing_path_info() (in module gluonrewrite) 72flatten() (gluonhtmlDIV method) 39flatten() (gluonhtmlMARKMIN method) 44flatten() (gluonhtmlXML method) 49flush() (gluondebugPipe method) 21force() (gluonlanguagestranslator method) 53forget() (gluonglobalsSession method) 30FORM (class in gluonhtml) 40form_factory() (in module gluonsqlhtml) 104format() (gluonutf8Utf8 method) 140formatter() (gluonsqlDALField method) 91formatter() (gluonsqlField method) 96formatter() (gluonvalidatorsANY_OF method) 145formatter() (gluonvalidatorsIS_DATE method) 148formatter() (gluonvalidatorsIS_DATETIME method)

149formatter() (gluonvalidatorsIS_DECIMAL_IN_RANGE

method) 150formatter() (gluonvalidatorsIS_EMPTY_OR method)

152formatter() (gluonvalidatorsIS_FLOAT_IN_RANGE

method) 153formatter() (gluonvalidatorsIS_JSON method) 169formatter() (gluonvalidatorsIS_LIST_OF_EMAILS

method) 152formstyle_bootstrap() (in module gluonsqlhtml) 105formstyle_bootstrap3_inline_factory() (in module

gluonsqlhtml) 105formstyle_bootstrap3_stacked() (in module

gluonsqlhtml) 105formstyle_divs() (in module gluonsqlhtml) 105formstyle_inline() (in module gluonsqlhtml) 105formstyle_table2cols() (in module gluonsqlhtml) 105formstyle_table3cols() (in module gluonsqlhtml) 105formstyle_ul() (in module gluonsqlhtml) 105formstyles (gluonsqlhtmlSQLFORM attribute) 102FormWidget (class in gluonsqlhtml) 99frameset (gluonhtmlHTML attribute) 43frameset (gluonhtmlXHTML attribute) 49

Ggenerate() (in module gluonrecfile) 67GENERIC_DESCRIPTION

(gluonsqlhtmlUploadWidget attribute)104

geocode() (in module gluontools) 137get() (gluonhtmlDIV method) 39get() (gluonsqlDALRow method) 91get_callable_argspec() (in module gluonutils) 143get_code_for_scheduler() (in module gluonwidget) 171get_digest() (in module gluonutils) 143get_effective_router() (in module gluonrewrite) 72get_format() (gluontoolsCrud method) 130get_instances() (gluonsqlDAL static method) 93get_or_create_key() (gluontoolsAuth static method)

125get_or_create_user() (gluontoolsAuth method) 125get_parsed() (in module gluontemplate) 115get_possible_languages() (gluonlanguagestranslator

method) 54get_possible_languages_info()

(gluonlanguagestranslator method) 54get_query() (gluontoolsCrud method) 130get_renderer() (gluontoolsWiki method) 135get_session() (in module gluonfileutils) 26get_t() (gluonlanguagestranslator method) 54get_url() (in module gluonwidget) 171get_usage() (in module gluonshell) 87get_vars (gluonglobalsRequest attribute) 28get_vars_next() (gluontoolsAuth method) 126get_workers() (gluonschedulerScheduler method) 79getcfs() (in module gluoncfs) 9getfirst() (gluonstorageStorage method) 108getipaddrinfo() (in module gluonutils) 143getlast() (gluonstorageStorage method) 108getlist() (gluonstorageStorage method) 108give_up() (gluonschedulerMetaScheduler method) 78gluonadmin (module) 3gluoncache (module) 7gluoncfs (module) 9gluoncompileapp (module) 11gluoncontenttype (module) 15gluoncustom_import (module) 17gluondal (module) 19gluondebug (module) 21gluondecoder (module) 23gluonfileutils (module) 25gluonglobals (module) 27gluonhighlight (module) 33gluonhtml (module) 35gluonhttp (module) 51gluonlanguages (module) 53gluonmain (module) 57gluonmessageboxhandler (module) 59

182 Index

web2py Documentation Release 2146-stable

gluonmyregex (module) 61gluonnewcron (module) 63gluonportalocker (module) 65gluonrecfile (module) 67gluonrestricted (module) 69gluonrewrite (module) 71gluonsanitizer (module) 75gluonscheduler (module) 77gluonserializers (module) 83gluonsettings (module) 85gluonshell (module) 87gluonsql (module) 89gluonsqlhtml (module) 97gluonstorage (module) 107gluonstreamer (module) 111gluontemplate (module) 113gluontools (module) 117gluonutf8 (module) 139gluonutils (module) 143gluonvalidators (module) 145gluonwidget (module) 171gluonxmlrpc (module) 173grid() (gluonsqlhtmlSQLFORM static method) 102groups() (gluontoolsAuth method) 126

HH1 (class in gluonhtml) 42H2 (class in gluonhtml) 42H3 (class in gluonhtml) 42H4 (class in gluonhtml) 42H5 (class in gluonhtml) 42H6 (class in gluonhtml) 42handler() (in module gluonxmlrpc) 173hardcron (class in gluonnewcron) 64harg0 (gluonrewriteMapUrlIn attribute) 71has_membership() (gluontoolsAuth method) 126has_options() (gluonsqlhtmlOptionsWidget static

method) 100has_permission() (gluontoolsAuth method) 126has_permission() (gluontoolsCrud method) 130has_representer() (gluonsqlDAL method) 94HEAD (class in gluonhtml) 42here() (gluontoolsAuth method) 126hidden_fields() (gluonhtmlFORM method) 41highlight() (in module gluonhighlight) 33HR (class in gluonhtml) 42HTML (class in gluonhtml) 42html5 (gluonhtmlHTML attribute) 43html_render() (gluontoolsWiki method) 135HTTP 51HttpServer (class in gluonmain) 58

II (class in gluonhtml) 43

ics() (in module gluonserializers) 83ID_DELETE_SUFFIX (gluonsqlhtmlUploadWidget at-

tribute) 104id_group() (gluontoolsAuth method) 126ID_LABEL_SUFFIX (gluonsqlhtmlSQLFORM at-

tribute) 101ID_ROW_SUFFIX (gluonsqlhtmlSQLFORM attribute)

101IFRAME (class in gluonhtml) 43IMG (class in gluonhtml) 43impersonate() (gluontoolsAuth method) 126import_from_csv_file() (gluonsqlDAL method) 94import_from_csv_file() (gluonsqlDALTable method)

92import_table_definitions() (gluonsqlDAL method) 94include() (gluontemplateTemplateParser method) 115include_files() (gluonglobalsResponse method) 28include_meta() (gluonglobalsResponse method) 28index() (gluonutf8Utf8 method) 140initialize_urandom() (in module gluonutils) 143INPUT (class in gluonhtml) 43insert() (gluonhtmlDIV method) 40insert() (gluonsqlDALTable method) 92insert() (gluontemplateContent method) 114instances (gluontoolsPluginManager attribute) 137IntegerWidget (class in gluonsqlhtml) 99interaction() (gluondebugWebDebugger method) 22invalid_url() (in module gluonrewrite) 72IO (class in gluonwidget) 171IS_ALPHANUMERIC (class in gluonvalidators) 147IS_DATE (class in gluonvalidators) 148IS_DATE_IN_RANGE (class in gluonvalidators) 147IS_DATETIME (class in gluonvalidators) 148IS_DATETIME_IN_RANGE (class in gluonvalidators)

148IS_DECIMAL_IN_RANGE (class in gluonvalidators)

149IS_EMAIL (class in gluonvalidators) 150IS_EMPTY_OR (class in gluonvalidators) 152IS_EQUAL_TO (class in gluonvalidators) 163is_expired() (gluonglobalsSession method) 30IS_EXPR (class in gluonvalidators) 152IS_FLOAT_IN_RANGE (class in gluonvalidators) 153IS_IMAGE (class in gluonvalidators) 153is_image() (gluonsqlhtmlUploadWidget static method)

104is_impersonating() (gluontoolsAuth method) 126IS_IN_DB (class in gluonvalidators) 154IS_IN_SET (class in gluonvalidators) 154IS_INT_IN_RANGE (class in gluonvalidators) 155IS_IPADDRESS (class in gluonvalidators) 159IS_IPV4 (class in gluonvalidators) 156IS_IPV6 (class in gluonvalidators) 158IS_JSON (class in gluonvalidators) 169

Index 183

web2py Documentation Release 2146-stable

IS_LENGTH (class in gluonvalidators) 161IS_LIST_OF (class in gluonvalidators) 162IS_LIST_OF_EMAILS (class in gluonvalidators) 152is_logged_in() (gluontoolsAuth method) 126is_loopback_ip_address() (in module gluonutils) 144IS_LOWER (class in gluonvalidators) 162IS_MATCH (class in gluonvalidators) 162is_new() (gluonglobalsSession method) 30IS_NOT_EMPTY (class in gluonvalidators) 163IS_NOT_IN_DB (class in gluonvalidators) 164IS_NULL_OR (in module gluonvalidators) 164IS_SLUG (class in gluonvalidators) 164IS_STRONG (class in gluonvalidators) 165IS_TIME (class in gluonvalidators) 166is_tracking_changes() (in module gluoncustom_import)

17IS_UPLOAD_FILENAME (class in gluonvalidators)

166IS_UPPER (class in gluonvalidators) 167IS_URL (class in gluonvalidators) 167is_valid_ip_address() (in module gluonutils) 144isalnum() (gluonutf8Utf8 method) 140isalpha() (gluonutf8Utf8 method) 140isdigit() (gluonutf8Utf8 method) 140islower() (gluonutf8Utf8 method) 140isodatetime (gluonvalidatorsIS_DATETIME attribute)

149isspace() (gluonutf8Utf8 method) 140istitle() (gluonutf8Utf8 method) 140isupper() (gluonutf8Utf8 method) 140

JJobGraph (class in gluonscheduler) 77join() (gluonutf8Utf8 method) 140json() (gluonglobalsResponse method) 28json() (gluontoolsService method) 132json() (in module gluonserializers) 83jsonrpc() (gluontoolsService method) 132jsonrpc2() (gluontoolsService method) 132jsonrpc_errors (gluontoolsService attribute) 133JSONWidget (class in gluonsqlhtml) 99jwt() (gluontoolsAuth method) 126

Kkeys() (gluontoolsPluginManager method) 137kill() (gluonschedulerScheduler method) 79

LLABEL (class in gluonhtml) 44label (gluonsqlhtmlExportClass attribute) 98label (gluonsqlhtmlExporterCSV attribute) 98label (gluonsqlhtmlExporterCSV_hidden attribute) 98label (gluonsqlhtmlExporterHTML attribute) 98label (gluonsqlhtmlExporterJSON attribute) 98

label (gluonsqlhtmlExporterTSV attribute) 99label (gluonsqlhtmlExporterXML attribute) 99launch() (gluonnewcronhardcron method) 64Lazy (gluonsqlDALField attribute) 91Lazy (gluonsqlField attribute) 95lazy_cache() (in module gluoncache) 8lazy_define_table() (gluonsqlDAL method) 94LEGEND (class in gluonhtml) 44LI (class in gluonhtml) 44LINK (class in gluonhtml) 44List (class in gluonstorage) 107listdir() (in module gluonfileutils) 25ListWidget (class in gluonsqlhtml) 99ljust() (gluonutf8Utf8 method) 140load() (gluonrestrictedRestrictedError method) 69load() (gluonrestrictedTicketStorage method) 69LOAD() (in module gluoncompileapp) 11load() (in module gluonrewrite) 72load_routers() (in module gluonrewrite) 73load_storage() (in module gluonstorage) 109LoadFactory (class in gluoncompileapp) 12loads_json() (in module gluonserializers) 83loads_yaml() (in module gluonserializers) 83local_import_aux() (in module gluoncompileapp) 12localhost (gluonvalidatorsIS_IPV4 attribute) 158lock() (in module gluonportalocker) 66LockedFile (class in gluonportalocker) 65log() (gluonrestrictedRestrictedError method) 69log_event() (gluontoolsAuth method) 127log_event() (gluontoolsCrud method) 130log_rewrite() (in module gluonrewrite) 73logger (gluonsqlDAL attribute) 94login() (gluontoolsAuth method) 127login_bare() (gluontoolsAuth method) 127login_user() (gluontoolsAuth method) 127logout() (gluontoolsAuth method) 127logout_bare() (gluontoolsAuth method) 127loop() (gluonschedulerMetaScheduler method) 78loop() (gluonschedulerScheduler method) 79lower() (gluonutf8Utf8 method) 141lstrip() (gluonutf8Utf8 method) 141

MM() (gluonlanguagestranslator method) 53Mail (class in gluontools) 117MailAttachment (class in gluontools) 118main() (in module gluonscheduler) 82make_fake_file_like_object() (in module gluonfileutils)

26manage_tokens() (gluontoolsAuth method) 127map_app() (gluonrewriteMapUrlIn method) 71map_controller() (gluonrewriteMapUrlIn method) 71map_function() (gluonrewriteMapUrlIn method) 71map_language() (gluonrewriteMapUrlIn method) 71

184 Index

web2py Documentation Release 2146-stable

map_prefix() (gluonrewriteMapUrlIn method) 71map_root_static() (gluonrewriteMapUrlIn method) 72map_static() (gluonrewriteMapUrlIn method) 72map_url_in() (in module gluonrewrite) 73map_url_out() (in module gluonrewrite) 73MapUrlIn (class in gluonrewrite) 71MapUrlOut (class in gluonrewrite) 72MARKMIN (class in gluonhtml) 44markmin_base() (gluontoolsWiki method) 135markmin_render() (gluontoolsWiki method) 135maybe_add() (gluonvalidatorsIS_IN_DB method) 154md5_hash() (in module gluonutils) 144media() (gluontoolsWiki method) 135MENU (class in gluonhtml) 44menu() (gluontoolsWiki method) 135message (gluonhttpHTTP attribute) 51MessageBoxHandler (class in

gluonmessageboxhandler) 59Messages (class in gluonstorage) 108META (class in gluonhtml) 45MetaScheduler (class in gluonscheduler) 77Method (gluonsqlDALField attribute) 91Method (gluonsqlField attribute) 95mktree() (in module gluonfileutils) 25model_cmp() (in module gluoncompileapp) 12model_cmp_sep() (in module gluoncompileapp) 12MultipleOptionsWidget (class in gluonsqlhtml) 99mybuiltin (class in gluoncompileapp) 12

Nnavbar() (gluontoolsAuth method) 127nice() (gluonvalidatorsIS_DATETIME static method)

149no_underscore() (gluonhtmlBEAUTIFY static method)

36Node (class in gluontemplate) 114NOESCAPE (class in gluontemplate) 114not_authorized() (gluontoolsAuth method) 127not_authorized() (gluontoolsWiki method) 135NotifySendHandler (class in gluonmessageboxhandler)

59now() (gluonschedulerScheduler method) 79numbers (gluonvalidatorsIS_IPV4 attribute) 158

OOBJECT (class in gluonhtml) 45OL (class in gluonhtml) 44omit_acf() (gluonrewriteMapUrlOut method) 72omit_lang() (gluonrewriteMapUrlOut method) 72on() (gluonsqlDALTable method) 92open() (in module gluonrecfile) 67OPTGROUP (class in gluonhtml) 45OPTION (class in gluonhtml) 45options() (gluonvalidatorsIS_IN_DB method) 154

options() (gluonvalidatorsIS_IN_SET method) 155OptionsWidget (class in gluonsqlhtml) 100output() (gluontemplateBlockNode method) 113output_aux() (in module gluontemplate) 115

PP (class in gluonhtml) 45PACKAGE_PATH_SUFFIX

(gluoncustom_importTrackImporter at-tribute) 17

pad() (in module gluonutils) 144pages() (gluontoolsWiki method) 136params_substitution() (gluonlanguagestranslator

method) 54parse() (gluontemplateTemplateParser method) 115parse_all_vars() (gluonglobalsRequest method) 28parse_as_rest() (gluonsqlDAL method) 94parse_get_vars() (gluonglobalsRequest method) 28parse_path_info() (in module gluonshell) 87parse_post_vars() (gluonglobalsRequest method) 28parse_template() (in module gluontemplate) 115parse_version() (in module gluonfileutils) 25parsecronline() (in module gluonnewcron) 64partition() (gluonutf8Utf8 method) 141PasswordWidget (class in gluonsqlhtml) 100pbkdf2_hex() (in module gluonutils) 144Pipe (class in gluondebug) 21plugin_install() (in module gluonadmin) 5plugin_pack() (in module gluonadmin) 5PluginManager (class in gluontools) 136plural() (gluonlanguagestranslator method) 55pop_arg_if() (gluonrewriteMapUrlIn method) 72pop_task() (gluonschedulerMetaScheduler method) 78pop_task() (gluonschedulerScheduler method) 79post_vars (gluonglobalsRequest attribute) 28PRE (class in gluonhtml) 45prettydate() (in module gluontools) 137preview() (gluontoolsWiki method) 136private (gluonvalidatorsIS_IPV4 attribute) 158process() (gluonhtmlFORM method) 41profile() (gluontoolsAuth method) 127

Qqueue_task() (gluonschedulerScheduler method) 79quit() (gluonwidgetweb2pyDialog method) 172

Rr_multiline (gluontemplateTemplateParser attribute)

115r_tag (gluontemplateTemplateParser attribute) 115RadioWidget (class in gluonsqlhtml) 100random_password() (gluontoolsAuth method) 127rangetolist() (in module gluonnewcron) 64re_block (gluontemplateTemplateParser attribute) 115

Index 185

web2py Documentation Release 2146-stable

re_compile() (in module gluoncompileapp) 12re_pass (gluontemplateTemplateParser attribute) 115re_unblock (gluontemplateTemplateParser attribute)

115read() (gluondebugPipe method) 21read() (gluonportalockerLockedFile method) 66read() (gluontoolsCrud method) 130read() (gluontoolsWiki method) 136read_file() (in module gluonfileutils) 25read_locked() (in module gluonportalocker) 66read_pyc() (in module gluoncompileapp) 12readline() (gluondebugPipe method) 21readline() (gluonportalockerLockedFile method) 66readlines() (gluonportalockerLockedFile method) 66readlines_file() (in module gluonfileutils) 25Recaptcha (class in gluontools) 129Recaptcha2 (class in gluontools) 129recursive_unlink() (in module gluonfileutils) 25redirect() (in module gluonhttp) 51REDIRECT_JS (gluonhtmlFORM attribute) 41regex (gluonvalidatorsIS_EMAIL attribute) 151regex (gluonvalidatorsIS_IPV4 attribute) 158regex_attr (gluonhtmlDIV attribute) 40regex_class (gluonhtmlDIV attribute) 40REGEX_CLEANUP (gluonvalidatorsCLEANUP

attribute) 146regex_filter_in() (in module gluonrewrite) 73regex_filter_out() (in module gluonrewrite) 73regex_id (gluonhtmlDIV attribute) 40regex_proposed_but_failed (gluonvalidatorsIS_EMAIL

attribute) 151regex_select() (in module gluonrewrite) 73regex_tag (gluonhtmlDIV attribute) 40regex_uri() (in module gluonrewrite) 73regex_url_in() (in module gluonrewrite) 73register() (gluontoolsAuth method) 127register_bare() (gluontoolsAuth method) 127reindent() (gluontemplateTemplateParser method) 115release() (gluonnewcronToken method) 63remove() (in module gluonrecfile) 67remove_compiled_application() (in module

gluoncompileapp) 12render() (gluonglobalsResponse method) 28render() (in module gluontemplate) 115render_tags() (gluontoolsWiki method) 136renew() (gluonglobalsSession method) 30replace() (gluonutf8Utf8 method) 141report_task() (gluonschedulerMetaScheduler method)

78report_task() (gluonschedulerScheduler method) 80represent() (gluonsqlDAL method) 94represent() (gluonsqlhtmlUploadWidget class method)

104represent() (in module gluonsqlhtml) 105

represented() (gluonsqlhtmlExportClass method) 98representers (gluonsqlDAL attribute) 94Request (class in gluonglobals) 27request_reset_password() (gluontoolsAuth method) 127requires() (gluontoolsAuth method) 127requires_https() (gluonglobalsRequest method) 28requires_login() (gluontoolsAuth method) 127requires_login_or_token() (gluontoolsAuth method)

127requires_membership() (gluontoolsAuth method) 128requires_permission() (gluontoolsAuth method) 128requires_signature() (gluontoolsAuth method) 128reset_password() (gluontoolsAuth method) 128reset_password_deprecated() (gluontoolsAuth method)

128Response (class in gluonglobals) 28restful() (gluonglobalsRequest method) 28restricted() (in module gluonrestricted) 69RestrictedError 69resume() (gluonschedulerScheduler method) 80retrieve() (gluonsqlDALField method) 91retrieve() (gluonsqlField method) 96retrieve_file_properties() (gluonsqlDALField method)

91retrieve_file_properties() (gluonsqlField method) 96retrieve_password() (gluontoolsAuth method) 128retrieve_username() (gluontoolsAuth method) 128reverse_geocode() (in module gluontools) 137rfind() (gluonutf8Utf8 method) 141rindex() (gluonutf8Utf8 method) 141rjust() (gluonutf8Utf8 method) 141rollback() (gluonsqlDAL method) 94rows() (gluontoolsCrud method) 130rows_page (gluontoolsWiki attribute) 136rpartition() (gluonutf8Utf8 method) 141rsplit() (gluonutf8Utf8 method) 141rss() (gluontoolsService method) 133rss() (in module gluonserializers) 83rstrip() (gluonutf8Utf8 method) 141run() (gluondebugWebDebugger method) 22run() (gluonnewcroncronlauncher method) 63run() (gluonnewcronextcron method) 64run() (gluonnewcronhardcron method) 64run() (gluonnewcronsoftcron method) 64run() (gluonschedulerMetaScheduler method) 78run() (gluontoolsService method) 133run() (in module gluonshell) 88run_controller_in() (in module gluoncompileapp) 13run_login_onaccept() (gluontoolsAuth method) 128run_models_in() (in module gluoncompileapp) 13run_system_tests() (in module gluonwidget) 171run_view_in() (in module gluoncompileapp) 13

186 Index

web2py Documentation Release 2146-stable

Ssafe_encode() (in module gluonserializers) 83safe_float() (in module gluonsqlhtml) 105safe_int() (in module gluonsqlhtml) 105sanitize() (in module gluonsanitizer) 75save_password() (in module gluonmain) 58save_pyc() (in module gluoncompileapp) 13save_session_id_cookie() (gluonglobalsSession

method) 31save_storage() (in module gluonstorage) 109Scheduler (class in gluonscheduler) 78SCRIPT (class in gluonhtml) 45search() (gluontoolsCrud method) 130search() (gluontoolsWiki method) 136search_menu() (gluonsqlhtmlSQLFORM static

method) 102secure() (gluonglobalsSession method) 31secure_dumps() (in module gluonutils) 144secure_loads() (in module gluonutils) 144SELECT (class in gluonhtml) 45select() (gluontoolsCrud method) 131select_host() (gluontoolsAuth method) 128send() (gluontoolsMail method) 119send_heartbeat() (gluonschedulerMetaScheduler

method) 78send_heartbeat() (gluonschedulerScheduler method) 80serialize() (gluonhtmlMENU method) 45serialize_mobile() (gluonhtmlMENU method) 45serializers (gluonsqlDAL attribute) 95serve_amfrpc() (gluontoolsService method) 133serve_csv() (gluontoolsService method) 134serve_json() (gluontoolsService method) 134serve_jsonrpc() (gluontoolsService method) 134serve_jsonrpc2() (gluontoolsService method) 134serve_rss() (gluontoolsService method) 134serve_run() (gluontoolsService method) 134serve_soap() (gluontoolsService method) 134serve_xml() (gluontoolsService method) 134serve_xmlrpc() (gluontoolsService method) 134server_ready() (gluonwidgetweb2pyDialog method)

172Service (class in gluontools) 131ServiceJsonRpcException 131Session (class in gluonglobals) 29set_attributes() (gluonsqlDALField method) 91set_attributes() (gluonsqlField method) 96set_current_languages() (gluonlanguagestranslator

method) 55set_folder() (gluonsqlDAL static method) 95set_requirements() (gluonschedulerScheduler method)

80set_self_id() (gluonvalidatorsIS_EMPTY_OR method)

152set_self_id() (gluonvalidatorsIS_IN_DB method) 154

set_self_id() (gluonvalidatorsIS_NOT_IN_DB method)164

set_trace() (in module gluondebug) 22set_worker_status() (gluonschedulerScheduler method)

80Settings (class in gluonstorage) 108show_if() (in module gluonsqlhtml) 105sibling() (gluonhtmlDIV method) 40siblings() (gluonhtmlDIV method) 40simple_hash() (in module gluonutils) 144sleep() (gluonschedulerMetaScheduler method) 78sleep() (gluonschedulerScheduler method) 80sluggify() (gluonrewriteMapUrlIn method) 72sluggify() (in module gluonrewrite) 73smart_query() (gluonsqlDAL method) 95smartdictform() (gluonsqlhtmlSQLFORM static

method) 102smartgrid() (gluonsqlhtmlSQLFORM static method)

102soap() (gluontoolsService method) 134softcron (class in gluonnewcron) 64SPAN (class in gluonhtml) 46split() (gluonutf8Utf8 method) 141split_emails (gluonvalidatorsIS_LIST_OF_EMAILS at-

tribute) 152splitlines() (gluonutf8Utf8 method) 141SQLFORM (class in gluonsqlhtml) 100sqlsafe (gluonsqlDALField attribute) 91sqlsafe (gluonsqlDALTable attribute) 92sqlsafe (gluonsqlField attribute) 96sqlsafe_alias (gluonsqlDALTable attribute) 92sqlsafe_name (gluonsqlDALField attribute) 91sqlsafe_name (gluonsqlField attribute) 96SQLTABLE (class in gluonsqlhtml) 103start() (gluonmainHttpServer method) 58start() (gluonwidgetweb2pyDialog method) 172start() (in module gluonwidget) 171start_browser() (in module gluonwidget) 171start_heartbeats() (gluonschedulerMetaScheduler

method) 78start_schedulers() (gluonwidgetweb2pyDialog method)

172start_schedulers() (in module gluonwidget) 171startswith() (gluonutf8Utf8 method) 141stop() (gluonmainHttpServer method) 58stop() (gluonwidgetweb2pyDialog method) 172stop_task() (gluonschedulerScheduler method) 80stop_trace() (in module gluondebug) 22stopcron() (in module gluonnewcron) 64Storage (class in gluonstorage) 107StorageList (class in gluonstorage) 109store() (gluonrestrictedTicketStorage method) 69store() (gluonsqlDALField method) 91store() (gluonsqlField method) 96

Index 187

web2py Documentation Release 2146-stable

stream() (gluonglobalsResponse method) 28stream_file_or_304_or_206() (in module

gluonstreamer) 111streamer() (in module gluonstreamer) 111strict (gluonhtmlHTML attribute) 43strict (gluonhtmlXHTML attribute) 49StringWidget (class in gluonsqlhtml) 103strip() (gluonutf8Utf8 method) 141STRONG (class in gluonhtml) 46STYLE (class in gluonhtml) 46style() (gluonsqlhtmlSQLTABLE method) 103SuperNode (class in gluontemplate) 114swapcase() (gluonutf8Utf8 method) 142

TTABLE (class in gluonhtml) 46table_cas() (gluontoolsAuth method) 128table_event() (gluontoolsAuth method) 128table_group() (gluontoolsAuth method) 128table_membership() (gluontoolsAuth method) 128table_permission() (gluontoolsAuth method) 128table_token() (gluontoolsAuth method) 128table_user() (gluontoolsAuth method) 128tables (gluonsqlDAL attribute) 95tables() (gluontoolsCrud method) 131tag (gluonhtmlA attribute) 35tag (gluonhtmlB attribute) 36tag (gluonhtmlBEAUTIFY attribute) 36tag (gluonhtmlBODY attribute) 36tag (gluonhtmlBR attribute) 36tag (gluonhtmlBUTTON attribute) 36tag (gluonhtmlCAT attribute) 36tag (gluonhtmlCENTER attribute) 36tag (gluonhtmlCOL attribute) 37tag (gluonhtmlCOLGROUP attribute) 37tag (gluonhtmlDIV attribute) 40tag (gluonhtmlEM attribute) 40tag (gluonhtmlEMBED attribute) 40tag (gluonhtmlFIELDSET attribute) 40tag (gluonhtmlFORM attribute) 41tag (gluonhtmlH1 attribute) 42tag (gluonhtmlH2 attribute) 42tag (gluonhtmlH3 attribute) 42tag (gluonhtmlH4 attribute) 42tag (gluonhtmlH5 attribute) 42tag (gluonhtmlH6 attribute) 42tag (gluonhtmlHEAD attribute) 42tag (gluonhtmlHR attribute) 42tag (gluonhtmlHTML attribute) 43tag (gluonhtmlI attribute) 43tag (gluonhtmlIFRAME attribute) 43tag (gluonhtmlIMG attribute) 43tag (gluonhtmlINPUT attribute) 44tag (gluonhtmlLABEL attribute) 44

tag (gluonhtmlLEGEND attribute) 44tag (gluonhtmlLI attribute) 44tag (gluonhtmlLINK attribute) 44tag (gluonhtmlMENU attribute) 45tag (gluonhtmlMETA attribute) 45tag (gluonhtmlOBJECT attribute) 45tag (gluonhtmlOL attribute) 44tag (gluonhtmlOPTGROUP attribute) 45tag (gluonhtmlOPTION attribute) 45tag (gluonhtmlP attribute) 45tag (gluonhtmlPRE attribute) 45tag (gluonhtmlSCRIPT attribute) 45tag (gluonhtmlSELECT attribute) 46tag (gluonhtmlSPAN attribute) 46tag (gluonhtmlSTRONG attribute) 46tag (gluonhtmlSTYLE attribute) 46tag (gluonhtmlTABLE attribute) 46tag (gluonhtmlTBODY attribute) 47tag (gluonhtmlTD attribute) 46tag (gluonhtmlTEXTAREA attribute) 46tag (gluonhtmlTFOOT attribute) 47tag (gluonhtmlTH attribute) 47tag (gluonhtmlTHEAD attribute) 47tag (gluonhtmlTITLE attribute) 47tag (gluonhtmlTR attribute) 47tag (gluonhtmlTT attribute) 47tag (gluonhtmlUL attribute) 44tag (gluonhtmlXHTML attribute) 49TAG (in module gluonhtml) 46tar() (in module gluonfileutils) 26tar_compiled() (in module gluonfileutils) 26Task (class in gluonscheduler) 81task_status() (gluonschedulerScheduler method) 81TaskReport (class in gluonscheduler) 82TBODY (class in gluonhtml) 47TD (class in gluonhtml) 46TemplateParser (class in gluontemplate) 114terminate() (gluonschedulerScheduler method) 81terminate_process() (gluonschedulerMetaScheduler

method) 78test() (in module gluoncompileapp) 13test() (in module gluonshell) 88TEXTAREA (class in gluonhtml) 46TextWidget (class in gluonsqlhtml) 103TFOOT (class in gluonhtml) 47TH (class in gluonhtml) 46THEAD (class in gluonhtml) 47THREAD_LOCAL (gluoncustom_importTrackImporter

attribute) 17TicketStorage (class in gluonrestricted) 69TimeWidget (class in gluonsqlhtml) 104TITLE (class in gluonhtml) 47title() (gluonutf8Utf8 method) 142to() (gluonhttpHTTP method) 51

188 Index

web2py Documentation Release 2146-stable

to_string() (gluontemplateTemplateParser method) 115Token (class in gluonnewcron) 63toolbar() (gluonglobalsResponse method) 29total_seconds() (gluonschedulerScheduler static

method) 81TR (class in gluonhtml) 47track_changes() (in module gluoncustom_import) 17TrackImporter (class in gluoncustom_import) 17transitional (gluonhtmlHTML attribute) 43transitional (gluonhtmlXHTML attribute) 49translate() (gluonlanguagestranslator method) 55translate() (gluonutf8Utf8 method) 142translator (class in gluonlanguages) 53truncate() (gluonsqlDALTable method) 92try_redirect_on_error() (in module gluonrewrite) 73try_rewrite_on_error() (in module gluonrewrite) 73try_start_scheduler() (gluonwidgetweb2pyDialog

method) 172try_stop_scheduler() (gluonwidgetweb2pyDialog

method) 172TT (class in gluonhtml) 47TYPE (class in gluonscheduler) 81

UUL (class in gluonhtml) 44unlock() (in module gluonportalocker) 66untar() (in module gluonfileutils) 26unzip() (in module gluonadmin) 5up() (in module gluonfileutils) 25update() (gluonhtmlDIV method) 40update() (gluonsqlDALTable method) 92update() (gluontoolsCrud method) 131update() (gluonwidgetweb2pyDialog method) 172update_all_languages() (in module gluonlanguages) 55update_canvas() (gluonwidgetweb2pyDialog method)

172update_dependencies() (gluonschedulerScheduler

method) 81update_groups() (gluontoolsAuth method) 128update_or_insert() (gluonsqlDALTable method) 92update_request() (gluonrewriteMapUrlIn method) 72update_schedulers() (gluonwidgetweb2pyDialog

method) 172upgrade() (in module gluonadmin) 5UploadWidget (class in gluonsqlhtml) 104upper() (gluonutf8Utf8 method) 142url() (gluontoolsAuth method) 128url() (gluontoolsCrud method) 131URL() (in module gluonhtml) 47url_in() (in module gluonrewrite) 73url_out() (in module gluonrewrite) 73urlify() (gluonvalidatorsIS_SLUG static method) 165user_agent() (gluonglobalsRequest method) 28user_group() (gluontoolsAuth method) 128

user_group_role() (gluontoolsAuth method) 128user_id (gluontoolsAuth attribute) 128Utf8 (class in gluonutf8) 139uuid (gluonglobalsRequest attribute) 28uuid() (gluonsqlDAL method) 95

Vvalidate() (gluonhtmlFORM method) 41validate() (gluonschedulerJobGraph method) 77validate() (gluonsqlDALField method) 91validate() (gluonsqlField method) 96validate_and_insert() (gluonsqlDALTable method) 92validate_and_update() (gluonsqlDALTable method) 92validate_and_update_or_insert() (gluonsqlDALTable

method) 92validate_args() (gluonrewriteMapUrlIn method) 72validators (gluonsqlDAL attribute) 95validators_method() (gluonsqlDAL method) 95vars (gluonglobalsRequest attribute) 28verify_email() (gluontoolsAuth method) 128VERIFY_SERVER (gluontoolsRecaptcha attribute)

129VERIFY_SERVER (gluontoolsRecaptcha2 attribute)

130Virtual (gluonsqlDALField attribute) 91Virtual (gluonsqlField attribute) 96

Ww2p_pack() (in module gluonfileutils) 26w2p_pack_plugin() (in module gluonfileutils) 26w2p_unpack() (in module gluonfileutils) 26w2p_unpack_plugin() (in module gluonfileutils) 26web2py_uuid() (in module gluonutils) 144web2pyDialog (class in gluonwidget) 171WebDebugger (class in gluondebug) 21when_is_logged_in_bypass_next_in_url()

(gluontoolsAuth method) 128where() (gluonsqlDAL method) 95widget() (gluonsqlhtmlBooleanWidget class method)

97widget() (gluonsqlhtmlCheckboxesWidget class

method) 97widget() (gluonsqlhtmlFormWidget class method) 99widget() (gluonsqlhtmlJSONWidget class method) 99widget() (gluonsqlhtmlListWidget class method) 99widget() (gluonsqlhtmlMultipleOptionsWidget class

method) 100widget() (gluonsqlhtmlOptionsWidget class method)

100widget() (gluonsqlhtmlPasswordWidget class method)

100widget() (gluonsqlhtmlRadioWidget class method) 100widget() (gluonsqlhtmlStringWidget class method) 103widget() (gluonsqlhtmlTextWidget class method) 104

Index 189

web2py Documentation Release 2146-stable

widget() (gluonsqlhtmlUploadWidget class method)104

widgets (gluonsqlhtmlSQLFORM attribute) 103Wiki (class in gluontools) 135wiki() (gluontoolsAuth method) 129wikimenu() (gluontoolsAuth method) 129with_alias() (gluonsqlDALTable method) 92with_prefix() (gluoncacheCache static method) 8wrapped_assign_tasks() (gluonschedulerScheduler

method) 81wrapped_pop_task() (gluonschedulerScheduler

method) 81wrapped_report_task() (gluonschedulerScheduler

method) 81write() (gluondebugPipe method) 21write() (gluonglobalsResponse method) 29write() (gluonportalockerLockedFile method) 66write() (gluontemplateDummyResponse method) 114write() (gluonwidgetIO method) 171write_file() (in module gluonfileutils) 25write_locked() (in module gluonportalocker) 66wsgibase() (in module gluonmain) 57

XXHTML (class in gluonhtml) 49XML (class in gluonhtml) 49xml() (gluonhtmlA method) 35xml() (gluonhtmlCODE method) 37xml() (gluonhtmlDIV method) 40xml() (gluonhtmlFORM method) 42xml() (gluonhtmlHTML method) 43xml() (gluonhtmlINPUT method) 44xml() (gluonhtmlMARKMIN method) 44xml() (gluonhtmlMENU method) 45xml() (gluonhtmlP method) 45xml() (gluonhtmlSCRIPT method) 45xml() (gluonhtmlSTYLE method) 46xml() (gluonhtmlXHTML method) 49xml() (gluonhtmlXML method) 50xml() (gluontemplateNOESCAPE method) 114xml() (gluontoolsRecaptcha method) 129xml() (gluontoolsRecaptcha2 method) 130xml() (gluontoolsService method) 134xml() (in module gluonserializers) 83xml_rec() (in module gluonserializers) 83xmlescape() (in module gluonhtml) 50xmlns (gluonhtmlXHTML attribute) 49xmlrpc() (gluonglobalsResponse method) 29xmlrpc() (gluontoolsService method) 134

Yyaml() (in module gluonserializers) 83

Zzfill() (gluonutf8Utf8 method) 142

190 Index

  • admin Module
    • Utility functions for the Admin application
      • cache Module
        • Basic caching classes and methods
          • cfs Module
            • Functions required to execute app components
              • compileapp Module
                • Functions required to execute app components
                  • contenttype Module
                  • custom_import Module
                    • Support for smart import syntax for web2py applications
                      • dal Module
                        • Takes care of adapting pyDAL to web2pyrsquos needs
                          • debug Module
                            • Debugger support classes
                              • decoder Module
                              • fileutils Module
                                • File operations
                                  • globals Module
                                  • highlight Module
                                  • html Module
                                    • Template helpers
                                      • http Module
                                        • HTTP statuses helpers
                                          • languages Module
                                            • Translation system
                                              • main Module
                                                • The gluon wsgi application
                                                  • messageboxhandler Module
                                                  • myregex Module
                                                    • Useful regexes
                                                      • newcron Module
                                                      • portalocker Module
                                                      • recfile Module
                                                        • Generates names for cache and session files
                                                          • restricted Module
                                                            • Restricted environment to execute applicationrsquos code
                                                              • rewrite Module
                                                              • sanitizer Module
                                                                • Cross-site scripting (XSS) defense
                                                                  • scheduler Module
                                                                    • Background processes made simple
                                                                      • serializers Module
                                                                      • settings Module
                                                                      • shell Module
                                                                        • Web2py environment in the shell
                                                                          • sql Module
                                                                            • Just for backward compatibility
                                                                              • sqlhtml Module
                                                                              • storage Module
                                                                              • streamer Module
                                                                                • Facilities to handle file streaming
                                                                                  • template Module
                                                                                    • Templating syntax
                                                                                      • tools Module
                                                                                        • Auth Mail PluginManager and various utilities
                                                                                          • utf8 Module
                                                                                            • Utilities and class for UTF8 strings managing
                                                                                              • utils Module
                                                                                                • This file specifically includes utilities for security
                                                                                                  • validators Module
                                                                                                    • Validators
                                                                                                      • widget Module
                                                                                                        • The widget is called from web2py
                                                                                                          • xmlrpc Module
                                                                                                          • Indices and tables
                                                                                                          • Python Module Index
Page 8: web2py Documentation - Read the Docs
Page 9: web2py Documentation - Read the Docs
Page 10: web2py Documentation - Read the Docs
Page 11: web2py Documentation - Read the Docs
Page 12: web2py Documentation - Read the Docs
Page 13: web2py Documentation - Read the Docs
Page 14: web2py Documentation - Read the Docs
Page 15: web2py Documentation - Read the Docs
Page 16: web2py Documentation - Read the Docs
Page 17: web2py Documentation - Read the Docs
Page 18: web2py Documentation - Read the Docs
Page 19: web2py Documentation - Read the Docs
Page 20: web2py Documentation - Read the Docs
Page 21: web2py Documentation - Read the Docs
Page 22: web2py Documentation - Read the Docs
Page 23: web2py Documentation - Read the Docs
Page 24: web2py Documentation - Read the Docs
Page 25: web2py Documentation - Read the Docs
Page 26: web2py Documentation - Read the Docs
Page 27: web2py Documentation - Read the Docs
Page 28: web2py Documentation - Read the Docs
Page 29: web2py Documentation - Read the Docs
Page 30: web2py Documentation - Read the Docs
Page 31: web2py Documentation - Read the Docs
Page 32: web2py Documentation - Read the Docs
Page 33: web2py Documentation - Read the Docs
Page 34: web2py Documentation - Read the Docs
Page 35: web2py Documentation - Read the Docs
Page 36: web2py Documentation - Read the Docs
Page 37: web2py Documentation - Read the Docs
Page 38: web2py Documentation - Read the Docs
Page 39: web2py Documentation - Read the Docs
Page 40: web2py Documentation - Read the Docs
Page 41: web2py Documentation - Read the Docs
Page 42: web2py Documentation - Read the Docs
Page 43: web2py Documentation - Read the Docs
Page 44: web2py Documentation - Read the Docs
Page 45: web2py Documentation - Read the Docs
Page 46: web2py Documentation - Read the Docs
Page 47: web2py Documentation - Read the Docs
Page 48: web2py Documentation - Read the Docs
Page 49: web2py Documentation - Read the Docs
Page 50: web2py Documentation - Read the Docs
Page 51: web2py Documentation - Read the Docs
Page 52: web2py Documentation - Read the Docs
Page 53: web2py Documentation - Read the Docs
Page 54: web2py Documentation - Read the Docs
Page 55: web2py Documentation - Read the Docs
Page 56: web2py Documentation - Read the Docs
Page 57: web2py Documentation - Read the Docs
Page 58: web2py Documentation - Read the Docs
Page 59: web2py Documentation - Read the Docs
Page 60: web2py Documentation - Read the Docs
Page 61: web2py Documentation - Read the Docs
Page 62: web2py Documentation - Read the Docs
Page 63: web2py Documentation - Read the Docs
Page 64: web2py Documentation - Read the Docs
Page 65: web2py Documentation - Read the Docs
Page 66: web2py Documentation - Read the Docs
Page 67: web2py Documentation - Read the Docs
Page 68: web2py Documentation - Read the Docs
Page 69: web2py Documentation - Read the Docs
Page 70: web2py Documentation - Read the Docs
Page 71: web2py Documentation - Read the Docs
Page 72: web2py Documentation - Read the Docs
Page 73: web2py Documentation - Read the Docs
Page 74: web2py Documentation - Read the Docs
Page 75: web2py Documentation - Read the Docs
Page 76: web2py Documentation - Read the Docs
Page 77: web2py Documentation - Read the Docs
Page 78: web2py Documentation - Read the Docs
Page 79: web2py Documentation - Read the Docs
Page 80: web2py Documentation - Read the Docs
Page 81: web2py Documentation - Read the Docs
Page 82: web2py Documentation - Read the Docs
Page 83: web2py Documentation - Read the Docs
Page 84: web2py Documentation - Read the Docs
Page 85: web2py Documentation - Read the Docs
Page 86: web2py Documentation - Read the Docs
Page 87: web2py Documentation - Read the Docs
Page 88: web2py Documentation - Read the Docs
Page 89: web2py Documentation - Read the Docs
Page 90: web2py Documentation - Read the Docs
Page 91: web2py Documentation - Read the Docs
Page 92: web2py Documentation - Read the Docs
Page 93: web2py Documentation - Read the Docs
Page 94: web2py Documentation - Read the Docs
Page 95: web2py Documentation - Read the Docs
Page 96: web2py Documentation - Read the Docs
Page 97: web2py Documentation - Read the Docs
Page 98: web2py Documentation - Read the Docs
Page 99: web2py Documentation - Read the Docs
Page 100: web2py Documentation - Read the Docs
Page 101: web2py Documentation - Read the Docs
Page 102: web2py Documentation - Read the Docs
Page 103: web2py Documentation - Read the Docs
Page 104: web2py Documentation - Read the Docs
Page 105: web2py Documentation - Read the Docs
Page 106: web2py Documentation - Read the Docs
Page 107: web2py Documentation - Read the Docs
Page 108: web2py Documentation - Read the Docs
Page 109: web2py Documentation - Read the Docs
Page 110: web2py Documentation - Read the Docs
Page 111: web2py Documentation - Read the Docs
Page 112: web2py Documentation - Read the Docs
Page 113: web2py Documentation - Read the Docs
Page 114: web2py Documentation - Read the Docs
Page 115: web2py Documentation - Read the Docs
Page 116: web2py Documentation - Read the Docs
Page 117: web2py Documentation - Read the Docs
Page 118: web2py Documentation - Read the Docs
Page 119: web2py Documentation - Read the Docs
Page 120: web2py Documentation - Read the Docs
Page 121: web2py Documentation - Read the Docs
Page 122: web2py Documentation - Read the Docs
Page 123: web2py Documentation - Read the Docs
Page 124: web2py Documentation - Read the Docs
Page 125: web2py Documentation - Read the Docs
Page 126: web2py Documentation - Read the Docs
Page 127: web2py Documentation - Read the Docs
Page 128: web2py Documentation - Read the Docs
Page 129: web2py Documentation - Read the Docs
Page 130: web2py Documentation - Read the Docs
Page 131: web2py Documentation - Read the Docs
Page 132: web2py Documentation - Read the Docs
Page 133: web2py Documentation - Read the Docs
Page 134: web2py Documentation - Read the Docs
Page 135: web2py Documentation - Read the Docs
Page 136: web2py Documentation - Read the Docs
Page 137: web2py Documentation - Read the Docs
Page 138: web2py Documentation - Read the Docs
Page 139: web2py Documentation - Read the Docs
Page 140: web2py Documentation - Read the Docs
Page 141: web2py Documentation - Read the Docs
Page 142: web2py Documentation - Read the Docs
Page 143: web2py Documentation - Read the Docs
Page 144: web2py Documentation - Read the Docs
Page 145: web2py Documentation - Read the Docs
Page 146: web2py Documentation - Read the Docs
Page 147: web2py Documentation - Read the Docs
Page 148: web2py Documentation - Read the Docs
Page 149: web2py Documentation - Read the Docs
Page 150: web2py Documentation - Read the Docs
Page 151: web2py Documentation - Read the Docs
Page 152: web2py Documentation - Read the Docs
Page 153: web2py Documentation - Read the Docs
Page 154: web2py Documentation - Read the Docs
Page 155: web2py Documentation - Read the Docs
Page 156: web2py Documentation - Read the Docs
Page 157: web2py Documentation - Read the Docs
Page 158: web2py Documentation - Read the Docs
Page 159: web2py Documentation - Read the Docs
Page 160: web2py Documentation - Read the Docs
Page 161: web2py Documentation - Read the Docs
Page 162: web2py Documentation - Read the Docs
Page 163: web2py Documentation - Read the Docs
Page 164: web2py Documentation - Read the Docs
Page 165: web2py Documentation - Read the Docs
Page 166: web2py Documentation - Read the Docs
Page 167: web2py Documentation - Read the Docs
Page 168: web2py Documentation - Read the Docs
Page 169: web2py Documentation - Read the Docs
Page 170: web2py Documentation - Read the Docs
Page 171: web2py Documentation - Read the Docs
Page 172: web2py Documentation - Read the Docs
Page 173: web2py Documentation - Read the Docs
Page 174: web2py Documentation - Read the Docs
Page 175: web2py Documentation - Read the Docs
Page 176: web2py Documentation - Read the Docs
Page 177: web2py Documentation - Read the Docs
Page 178: web2py Documentation - Read the Docs
Page 179: web2py Documentation - Read the Docs
Page 180: web2py Documentation - Read the Docs
Page 181: web2py Documentation - Read the Docs
Page 182: web2py Documentation - Read the Docs
Page 183: web2py Documentation - Read the Docs
Page 184: web2py Documentation - Read the Docs
Page 185: web2py Documentation - Read the Docs
Page 186: web2py Documentation - Read the Docs
Page 187: web2py Documentation - Read the Docs
Page 188: web2py Documentation - Read the Docs
Page 189: web2py Documentation - Read the Docs
Page 190: web2py Documentation - Read the Docs
Page 191: web2py Documentation - Read the Docs
Page 192: web2py Documentation - Read the Docs
Page 193: web2py Documentation - Read the Docs
Page 194: web2py Documentation - Read the Docs
Page 195: web2py Documentation - Read the Docs