Package zms :: Module standard
[frames] | no frames]

Module standard

ZMS standard utility module

This module provides helpful functions and classes for use in Python Scripts. It can be accessed from Python with the statement "import Products.zms.standard"

Classes
  SessionBTreeWrapper
  initutil
Functions
 
initZMS(self, id, titlealt, title, lang, manage_lang, REQUEST)
str
getPRODUCT_HOME()
Returns home-folder of this Product.
str
getPACKAGE_HOME()
Returns path to lib/site-packages.
str
getINSTANCE_HOME()
Returns path to Instance
 
zmi_paths(context)
MyFile
FileFromData(context, data, filename='', content_type=None)
Creates a new instance of a file from given data.
MyImage
ImageFromData(context, data, filename='', content_type=None)
Creates a new instance of an image from given data.
 
set_response_headers(fn, mt='application/octet-stream', size=None, request=None)
Set content-type and -disposition to response-headers.
str
umlaut_quote(s, mapping={})
Replace umlauts in s using given mapping.
str
url_append_params(url, dict, sep='&')
Append params from dict to given url.
str
url_inherit_params(url, REQUEST, exclude=[], sep='&')
Inerits params from request to given url.
str
string_maxlen(s, maxlen=20, etc='...', encoding=None)
Returns string with specified maximum-length.
str
url_encode(url)
All unsafe characters must always be encoded within a URL.
tuple
guess_content_type(filename, data)
Guess the type of a file based on its filename and the data.
 
html_quote(v, name='(Unknown name)', md={})
bytes
bin2hex(m)
Returns a string with the hexadecimal representation of integer m.
bytes
hex2bin(m)
Converts a hexadecimal-string m to an integer.
list
encrypt_schemes()
Available encryption-schemes.
str
encrypt_password(pw, algorithm='md5', hex=False)
Encrypts given password.
str
encrypt_ordtype(s)
Encrypts given string with entities by random algorithm.
int
rand_int(n)
Random integer in given range.
str
getDataSizeStr(len)
Returns display string for file-size (KB).
str
getMimeTypeIconSrc(mt)
Returns the absolute-url of an icon representing the specified MIME-type.
 
unencode(p, enc='utf-8')
Unencodes given parameter.
str
id_prefix(s)
Returns prefix from identifier (which is the non-numeric part at the beginning).
str
id_quote(s, mapping={'\x20': '_','-': '_','/': '_',})
Converts given string to identifier (removes special-characters and replaces German umlauts).
 
form_quote(text, REQUEST)
Remove <form>-tags for Management Interface.
 
qs_append(qs, p, v)
Append to query-string.
any
nvl(a1, a2, n=None)
Returns its first argument if it is not equal to third argument (None), otherwise it returns its second argument.
 
get_session(context)
Get http-session.
 
get_session_value(context, key, defaultValue=None)
Get http-session-value.
 
set_session_value(context, key, value)
Set http-session-value.
 
triggerEvent(context, *args, **kwargs)
Hook for trigger of custom event (if there is one)
Bool
isManagementInterface(REQUEST)
Returns true if current context is management-interface, false else.
Bool
isPreviewRequest(REQUEST)
Returns true if current context is preview-request, false else.
str
unescape(s)
Unescape
str
http_import(context, url, method='GET', auth=None, parse_qs=0, timeout=10, headers={'Accept': '*/*'})
Send Http-Request and return Response-Body.
 
cmp(x, y)
Bool
sendMail(context, mto, msubject, mbody, REQUEST=None, mattach=None)
Sends Mail via MailHost.
 
extutil()
Returns util to handle zms3.extensions
 
getPlugin(context, path, options={})
Executes plugin.
 
getTempFile(context, id)
Get file fromn temp_folder.
    Logging
 
getLog(context)
Get zms_log.
str
writeStdout(context, info)
Write to standard-out (only allowed for development-purposes!).
str
writeLog(context, info)
Log debug-information.
str
writeBlock(context, info)
Log information.
str
writeError(context, info)
Log error.
str
re_sub(pattern, replacement, subject, ignorecase=False)
Performs a search-and-replace across subject, replacing all matches of regex in subject with replacement.
str
re_search(pattern, subject, ignorecase=False)
Scan through string looking for a location where the regular expression pattern produces a match, and return a corresponding MatchObject instance.
str
re_findall(pattern, text, ignorecase=False)
Return all non-overlapping matches of pattern in string, as a list of strings.
 
format_datetime_iso(t)
 
getLangFmtDate(context, t, lang=None, fmt_str='SHORTDATETIME_FMT')
Formats date in locale-format
time.struct_time
getDateTime(t)
Since Python 2.2 the type of objects from the time-module are time.struct_time instead of tuples.
time.struct_time
stripDateTime(t)
Strips time portion from date-time and returns date.
int
daysBetween(t0, t1)
Returns number of days between date t0 and t1.
 
compareDate(t0, t1)
Compares two dates t0 and t1 and returns result.
struct_time
parseLangFmtDate(s)
Parses a string representing a date by trying a variety of different parsers.
type
operator_gettype(v)
Returns python-type of given value.
dict
operator_setitem(a, b, c)
Applies value for key in python-dictionary.
any
operator_getitem(a, b, c=None, ignorecase=True)
Retrieves value for key from python-dictionary.
 
operator_delitem(a, b)
Delete key from python-dictionary.
object
operator_setattr(a, b, c)
Applies value for key to python-object.
any
operator_getattr(a, b, c=None)
Retrieves value for key from python-object.
 
operator_delattr(a, b)
Delete key from python-object.
string or filestream_iterator
localfs_read(filename, mode='b', cache='public, max-age=3600', REQUEST=None)
Reads file from local file-system.
 
localfs_write(filename, v, mode='b')
Writes value to file to local file-system.
 
localfs_remove(path, deep=0)
Removes file from local file-system.
list
localfs_readPath(filename, data=False, recursive=False, REQUEST=None)
Reads path from local file-system.
list
intersection_list(l1, l2)
Intersection of two lists (li & l2).
list
difference_list(l1, l2)
Difference of two lists (l1 - l2).
list
concat_list(l1, l2)
Concatenates two lists (l1 + l2).
dict
dict_list(l)
Converts list to dictionary: key=l[x*2], value=l[x*2+1]
list
distinct_list(l, i=None)
Returns distinct values of given field from list.
list
sort_list(l, qorder=None, qorderdir='asc', ignorecase=1)
Sorts list by given field.
list
string_list(s, sep='\n', trim=True)
Split string by given separator and trim items.
Bool
is_equal(x, y)
Compare the two objects x and y for equality.
str
str_json(i, encoding='ascii', errors='xmlcharrefreplace', formatted=False, level=0, allow_booleans=True, sort_keys=True)
Returns a json-string representation of the object.
str
str_item(i)
Returns a string representation of the item.
list
filter_list(l, i, v, o='%')
Filters list by given field.
list
copy_list(l)
Copies list l.
 
sync_list(l, nl, i)
Synchronizes list l with new list nl using the column i as identifier.
 
aggregate_list(l, i)
Aggregates given field in list.
    XML
str
getXmlHeader(encoding='utf-8')
Returns XML-Header (encoding=utf-8)
string
toXmlString(context, v, xhtml=False, encoding='utf-8')
Serializes value to ZMS XML-Structure.
any
parseXmlString(xml)
Parse value from ZMS XML-Structure.
str
processData(context, processId, data, trans=None)
Process data with custom transformation.
    Executable
Bool
dt_executable(context, v)
Returns if given value is executable.
any
dt_exec(context, v, o={})
Try to execute given value.
any
dt_html(context, value, REQUEST)
Execute given DTML-snippet.
any
dt_py(context, script, kw={})
Execute given Python-script.
any
dt_tal(context, text, options={})
Execute given TAL-snippet.
Variables
  security = ModuleSecurityInfo('Products.zms.standard')
Function Details

FileFromData(context, data, filename='', content_type=None)

 

Creates a new instance of a file from given data.

Parameters:
  • data (string) - File-data (binary)
  • filename (string) - Filename
Returns: MyFile
New instance of file.

ImageFromData(context, data, filename='', content_type=None)

 

Creates a new instance of an image from given data.

Parameters:
  • data (string) - Image-data (binary)
  • filename (string) - Filename
Returns: MyImage
New instance of image.

umlaut_quote(s, mapping={})

 

Replace umlauts in s using given mapping.

Parameters:
  • s (str) - String
  • mapping (dict) - Mapping
Returns: str
Quoted string

url_append_params(url, dict, sep='&amp;')

 

Append params from dict to given url.

Parameters:
  • url (str) - Url
  • dict (dict) - dictionary of params (key/value pairs)
Returns: str
New url

url_inherit_params(url, REQUEST, exclude=[], sep='&amp;')

 

Inerits params from request to given url.

Parameters:
  • url (str) - Url
  • REQUEST (ZPublisher.HTTPRequest) - the triggering request
Returns: str
New url

string_maxlen(s, maxlen=20, etc='...', encoding=None)

 

Returns string with specified maximum-length. If original string exceeds maximum-length '...' is appended at the end.

Parameters:
  • s (str) - String
  • maxlen (int) - Maximum-length
  • etc (str) - Characters to be appended if maximum-length is exceeded
  • encoding (str) - Encoding
Returns: str

url_encode(url)

 

All unsafe characters must always be encoded within a URL.

Parameters:
  • url - Url
  • s (str)
Returns: str
Encoded string

See Also: http://www.ietf.org/rfc/rfc1738.txt

guess_content_type(filename, data)

 

Guess the type of a file based on its filename and the data.

Parameters:
  • filename (str) - Filename
  • data (str) - Data
Returns: tuple
Tuple of MIME-type and encoding.

bin2hex(m)

 

Returns a string with the hexadecimal representation of integer m.

Parameters:
  • m (int) - Binary
Returns: bytes
String

hex2bin(m)

 

Converts a hexadecimal-string m to an integer.

Parameters:
  • m (bytes) - Hexadecimal.
Returns: bytes
Integer

encrypt_schemes()

 

Available encryption-schemes.

Returns: list
list of encryption-scheme ids

encrypt_password(pw, algorithm='md5', hex=False)

 

Encrypts given password.

Parameters:
  • pw (str) - Password
  • algorithm (str) - Encryption-algorithm (md5, sha-1, etc.)
  • hex (bool) - Hexlify
Returns: str
Encrypted password

encrypt_ordtype(s)

 

Encrypts given string with entities by random algorithm.

Parameters:
  • s (str) - String
Returns: str
Encrypted string

rand_int(n)

 

Random integer in given range.

Parameters:
  • n (int) - Range
Returns: int
Random integer

getDataSizeStr(len)

 

Returns display string for file-size (KB).

Parameters:
  • len (int) - length (bytes)
Returns: str

getMimeTypeIconSrc(mt)

 

Returns the absolute-url of an icon representing the specified MIME-type.

Parameters:
  • mt (str) - MIME-Type (e.g. image/gif, text/xml).
Returns: str

id_prefix(s)

 

Returns prefix from identifier (which is the non-numeric part at the beginning).

Parameters:
  • s (str) - Identifier
Returns: str
Id-prefix

id_quote(s, mapping={'\x20': '_','-': '_','/': '_',})

 

Converts given string to identifier (removes special-characters and replaces German umlauts).

Parameters:
  • s (str) - String
Returns: str
Identifier

nvl(a1, a2, n=None)

 

Returns its first argument if it is not equal to third argument (None), otherwise it returns its second argument.

Parameters:
  • a1 (any) - 1st argument
  • a2 (any) - 2nd argument
Returns: any

http_import(context, url, method='GET', auth=None, parse_qs=0, timeout=10, headers={'Accept': '*/*'})

 

Send Http-Request and return Response-Body.

Parameters:
  • url (str) - Remote-URL
  • method (str, values are GET or POST) - Method
  • auth (str) - Authentication
  • parse_qs (int, values are 0 or 1) - Parse Query-String
  • timeout (int, values in seconds) - Time-Out [s]
  • headers (dict) - Request-Headers
Returns: str
Response-Body

writeStdout(context, info)

 

Write to standard-out (only allowed for development-purposes!).

Parameters:
  • info (any) - Object
Returns: str

writeLog(context, info)

 

Log debug-information.

Parameters:
  • info (any) - Debug-information
Returns: str

writeBlock(context, info)

 

Log information.

Parameters:
  • info (any) - Information
Returns: str

writeError(context, info)

 

Log error.

Parameters:
  • info (any) - Information
Returns: str

re_sub(pattern, replacement, subject, ignorecase=False)

 

Performs a search-and-replace across subject, replacing all matches of regex in subject with replacement. The result is returned by the sub() function. The subject string you pass is not modified. convenience-function since re cannot be imported in restricted python

Parameters:
  • pattern (str) - the regular expression to which this string is to be matched
  • replacement (str) - the string to be substituted for each match
  • replacement (str) - ignore case considerations
Returns: str
the resulting string.

re_search(pattern, subject, ignorecase=False)

 

Scan through string looking for a location where the regular expression pattern produces a match, and return a corresponding MatchObject instance. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string. convenience-function since re cannot be imported in restricted python

Parameters:
  • pattern (str) - the regular expression to which this string is to be matched
Returns: str

re_findall(pattern, text, ignorecase=False)

 

Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match convenience-function since re cannot be imported in restricted python

Parameters:
  • pattern (str) - the regular expression to which this string is to be matched
Returns: str

getLangFmtDate(context, t, lang=None, fmt_str='SHORTDATETIME_FMT')

 

Formats date in locale-format

Parameters:
  • t (struct_time) - Datetime
  • lang (str) - Locale
  • fmt_str - Format-String, possible values SHORTDATETIME_FMT (default), SHORTDATE_FMT, DATETIME_FMT, DATE_FMT, DateTime, Day, Month, ISO8601, RFC2822

getDateTime(t)

 

Since Python 2.2 the type of objects from the time-module are time.struct_time instead of tuples. struct_time is compatible with tuple. This is no problem for Zope since Zope uses its own, more flexible, type DateTime. Nevertheless ZMS relies on the datatype "tuple" as DateTime has the limitation that no date prior to 1970-01-01 can be used!

Parameters:
  • t (DateTime.DateTime|tuple|time.struct_time) - the date-time
Returns: time.struct_time
the pythonic-time

stripDateTime(t)

 

Strips time portion from date-time and returns date.

Parameters:
  • t (DateTime.DateTime|tuple|time.struct_time) - the date-time
Returns: time.struct_time
the pythonic-time

daysBetween(t0, t1)

 

Returns number of days between date t0 and t1.

Parameters:
  • t0 (DateTime.DateTime|tuple|time.struct_time) - the start date-time
  • t1 (DateTime.DateTime|tuple|time.struct_time) - the end date-time
Returns: int
the number of days between date t0 and t1.

compareDate(t0, t1)

 

Compares two dates t0 and t1 and returns result.
 +1: t0 &lt; t1
  0: t0 == t1
 -1: t0 &gt; t1
@returns: A negative number if date t0 is before t1, zero if they are equal, or positive if t0 is after t1.
@rtype: C{int}

parseLangFmtDate(s)

 

Parses a string representing a date by trying a variety of different parsers. The parse will try each parse pattern in turn. A parse is only deemed successful if it parses the whole of the input string. If no parse patterns match, None is returned.

Parameters:
  • s (s) - the date to parse
Returns: struct_time
the parsed date.

operator_gettype(v)

 

Returns python-type of given value.

Parameters:
  • v (any) - Value
Returns: type
the type of the value

operator_setitem(a, b, c)

 

Applies value for key in python-dictionary. This is a convenience-function since it is not possible to use expressions like a[b]=c in DTML.

Parameters:
  • a (dict) - Dictionary
  • b (any) - Key
  • c (any) - Value
Returns: dict

operator_getitem(a, b, c=None, ignorecase=True)

 

Retrieves value for key from python-dictionary.

Parameters:
  • a (dict) - Dictionary
  • b (any) - Key
  • c (any) - Default-Value
Returns: any

operator_delitem(a, b)

 

Delete key from python-dictionary.

Parameters:
  • a (dict) - Dictionary
  • b (any) - Key

operator_setattr(a, b, c)

 

Applies value for key to python-object. This is a convenience-function since the use expressions like setattr(a,b,c) is restricted in DTML.

Parameters:
  • a (any) - Object
  • b (string) - Key
  • c (any) - Value
Returns: object

operator_getattr(a, b, c=None)

 

Retrieves value for key from python-object. This is a convenience-function since the use expressions like getattr(a,b,c) is restricted in DTML.

Parameters:
  • a (any) - Object
  • b (any) - Key
  • c (any) - Default-Value
Returns: any

operator_delattr(a, b)

 

Delete key from python-object.

Parameters:
  • a (any) - Object
  • b (any) - Key

localfs_read(filename, mode='b', cache='public, max-age=3600', REQUEST=None)

 

Reads file from local file-system. You must grant permissions for reading from local file-system to directories in Config-Tab / Miscelleaneous-Section.

Parameters:
  • filename (string) - Filepath
  • filename (string) - Access mode
  • REQUEST (ZPublisher.HTTPRequest) - the triggering request
Returns: string or filestream_iterator
Contents of file

localfs_write(filename, v, mode='b')

 

Writes value to file to local file-system.

Parameters:
  • filename (str) - the filename.
  • mode (str) - the mode (b=binary).

intersection_list(l1, l2)

 

Intersection of two lists (li & l2).

Parameters:
  • l1 (list) - List #1
  • l2 (list) - List #2
Returns: list
Intersection list

difference_list(l1, l2)

 

Difference of two lists (l1 - l2).

Parameters:
  • l1 (list) - List #1
  • l2 (list) - List #2
Returns: list
Difference list

concat_list(l1, l2)

 

Concatenates two lists (l1 + l2).

Parameters:
  • l1 (list) - List #1
  • l2 (list) - List #2
Returns: list
Concatinated list

dict_list(l)

 

Converts list to dictionary: key=l[x*2], value=l[x*2+1]

Parameters:
  • l (list) - List
Returns: dict
Dictionary

distinct_list(l, i=None)

 

Returns distinct values of given field from list.

Parameters:
  • l (list) - List
Returns: list

sort_list(l, qorder=None, qorderdir='asc', ignorecase=1)

 

Sorts list by given field.

Returns: list
Sorted list.

filter_list(l, i, v, o='%')

 

Filters list by given field.

Parameters:
  • l (list) - List
  • i (str or int) - Field-name or -index
  • v (any) - Field-value
  • v (any) - Match-operator
Returns: list
Filtered list.

copy_list(l)

 

Copies list l.

Parameters:
  • l (list) - List
Returns: list
Copy of list.

getXmlHeader(encoding='utf-8')

 

Returns XML-Header (encoding=utf-8)

Parameters:
  • encoding (str) - Encoding
Returns: str

toXmlString(context, v, xhtml=False, encoding='utf-8')

 

Serializes value to ZMS XML-Structure. @param context @type context @param v @type v @param xhtml @type xhtml @param encoding @type encoding

Returns: string

parseXmlString(xml)

 

Parse value from ZMS XML-Structure. @param xml

Parameters:
  • xml (str or BytesIO)
Returns: any
list or dict

processData(context, processId, data, trans=None)

 

Process data with custom transformation. @param context

Parameters:
  • processId (str) - the process-id
  • data (str or BytesIO) - the xml-data
  • trans (str) - the transformation
  • context (ZMSObject)
Returns: str
the transformed data

dt_executable(context, v)

 

Returns if given value is executable.

Parameters:
  • context (ZMSObject) - the context
  • v (str) - the executable code
Returns: Bool

dt_exec(context, v, o={})

 

Try to execute given value.

Parameters:
  • context (ZMSObject) - the context
  • v (str) - the executable code
  • o (dict) - the options
Returns: any

dt_html(context, value, REQUEST)

 

Execute given DTML-snippet.

Parameters:
  • context (ZMSObject) - the context
  • value (string) - DTML-snippet
  • REQUEST (ZPublisher.HTTPRequest) - the triggering request
Returns: any
Result of the execution or None

dt_py(context, script, kw={})

 

Execute given Python-script.

Parameters:
  • context (ZMSObject) - the context
  • script (string) - the Python-script
  • kw (dict) - additional options
Returns: any
Result of the execution or None

dt_tal(context, text, options={})

 

Execute given TAL-snippet.

Parameters:
  • context (ZMSObject) - the context
  • value (string) - TAL-snippet
Returns: any
Result of the execution or None

sendMail(context, mto, msubject, mbody, REQUEST=None, mattach=None)

 

Sends Mail via MailHost.

Parameters:
  • context (ZMSObject) - the context
  • mto (str or dict) - the recipient(s)
  • msubject - the subject
  • mbody (str or dict) - the body
Returns: Bool

getPlugin(context, path, options={})

 

Executes plugin.

Parameters:
  • context (ZMSObject) - the context
  • path (string) - the plugin path in $ZMS_HOME/plugins/
  • options (dict) - the options