Welcome to dk’s documentation!

Installation:

pip install dk

Contents:

Project information

The project home page is at:

The github directory is at:

Report any issues at:

dk

dk package

Subpackages

dk.collections package
Submodules
dk.collections.OrderedSet module

Ordered Set. Items can only be added once, further additions have no effect. The iterator iterates over the items in insertion order.

class dk.collections.OrderedSet.oset(iterable=())[source]

Bases: set

Ordered Set. Items can only be added once, further additions have no effect. The iterator iterates over the items in insertion order.

add(item)[source]
dk.collections.invdict module

Inversable dictionary.

class dk.collections.invdict.invdict[source]

Bases: dict

Inversable dict:

>>> -invdict({'key': 'val'}) == {'val': 'key'}
dk.collections.mmap module
class dk.collections.mmap.mmap(**attrs)[source]

Bases: list

Multi Map class, ie. a key/value collection where each key can occur multiple times. Implemented as a list of key/value tuples.

add(key, val)[source]
append(kv)[source]
dk.collections.pset module

Mapping classes.

class dk.collections.pset.defset(defval)[source]

Bases: dk.collections.pset.pset

pset with default value.

class dk.collections.pset.keyval(key, val)

Bases: tuple

key

Alias for field number 0

val

Alias for field number 1

class dk.collections.pset.pset(items=(), **attrs)[source]

Bases: dict

This code is placed in the Public Domain, or released under the wtfpl (http://sam.zoy.org/wtfpl/COPYING) wherever PD is problematic.

Property Set class. A property set is an object where values are attached to attributes, but can still be iterated over as key/value pairs. The order of assignment is maintained during iteration. Only one value allowed per key.

>>> x = pset()
>>> x.a = 42
>>> x.b = 'foo'
>>> x.a = 314
>>> x
pset(a=314, b='foo')
apply(fn)[source]

Apply function fn to all values in self.

items()[source]
keys()[source]
pprint(indent=0, tab=' ', seen=None)[source]

Pretty print the pset, indented.

remove(key)[source]

Remove key from client vars.

values()[source]
class dk.collections.pset.record(items=(), **attrs)[source]

Bases: dk.collections.pset.pset

A property set with commit, rollback, and encoding translation.

changed()[source]

Return list of fields that have changed since last commit.

commit()[source]

Copy current state to self._history

decode(encoding)[source]

Decode using encoding.

encode(encoding)[source]

Encode using encoding.

fields

Verbose name of all fields.

rollback()[source]

Copy snapshot from self._history into self.

strvals(empty='', none='NULL', encoding='u8')[source]

Return a list of all values, formatted for human consumption.

trans(source='iso-8859-1', dest='utf-8')[source]

Translate encoding.

dk.collections.pset.test_pset()[source]

Unit tests...

>>> request = pset(REQUEST={}, META={}, path='/', user=None, session={}, method='GET',
...                COOKIES={}, LANGUAGE_CODE='no')
>>> p = page(request)
>>> p.forms = 'fruit'
>>> p.forms.foo = 'bar'
>>> print p.forms.foo
bar
>>> p.forms.fob = 'baz'
>>> print p.forms.fob
baz
>>> x = pset()
>>> x.a
Traceback (most recent call last):
  ...
AttributeError: a
>>> y = pset(a=1, b=2, c=3)
>>> y.a
1
>>> y.b
2
>>> y.c
3
>>> z = pset()
>>> z.a = 1
>>> z.b = 2
>>> z.c = 3
>>> z[1]
2
>>> z
pset(a=1, b=2, c=3)
>>> class Point(pset): pass
>>> p = Point(x=11, y=22)
>>> p
Point(y=22, x=11)
dk.collections.pset.xmlrepr(v, toplevel=False)[source]

Return v as xml tag-soup.

dk.collections.sdict module
class dk.collections.sdict.sdict(**attrs)[source]

Bases: dict

Sorted Dictionary class. Iterating over the sdict will give back the key/value pairs in order of insertion. A key can only be in a sdict once.

keys()[source]
values()[source]
dk.collections.xmlrec module
dk.collections.xmlrec.Boolean(s)[source]
dk.collections.xmlrec.Date(s)[source]
dk.collections.xmlrec.Datetime(s)[source]
dk.collections.xmlrec.NOK(s)[source]
class dk.collections.xmlrec.xmlrec(soup, **types)[source]

Bases: dk.collections.pset.pset

convert = {'date': <function Date>, 'int': <type 'int'>, 'NOK': <function NOK>, 'bool': <function Boolean>, 'datetime': <function Datetime>}
Module contents

Abstract Data Types – mostly record types with different semantics.

dk.html package
Submodules
dk.html.css module
class dk.html.css.css(**attrs)[source]

Bases: dk.collections.pset.pset

dk.html.html module

HTML helper file.

class dk.html.html.a(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.abbr(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.acronym(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.address(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.applet(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.area(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.b(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.base(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.bdo(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.big(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.blockquote(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.body(*content, **kw)

Bases: dk.html.html.tag

dk.html.html.bokmaal

alias of link

class dk.html.html.br(**kw)

Bases: dk.html.html.xtag

class dk.html.html.bsefont(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.button(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.caption(*content, **kw)

Bases: dk.html.html.dtag

class dk.html.html.center(*content, **kw)

Bases: dk.html.html.tag

dk.html.html.checkbox_input

alias of input

class dk.html.html.cite(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.closetag(tag_name, *content, **kw)[source]

Bases: dk.html.html.tag

flatten(lst=None)[source]
class dk.html.html.code(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.col(**kw)

Bases: dk.html.html.xtag

class dk.html.html.colgroup(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.color[source]
aqua = '"#00FFFF"'
black = '"#000000"'
blue = '"#0000FF"'
fuchsia = '"#FF00FF"'
gray = '"#808080"'
green = '"#008000"'
lime = '"#00FF00"'
maroon = '"#800000"'
navy = '"#000080"'
olive = '"#808000"'
purple = '"#800080"'
red = '"#FF0000"'
silver = '"#COCOCO"'
teal = '"#008080"'
white = '"#FFFFFF"'
yellow = '"#FFFF00"'
class dk.html.html.dd(*content, **kw)

Bases: dk.html.html.tag

dk.html.html.del_

alias of del

class dk.html.html.dfn(*content, **kw)

Bases: dk.html.html.tag

dk.html.html.dir_

alias of dir

class dk.html.html.div(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.dl(*content, **kw)

Bases: dk.html.html.tag

dk.html.html.doctype

alias of DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"     "http://www.w3.org/TR/html4/strict.dtd"

dk.html.html.doctype401frameset

alias of DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"     "http://www.w3.org/TR/html4/frameset.dtd"

dk.html.html.doctype401strict

alias of DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"     "http://www.w3.org/TR/html4/strict.dtd"

dk.html.html.doctype401transitional

alias of DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"     "http://www.w3.org/TR/html4/loose.dtd"

class dk.html.html.dt(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.dtag(tag_name, *content, **kw)[source]

Bases: dk.html.html.tag

d(issappearing)tag: if the content is empty, i.e. self.content == (‘’,) this tag doesn’t output anything at all. Useful for legends, table captions, etc.

class dk.html.html.em(*content, **kw)

Bases: dk.html.html.tag

dk.html.html.english

alias of link

dk.html.html.escape(strval, enc=None)[source]

Convert string s (potentially unicode) to a ascii string with entitydefs like &oslash; &aelig; etc.

dk.html.html.escape_char(unichar)[source]
dk.html.html.escaped_array(strval)[source]

Convert unicode string to list of ascii characters or entitydefs like &oslash; etc.

class dk.html.html.fieldset(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.font(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.form(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.frame(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.frameset(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.h1(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.h2(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.h3(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.h4(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.h5(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.h6(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.head(*content, **kw)

Bases: dk.html.html.tag

dk.html.html.hidden_input

alias of input

class dk.html.html.hr(**kw)

Bases: dk.html.html.xtag

class dk.html.html.html(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.i(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.iframe(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.img(**kw)

Bases: dk.html.html.xtag

class dk.html.html.input(**kw)

Bases: dk.html.html.xtag

class dk.html.html.ins(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.kbd(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.label(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.legend(*content, **kw)

Bases: dk.html.html.dtag

class dk.html.html.li(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.lines(*content)[source]

Bases: dk.html.html.text

like text, except each item in content is separated with a <br> tag.

flatten()[source]

Bases: dk.html.html.xtag

class dk.html.html.map(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.menu(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.meta(**kw)

Bases: dk.html.html.xtag

dk.html.html.mkdtag(name, **attrs)[source]
dk.html.html.mkstag(name)[source]
dk.html.html.mktag(name, _parent=<class 'dk.html.html.tag'>, _nlafter=False, **attrs)[source]
dk.html.html.mkxtag(name, **attrs)[source]
dk.html.html.next

alias of link

class dk.html.html.nobr(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.noframes(*content, **kw)

Bases: dk.html.html.tag

dk.html.html.norm_attr_name(attr)[source]
dk.html.html.normalize(v)[source]

returns a stringified unicode version of v

dk.html.html.norsk

alias of link

class dk.html.html.noscript(*content, **kw)

Bases: dk.html.html.tag

dk.html.html.nynorsk

alias of link

dk.html.html.object_

alias of object

class dk.html.html.ol(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.opentag(tag_name, *content, **kw)[source]

Bases: dk.html.html.tag

flatten(lst=None)[source]
class dk.html.html.optgroup(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.option(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.p(*content, **kw)

Bases: dk.html.html.tag

dk.html.html.page(xtitle, abody)[source]

Shortcut to get a page up quickly.

class dk.html.html.param(*content, **kw)

Bases: dk.html.html.tag

dk.html.html.password_input

alias of input

dk.html.html.pdf

alias of link

dk.html.html.plain_attribute(strval, legal='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._:')[source]
class dk.html.html.pre(*content, **kw)

Bases: dk.html.html.tag

dk.html.html.prev

alias of link

class dk.html.html.q(*content, **kw)

Bases: dk.html.html.tag

dk.html.html.quote(strval)
dk.html.html.quote_if_needed(strval)[source]
dk.html.html.quote_smart(strval)[source]
dk.html.html.quote_xhtml(v)[source]
dk.html.html.radio_input

alias of input

dk.html.html.rawstr2unicode(strval)[source]
class dk.html.html.s(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.samp(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.script(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.select(options, selected=None, **kw)[source]

Bases: dk.html.html.tag

options
selected
values
class dk.html.html.small(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.span(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.sqlresult(res, desc=None, **kw)[source]

Bases: dk.html.html.tag

class dk.html.html.stag(tag_name, **kw)[source]

Bases: dk.html.html.xtag

s(ingle)tag

dk.html.html.start

alias of link

class dk.html.html.strike(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.strong(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.style(*content, **kw)

Bases: dk.html.html.tag

dk.html.html.stylesheet

alias of link

class dk.html.html.sub(*content, **kw)

Bases: dk.html.html.tag

dk.html.html.submit_button

alias of input

class dk.html.html.sup(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.table(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.tabledesc(*cols)[source]

Bases: object

class dk.html.html.tag(tag_name, *content, **kw)[source]

Bases: dk.html.html.xtag

Regular tag: outputs an open tag with attributes, followed by its contents, followed by a closing tag.

Attributes can be set either as keyword arguments in the constructor or by assigning to attributes of the object.

Content can be any combination of items, iterables, and generators:

>>> table(tr(td(i) for i in range(5)), tr(td(i**i) for i in range(5)))
<table><tr><td>0</td><td>1</td><td>2</td><td>3</td><td>4</td></tr>
<tr><td>1</td><td>1</td><td>4</td><td>27</td><td>256</td></tr>
</table>

NB: Attributes that conflict with Python keywords have an underline appended, e.g.: mytag.class_ = ...

close_tag()[source]
flatten(lst=None)[source]
open_tag()[source]
xcontent
class dk.html.html.tbody(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.td(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.text(*content)[source]

Bases: dk.html.html.tag

text tag: outputs its contents without any tags around it. Useful for grouping at the top level.

flatten()[source]
dk.html.html.text_input

alias of input

class dk.html.html.textarea(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.tfoot(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.th(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.thead(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.title(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.tr(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.tt(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.u(*content, **kw)

Bases: dk.html.html.tag

dk.html.html.u8escape(strval)[source]
class dk.html.html.ul(*content, **kw)

Bases: dk.html.html.tag

dk.html.html.unescape(txt)[source]

Convert text containing entitydefs into Unicode.

class dk.html.html.var(*content, **kw)

Bases: dk.html.html.tag

class dk.html.html.xtag(tag_name, **kw)[source]

Bases: object

x(ml-style)tag: a tag without content or a closing tag.

E.g. <br/> would be xtag(‘br’)

[2009-03-11]
w3 validator complains that 4.01 loose should not use <foo /> but <foo>.
attributes()[source]

return a string like key=”val”.

flatten()[source]
dk.html.theme module

Attempt at defining themes from Python (probably better to do this elsewhere).

dk.html.theme.mkpalette(_source, base, colorlist)[source]

Convenience function to define a palette.

class dk.html.theme.palette[source]

Color palettes from http://colormatch.dk. Colors are named with a lower case x in front of the nearest defined colorvalue.

class LightSkyBlue2[source]
Gray7 = '#121212'
Gray93 = '#ededed'
LightSkyBlue2 = '#a4d3ee'
get = ['#a4d3ee', '#6f8ea1', '#edd7a4', '#a1896f', '#121212', '#ededed']
xLemonChiffon4 = '#a1896f'
xLightSlateGray = '#6f8ea1'
xNavajoWhite2 = '#edd7a4'
class palette.xForrestGreen[source]
Gray48 = '#7a7a7a'
Gray52 = '#858585'
get = ['#257b24', '#3cc73a', '#5f7a23', '#9ac73a', '#858585', '#7a7a7a']
xForrestGreen = '#257b24'
xLimeGreen = '#3cc73a'
xOliveDrab4 = '#5f7a23'
xYellowGreen = '#9ac73a'
dk.html.uhtml module

New version of html.py module that works on/with Unicode.

class dk.html.uhtml.EscapedString[source]

Bases: unicode

class dk.html.uhtml.a(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.abbr(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.acronym(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.address(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.applet(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.area(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.b(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.base(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.bdo(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.big(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.blockquote(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.body(*content, **kw)

Bases: dk.html.uhtml.tag

dk.html.uhtml.bokmaal

alias of link

class dk.html.uhtml.br(**kw)

Bases: dk.html.uhtml.xtag

class dk.html.uhtml.bsefont(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.button(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.caption(*content, **kw)

Bases: dk.html.uhtml.dtag

class dk.html.uhtml.center(*content, **kw)

Bases: dk.html.uhtml.tag

dk.html.uhtml.checkbox_input

alias of input

class dk.html.uhtml.cite(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.closetag(tag_name, *content, **kw)[source]

Bases: dk.html.uhtml.tag

flatten(lst=None)[source]
class dk.html.uhtml.code(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.col(**kw)

Bases: dk.html.uhtml.xtag

class dk.html.uhtml.colgroup(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.dd(*content, **kw)

Bases: dk.html.uhtml.tag

dk.html.uhtml.del_

alias of del

class dk.html.uhtml.dfn(*content, **kw)

Bases: dk.html.uhtml.tag

dk.html.uhtml.dir_

alias of dir

class dk.html.uhtml.div(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.dl(*content, **kw)

Bases: dk.html.uhtml.tag

dk.html.uhtml.doctype

alias of DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"     "http://www.w3.org/TR/html4/strict.dtd"

dk.html.uhtml.doctype401frameset

alias of DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN"     "http://www.w3.org/TR/html4/frameset.dtd"

dk.html.uhtml.doctype401strict

alias of DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"     "http://www.w3.org/TR/html4/strict.dtd"

dk.html.uhtml.doctype401transitional

alias of DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"     "http://www.w3.org/TR/html4/loose.dtd"

class dk.html.uhtml.dt(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.dtag(tag_name, *content, **kw)[source]

Bases: dk.html.uhtml.tag

d(issappearing)tag: if the content is empty, i.e. self.content == (‘’,) this tag doesn’t output anything at all. Useful for legends, table captions, etc.

class dk.html.uhtml.em(*content, **kw)

Bases: dk.html.uhtml.tag

dk.html.uhtml.english

alias of link

dk.html.uhtml.escape(s, enc=None)[source]

Convert string s (potentially unicode) to a ascii string with entitydefs like &oslash; &aelig; etc.

dk.html.uhtml.escape_char(unichar)[source]
dk.html.uhtml.escaped_array(s)[source]

Convert unicode string to list of ascii characters or entitydefs like &oslash; etc.

class dk.html.uhtml.fieldset(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.font(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.form(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.frame(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.frameset(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.h1(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.h2(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.h3(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.h4(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.h5(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.h6(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.head(*content, **kw)

Bases: dk.html.uhtml.tag

dk.html.uhtml.hidden_input

alias of input

class dk.html.uhtml.hr(**kw)

Bases: dk.html.uhtml.xtag

class dk.html.uhtml.html(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.i(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.iframe(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.img(**kw)

Bases: dk.html.uhtml.xtag

class dk.html.uhtml.input(**kw)

Bases: dk.html.uhtml.xtag

class dk.html.uhtml.ins(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.kbd(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.label(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.legend(*content, **kw)

Bases: dk.html.uhtml.dtag

class dk.html.uhtml.li(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.lines(*content)[source]

Bases: dk.html.uhtml.text

like text, except each item in content is separated with a <br> tag.

flatten()[source]

Bases: dk.html.uhtml.xtag

class dk.html.uhtml.map(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.menu(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.meta(**kw)

Bases: dk.html.uhtml.xtag

dk.html.uhtml.mkdtag(name, **attrs)[source]
dk.html.uhtml.mkstag(name)[source]
dk.html.uhtml.mktag(name, _parent=<class 'dk.html.uhtml.tag'>, _nlafter=False, **attrs)[source]
dk.html.uhtml.mkxtag(name, **attrs)[source]
dk.html.uhtml.next

alias of link

class dk.html.uhtml.nobr(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.noframes(*content, **kw)

Bases: dk.html.uhtml.tag

dk.html.uhtml.norm_attr_name(a)[source]

_foo_bar => _foo_bar, class_ => class, max_height => max-height

>>> norm_attr_name(u'class_')
u'class'
>>> norm_attr_name(u'z_index')
u'z-index'
dk.html.uhtml.normalize(v)[source]

returns a stringified unicode version of v

dk.html.uhtml.norsk

alias of link

class dk.html.uhtml.noscript(*content, **kw)

Bases: dk.html.uhtml.tag

dk.html.uhtml.nynorsk

alias of link

dk.html.uhtml.object_

alias of object

class dk.html.uhtml.ol(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.opentag(tag_name, *content, **kw)[source]

Bases: dk.html.uhtml.tag

flatten(lst=None)[source]
class dk.html.uhtml.optgroup(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.option(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.p(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.param(*content, **kw)

Bases: dk.html.uhtml.tag

dk.html.uhtml.password_input

alias of input

dk.html.uhtml.pdf

alias of link

class dk.html.uhtml.pre(*content, **kw)

Bases: dk.html.uhtml.tag

dk.html.uhtml.prev

alias of link

class dk.html.uhtml.q(*content, **kw)

Bases: dk.html.uhtml.tag

dk.html.uhtml.quote(v)[source]
>>> quote(u"Bjorn's")
u'"Bjorn\'s"'
>>> quote(u'the "best"')
u'"the &quot;best&quot;"'
dk.html.uhtml.radio_input

alias of input

dk.html.uhtml.rawstr2unicode(s)[source]
class dk.html.uhtml.s(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.samp(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.script(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.select(options, selected=None, **kw)[source]

Bases: dk.html.uhtml.tag

options
selected
values
class dk.html.uhtml.small(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.span(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.stag(tag_name, **kw)[source]

Bases: dk.html.uhtml.xtag

s(ingle)tag

dk.html.uhtml.start

alias of link

class dk.html.uhtml.strike(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.strong(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.style(*content, **kw)

Bases: dk.html.uhtml.tag

dk.html.uhtml.stylesheet

alias of link

class dk.html.uhtml.sub(*content, **kw)

Bases: dk.html.uhtml.tag

dk.html.uhtml.submit_button

alias of input

class dk.html.uhtml.sup(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.table(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.tabledesc(*cols)[source]

Bases: object

class dk.html.uhtml.tag(tag_name, *content, **kw)[source]

Bases: dk.html.uhtml.xtag

Regular tag: outputs an open tag with attributes, followed by its contents, followed by a closing tag.

Attributes can be set either as keyword arguments in the constructor or by assigning to attributes of the object.

Content can be any combination of items, iterables, and generators:

>> table(tr(td(i) for i in range(5)), tr(td(i**i) for i in range(5)))

NB: Attributes that conflict with Python keywords have an underline appended, e.g.: mytag.class_ = ...

close_tag()[source]
flatten(lst=None)[source]
open_tag()[source]
xcontent
class dk.html.uhtml.tbody(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.td(*content, **kw)

Bases: dk.html.uhtml.tag

dk.html.uhtml.test_doctest()[source]
>>> br()
u'<br>'
>>> div('hello', b('world'))
u'<div>hello<b>world</b></div>\n'
>>> print select(options=[u'a', u'b'], name='foo')
u'<select name="foo" id="id_foo"><option value="a">a</option>\n<option value="b">b</option>\n</select>'
class dk.html.uhtml.text(*content)[source]

Bases: dk.html.uhtml.tag

text tag: outputs its contents without any tags around it. Useful for grouping at the top level.

flatten()[source]
dk.html.uhtml.text_input

alias of input

class dk.html.uhtml.textarea(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.tfoot(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.th(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.thead(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.title(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.tr(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.tt(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.u(*content, **kw)

Bases: dk.html.uhtml.tag

dk.html.uhtml.u8escape(s)[source]
class dk.html.uhtml.ul(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.var(*content, **kw)

Bases: dk.html.uhtml.tag

class dk.html.uhtml.xtag(tag_name, **kw)[source]

Bases: object

x(ml-style)tag: a tag without content or a closing tag. E.g. <br/> would be xtag(‘br’)

Note

[2009-03-11] w3 validator complains that 4.01 loose should not use <foo /> but <foo>.

attributes()[source]

return a string like key=”val”.

flatten()[source]
Module contents
dk.identifiers package
Submodules
dk.identifiers.kid module

Strukturen på våre kid-nummer: sensornr = ‘0123’ # fire siffer kandidatnr = ‘01234’ # fem siffer

kiddata = sensornr + kandidatnr kid = kiddata + kontroll_10(kiddata)

dk.identifiers.kid.create_kids(tctr, sequencenum)[source]

BFP-8

dk.identifiers.kid.generate_kids(sensornr, count, start=0)[source]

Generate count kid numbers for sensor with sensornr (prefix), starting at start (for the counting part of the kid).

dk.identifiers.kid.is_valid_kid(s)[source]

Test if s is a valid kid number.

dk.identifiers.kid.kontroll_10(s)[source]

MOD10 algoritmen.

MOD10 er forkortelse for Modulus 10 algoritmen, også kalt Luhn-algoritmen etter oppfinneren Hans Peter Luhn. Modulus 10 algoritmen benyttes bl.a. som beregningsmetode for et kontrollsiffer i KID-numre på bankenes innbetalingsblanketter. (http://no.wikipedia.org/wiki/MOD10)

dk.identifiers.kid.kontroll_11(s)[source]

MOD11 algoritmen.

MOD11 er forkortelse for Modulus11. Modulus11 benyttes blant annet som beregningsmetode for et kontrollsiffer i kontonumre i norske banker, organisasjonsnummer og for det siste sifferet i norske fødselsnummer. (Norske fødselsnummer har to kontrollsifre, det nest siste er også et modulo 11 kontrollsiffer, men ved beregningen av dette benyttes det multiplikatorer i en annen og uregelmessig rekkefølge). (http://no.wikipedia.org/wiki/MOD11)

dk.identifiers.kid.vekt(n, base)[source]

Funksjon som gir en repeterende serie med siffer fra base, som har lengde n.

For kontroll_10 er vekttall-serien: 2,1,2,1,2,1... for kontroll_11 er vekttall-serien: 2,3,4,5,6,7,2,3,4,5,...

dk.identifiers.navn module

Operations on names: shortening, normalizing, ...

TODO: This module should be connected to the names database.

exception dk.identifiers.navn.Name2Long[source]

Bases: exceptions.ValueError

The name is too long and cannot be shortened.

dk.identifiers.navn.combine(fornavn, etternavn)[source]

Combine fornavn and etternavn with a space in-between. Remove any double spaces and fix capitalization.

dk.identifiers.navn.forkort_navn(lengde, fornavn, etternavn)[source]

Shorten names and return the result as a string.

dk.identifiers.navn.forkort_navn_u8(lengde, fornavn_u8, etternavn_u8)[source]
dk.identifiers.navn.normalize(fornavn, etternavn)[source]

Normalize double spaces and title case.

dk.identifiers.navn.normalize2u8(navn)[source]

Normalized := Utf-8 And Title Case.

dk.identifiers.navn.normalize2uni(navn_u8)[source]

Normalized := Unicode And Title Case.

dk.identifiers.navn.shorten(lengde, fornavn, etternavn)[source]

Apply algorithms described above, first to first-names, then to last-names. Return tuple of (fornavn, etternavn).

dk.identifiers.navn.shorten_fname(length, fname)[source]

Try to shorten the first-name fname to length characters (raise ValueError if we fail).

Algorithm: Consider the last of the person’s first names and replace it
with its initial. If the resulting name is still too long, then call ourselves recursively.
dk.identifiers.navn.shorten_fname_u8(length, fname)[source]
dk.identifiers.navn.shorten_lname(length, lname)[source]

Try to shorten the last-name lname to length characters (raise ValueError if we fail).

Algorithm: Consider the first of the person’s last names and replace it
with its initial. If the resulting name is still too long, then call ourselves recursively.
dk.identifiers.navn.shorten_lname_u8(length, lname)[source]
dk.identifiers.navn.shorten_u8(lengde, fornavn, etternavn)[source]
dk.identifiers.navn.test_module()[source]
>>> forkort_navn(25, 'Bjorn Steinar', 'Fjeld Pettersen')
u'Bjorn S Fjeld Pettersen'
>>> forkort_navn(22, 'Bjorn Steinar', 'Fjeld Pettersen')
u'Bjorn S F Pettersen'
>>> forkort_navn(18, 'Bjorn Steinar', 'Fjeld Pettersen')
Traceback (most recent call last):
...
ValueError: Bjorn S F Pettersen kan ikke forkortes til 18 bokstaver
>>> v = forkort_navn(25, u'Bjørn Øystein', u'Fjeld Pettersen')
>>> u'Bjørn Ø Fjeld Pettersen'
>>> v == u'Bjørn Ø Fjeld Pettersen'
True
>>> v = forkort_navn(21, u'Bjørn Øystein', u'Ødal Pettersen')
>>> v == u'Bjørn Ø Ø Pettersen'
True
>>> v = forkort_navn_u8(21, u'Bjørn Øystein'.encode('u8'), u'Ødal Pettersen'.encode('u8'))
>>> v == u'Bjørn Ø Ø Pettersen'.encode('u8')
True

Normalisering av navn til utf-8 med stor forbokstav som eneste store bokstav.

>>> normalize2u8(u'Bjørn') == u'Bjørn'.encode('u8')
True
>>> normalize2u8(u'BJørn') == u'Bjørn'.encode('u8')
True
>>> normalize2u8(u'BJØrn'.encode('u8')) == u'Bjørn'.encode('u8')
True
>>> normalize2u8(u'geir-arne') == 'Geir-Arne'
True
dk.identifiers.persnr module

Norwegian ‘Personnummer’ module.

exception dk.identifiers.persnr.PersnrException[source]

Bases: exceptions.ValueError

Base exception for persnr module.

class dk.identifiers.persnr.TestingPersnr[source]

Bases: object

Class to generate personnummer.

next_persnr()[source]
dk.identifiers.persnr.calc_par1(ppnr)[source]

Calculate the first parity digit.

dk.identifiers.persnr.calc_par2(ppnr)[source]

Calculate the second parity digit.

dk.identifiers.persnr.calc_parity(ppnr)[source]

Calculate parity digits.

dk.identifiers.persnr.calc_year(yr2, inr)[source]

Find the 4-digit year, following all the rules.

dk.identifiers.persnr.check_individnr(inr, year4)[source]

Hopelessly inefficient way of checking the individnr.

dk.identifiers.persnr.check_parity(pnr)[source]

Check the last two digits, which are parity controls.

dk.identifiers.persnr.check_pnr(pnr, birthday, sex)[source]
>>> check_pnr('02057035768', datetime.date(1970, 5, 2), 'm')
True
dk.identifiers.persnr.check_pnr_structure(pnr)[source]

Raise exception if the structure of the personnummer is incorrect.

dk.identifiers.persnr.date(pnr)[source]

Find the birth date and return as datetime.date() object.

dk.identifiers.persnr.gender(pnr)[source]

Extract the gender as ‘M’ for male and ‘F’ for female.

dk.identifiers.persnr.generate_pnr(day, gndr)[source]

Generate all persnrs for a given gender on a given day.

dk.identifiers.persnr.is_persnr(pnr, country='NO')[source]

Return True if pnr is a valid persnr.

dk.identifiers.persnr.list_pnr(day=None, gender='M')[source]

List all persnrs for a given gender on a given day.

dk.identifiers.persnr.multiply_reduce(avec, bvec)[source]

Multiply each item in a with corresponding item in b, then sum the result.

dk.identifiers.persnr.splitpnr(pnr)[source]

Split the personnummer into it’s parts.

dk.identifiers.persnr.testing_persnr(n=0)[source]

Create a persnr for use in unit tests. If different tests need separate persnr, pass a unique small integer as a parameter.

dk.identifiers.persnr.year(pnr)[source]

Extract the year from pnr.

Module contents
dk.js package
Submodules
dk.js.js module

This module is dedicated to creating javascript snippets that can be consumed elsewhere. (uses MochiKit and seems to be imported in way too many places...)

dk.js.js.focus(item)[source]

Output javascript to focus on item.

dk.js.js.javascript(txt, **args)[source]

Compress javascript into a single line, for in-situ on___ handlers.

Same as a html.a element

dk.js.js.set_datefield(name, year, month, day)[source]

The year/month/day values need to be calculated as in the SetDateButton in widgets.

dk.js.js.setpnumber_connect(postnrid)[source]

Add onblur handler that connects the above event handler.

dk.js.js.setpnumber_function(postnrid, poststedid)[source]

Event handler to load poststed from postnr, through an ajax call.

dk.js.js.submit_form(formname)[source]

JS sniplet that will submit the named form when being the target of an event-handler.

Module contents
dk.ttcal package
Submodules
dk.ttcal.calfns module
dk.ttcal.calfns.chop(it, n)[source]

Chop iterator into n size chuchks.

dk.ttcal.calfns.isoweek(year, week)[source]

Iterate over the days in isoweek week of year.

dk.ttcal.calfns.rangecmp()[source]

Compare half-open intervals [a, b) and [c, d) They compare equal if there is overlap.

dk.ttcal.calfns.rangetuple(x)[source]
dk.ttcal.day module

Date (single day) operations.

class dk.ttcal.day.Day[source]

Bases: datetime.date

A calendar date.

Month

Return a Month object representing the month self belongs to.

Year

Return a Year object representing the year self belongs to.

between_tuple()[source]

Return a tuple of datetimes that is convenient for sql between queries.

code

One letter code representing the dayname.

compare(other)[source]

Return how similar self is to other, i.e. the smallest factor they have in common (‘day’, ‘month’, or ‘year’). Returns None if the Days are in different years.

date()[source]

Excplicitly convert to datetime.date.

datetime(hour=0, minute=0, second=0)[source]

Extend self to datetime.

datetuple()[source]

Return year, month, day.

day_code = ['M', 'U', 'W', 'H', 'F', 'A', 'S']
day_name = [u'mandag', u'tirsdag', u'onsdag', u'torsdag', u'fredag', u'l\xf8rdag', u's\xf8ndag']
dayname

The semi-localized name of self.

display

Return the ‘class’ of self.

first

Define self == self.first for polymorphic usage with other classes.

format(fmt=None)[source]

Emulate Django’s date filter.

classmethod from_idtag(tag)[source]

Return Day from idtag.

static get_day_name(daynum, length=None)[source]

Return dayname for daynum.

idtag

Return the idtag for self: dyyyymmddmm.

in_month

True iff the day is in its month.

isoyear

Return the isoyear of self.

last

Define self == self.last for polymorphic usage with other classes.

middle

Return the day that splits the date range in half.

next()[source]

Return Tomorrow (for use in templates).

classmethod parse(strval)[source]

Parse date value from a string. Allowed syntax include

yyyy-mm-dd, yyyy-m-dd, yyyy-mm-d, yyyy-m-d
dd-mm-yyyy, etc.
dd/mm/yyyy, ...
dd.mm.yyyy, ...
ddmmyyyy
prev()[source]

Return Yesterday (for use in templates).

range()[source]

Return an iterator for the range of self.

rangetuple()[source]
special

True if the database has an entry for this date (sets special_hours).

timetuple()[source]

Create timetuple from datetuple. (to interact with datetime objects).

today

True if self is today.

week

Return a Week object representing the week self belongs to.

weekday

True if self is a weekday.

weekend

True if self is Saturday or Sunday.

weeknum

Return the isoweek of self.

class dk.ttcal.day.Days(start, end, start_week=False)[source]

Bases: list

A contigous set of days.

between_tuple()[source]

Return a tuple of datetimes that is convenient for sql between queries.

first

1st day

last

last day

middle

Return the day that splits the date range in half.

range()[source]

Return an iterator for the range of self.

class dk.ttcal.day.Today[source]

Bases: dk.ttcal.day.Day

Special subclass for today’s date.

today = True
dk.ttcal.duration module

Extension of datetime.timedelta.

class dk.ttcal.duration.Duration[source]

Bases: datetime.timedelta

A duration of time.

duration_tuple()[source]

Return self as hours, minutes, seconds.

hrs

The number of hours in self.

mins

The number of minutes in self.

classmethod parse(txt)[source]

Parse a textual representation into a Duration object. Format HHH:MM:SS.

secs

The number of seconds in self.

classmethod sum(sequence, start=None)[source]

Return the sum of sequence. (built-in sum only works with numbers).

toint()[source]

Convert self to integer.

dk.ttcal.month module
class dk.ttcal.month.Month(year=None, month=None, date=None)[source]

Bases: object

A calendar month.

Month
Year

Return a Year object for the year-part of this month.

between_tuple()[source]

Return a tuple of datetimes that is convenient for sql between queries.

datetuple()[source]

First date in month.

daycount

The number of days in this month (as an int).

dayiter()[source]
days()[source]

Return a list of days (class:ttcal.Day) in this month.

first

First day in month.

format(fmt=None)[source]

Format according to format string. Default format is monthname, four-digit-year.

classmethod from_date(d)[source]

Create a Month from the date d.

classmethod from_idtag(tag)[source]

Parse idtag into class:Month.

idtag()[source]

Return a text representation that is parsable by the from_idtag function (above), and is useable as part of an url.

last

Last day in month.

mark(d, value='mark', method='replace')[source]
marked_days()[source]
middle

Return the day that splits the date range in half.

month = None
month_name = ['', 'Januar', 'Februar', 'Mars', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Desember']
next()[source]

Next month.

numdays()[source]

The number of days in the month.

classmethod parse(txt)[source]

Parse a textual representation into a Month object. Format YYYY-MM?

prev()[source]

Previous month.

range()[source]

Return an iterator for the range of self.

rangetuple()[source]
timetuple()[source]

Create timetuple from datetuple. (to interact with datetime objects).

year = None
dk.ttcal.week module
class dk.ttcal.week.Week(days, month)[source]

Bases: object

between_tuple()[source]

Return a tuple of datetimes that is convenient for sql between queries.

current

True if today is in week.

datetuple()[source]

First day of this week.

days = None
first

1st day of week.

classmethod from_idtag(tag)[source]
idtag()[source]
last

Last day of week.

middle

Return the day that splits the date range in half.

month = None
num = None
range()[source]

Return an iterator for the range of self.

rangetuple()[source]
until_today()[source]
classmethod weeknum(n=None, year=None)[source]
year = None
dk.ttcal.year module
class dk.ttcal.year.Year(year=None)[source]

Bases: object

H1

First half of this year.

H2

Last half of this year.

Month

For orthogonality in the api.

Q1

1st quarter.

Q2

2nd quarter.

Q3

3rd quarter.

Q4

4th quarter.

Year
april
august
between_tuple()[source]

Return a tuple of datetimes that is convenient for sql between queries.

datetuple()[source]

January 1.

dayiter()[source]
december
february
first

First day of first month.

format(fmt=None)[source]

Format according to format string. Default format is monthname, four-digit-year.

classmethod from_idtag(tag)[source]

Year tags have the lower-case letter y + the four digit year, eg. y2008.

halves()[source]

Both halves of the year.

idtag()[source]

Year tags have the lower-case letter y + the four digit year, eg. y2008.

january
july
june
last

Last day of last month.

march
mark(d, value='mark')[source]
mark_period(p, value='mark')[source]
marked_days()[source]
may
middle

Return the day that splits the date range in half.

next()[source]

Next year.

november
october
prev()[source]

Previous year.

quarters()[source]

Every quarter in this year.

range()[source]

Return an iterator for the range of self.

rangetuple()[source]
rows()[source]
rows4()[source]
september
timetuple()[source]
Module contents

Date classes (originally from TikTok).

dk.ttcal.from_idtag(idtag)[source]

Return a class from idtag.

Submodules

dk.age module

Age (date subtraction) routines.

class dk.age.age(dob, today=None)[source]

Bases: object

The number of years, months, and days since date of birth.

dk.age.birthday_this_year(birthday, today=None)[source]

Return the date of the birthday in the current year.

dk.age.days_ago(n, dato=None)[source]

The date that is n days before dato (or today).

dk.age.next_birthday(birthday, today=None)[source]

Return the date of the next birthday for someone born on date birthday.

dk.age.previous_birthday(birthday, today=None)[source]

Return the previous birthday relative to today.

dk.age.weeks_ago(n, today=None)[source]

The date that is n weeks before today.

dk.age.years_ago(n, today=None)[source]

The date that is n years before today.

dk.asciify module

Convert unicode strings to visually similar ascii representations.

dk.asciify.ascii_name(name)[source]

Convert name from unicode to a ascii representation that (while surely a grave bastardization) can be used as a filename without (ever!) causing problems.

dk.asciify.asciify(s, spaces=None, legal=None, replacement='')[source]

Convert unicode string s to a similarly looking ascii string.

If spaces is specified, runs of space characters are replaced with exactly one spaces.

If legal is specified (as a string), only characters from legal will be in the result, otherwise all characters from ascii 32 to ascii 127 are allowed.

If replacement is passed, then any characters that are elided will be replaced by replacement.

dk.asciify.slug(txt)[source]

Same as above, but intended for URIs.

dk.dkimport module

Convenience function for importing a fqdn from a package. (to hide the baroque nature of __import__).

dk.dkimport.defined_symbols(module, attrfilter=None, itemfilter=None)[source]

Return symbols that are defined in module.

dk.dkimport.dkimport(name)[source]

Import and return the item specified by name:

Usage:

>>> item = dkimport('dk.core.dkimport.dkimport')
>>> item.__name__
'dkimport'
dk.dkimport.dkimport_functions(modname, **kw)[source]

Return all functions from all direct sub-modules of modname.

dk.dkimport.dkimport_star(modname, **kw)[source]

Import all names from module modname, similar to:

from modname import *

Available **kw arguments:

filefilter A function that receives a filename (with extension
but without path) that should return True if the filename should be included.

useful for modularly implementing functionality, yet making it dynamically available from the top namespace:

...path/cmds/a.py
    def a(): ...
...path/cmds/b.py
    def b(): ...
...path/cmds/c.py
    def c(): ...

...path/cmds/__init__.py
    from dk.dkimport import dkimport_star as _dki

    for _item in _dki('..path.cmds'):
        if hasattr(_item, '__name__'):
            globals()[_item.__name__] = _item
dk.dkimport.load_files_from(module_path, module_name, filefilter=None)[source]

Load all .py files in module.

dk.dklogger module

Convenience function for installing a module level logger:

from dk import dklogger
logger = dklogger.dklogger(__name__, debug=1, info=1)
logger.setLevel(dklogger.DEBUG)

to prevent logging to stdout, pass stream=None

dk.dklogger.dklogger(name, debug=False, info=False, fname=None, stream=<open file '<stdout>', mode 'w'>, format='%(asctime)s %(levelname)-7s\n %(pathname)s@%(funcName)s:%(lineno)d %(message)s', datefmt='%Y-%m-%d %H:%M:%S')[source]

dk.findapps module

Module for finding all apps folders.

dk.findapps.appfolder(appname)[source]

Return app folder for appname.

dk.findapps.appfolders()[source]

Find all django app folders, yield absolute paths to the folders.

dk.findapps.appname(folder)[source]

Return the app name for the (app)folder).

dk.findapps.appnames()[source]

Find the name of all the apps.

dk.findapps.is_appfolder(path)[source]

Is the path an app folder?

dk.fstr module

class dk.fstr.fstr[source]

Bases: str

String sub-class with a split() method that splits a given indexes.

Usage:

>>> r = fstr('D2008022002')
>>> print r.split(1, 5, 7, 9)
['D', '2008', '02', '20', '02']
>>> _, year, _ = r.split(1,5)
>>> year
'2008'
split(*ndxs)[source]

dk.grid module

A 2D grid with slicing.

Usage:

>>> t = grid(emptyval=0)
>>> t.apply[:5,:5] = lambda v, (y,x):y*x
>>> t
 0 0 0  0  0
 0 1 2  3  4
 0 2 4  6  8
 0 3 6  9 12
 0 4 8 12 16
>>> t.apply[:5,:5] = lambda v, p:v*2
>>> t
 0 0  0  0  0
 0 2  4  6  8
 0 4  8 12 16
 0 6 12 18 24
 0 8 16 24 32
>>> t2 = grid.copy(t, lambda orig, (y,x):orig[y,x] / 2)
>>> t2
 0 0 0  0  0
 0 1 2  3  4
 0 2 4  6  8
 0 3 6  9 12
 0 4 8 12 16
class dk.grid.Empty(emptyval=None)[source]

Bases: dk.proxy.proxy

setval(v)[source]
class dk.grid.grid(rows=0, cols=0, emptyval=None)[source]

Bases: object

This is a tabular object of two dimensions that supports slice notation.

Deleted = <->
apply
apply_cell(y, x, fn)[source]
apply_iterator()[source]

You can implement the game of life style actions with this iterator:

def average((y,x)):
    return sum(t[y-1:y+1, x-1:x+1]) / 9.0
t.apply[:2, :2] = lambda value, key: average(key)
columns
classmethod copy(tgrid, fn=None)[source]
copy_area()[source]
del_cell(y, x)[source]
empty_col(x)[source]
empty_row(y)[source]
get_cell(y, x)[source]
get_col(x)[source]
get_row(y)[source]
height
insert_col(xpos=None, count=1)[source]
insert_row(ypos=None, count=1)[source]
isempty(y1, x1, y2, x2)[source]
key_iterator()[source]
keyiter(ykey, xkey, debug=False)[source]
keys
lastcol
lastrow
move_area()[source]
next_nonempty_down(ykey, xkey)[source]
next_nonempty_right(ykey, xkey)[source]
notempty(y1, x1, y2, x2)[source]
print_row(y)[source]
purge()[source]

Remove rows and columns that are empty.

raise_indexerror(y, x)[source]
range_check(y, x, throw=True)[source]
remove_col(xpos, count=1)[source]
remove_row(ypos, count=1)[source]
resize(yndx, xndx, pr=False)[source]

Resize so that self[yndx,xndx] is valid.

reverse_key_iterator()[source]
reversed
rows
set_cell(y, x, v)[source]
size
transpose()[source]
value_iterator()[source]
values
width
dk.grid.indexiter(length, ndx)[source]
class dk.grid.point[source]

Bases: tuple

x
y
dk.grid.point_xiter(start, end)[source]
dk.grid.point_yiter(start, end)[source]
class dk.grid.rect(x, y, w, h)[source]

Bases: object

NE
NW
SE
SW
corners
isomorphic(other)[source]

Same shape?

opposite(corner)[source]
x
x2
y
y2
class dk.grid.table_iterator(iterfn)[source]

Bases: object

class dk.grid.value_iterator(gridobj, ykey, xkey)[source]

Bases: object

indices(direction='RD')[source]
iter(direction='RD')[source]
ndx_base(direction='RD')[source]
rect()[source]

dk.iplist module

Collections of distinct ip-addresses.

class dk.iplist.IPList(iterable=())[source]

Bases: object

List (well, actually more of a set) of ip-addresses (well, actually using subnets...).

add(ipaddy)[source]

Add ipaddy to self.

network()[source]

Return the list of networks that cover our list of ip-addys.

pack()[source]

Convert to compressed, but db friendly, notation. This fits ~124 ip addys into 250 bytes, if they are sufficiently contigous.

unpack(b64val)[source]

Reverse steps in pack().

dk.proxy module

Proxy class that forwards __special__ methods too.

class dk.proxy.proxy(obj)[source]

Bases: object

Proxy class that forwards __special__ methods too.

dk.text module

dk.text.u(obj)

Return obj as a unicode string. If obj is a (non-)unicode string, then first try to decode it as utf-8, then as iso-8859-1.

dk.text.u8(obj)

Return a utf-8 representation of obj.

dk.text.unicode_repr(obj)[source]

Return obj as a unicode string. If obj is a (non-)unicode string, then first try to decode it as utf-8, then as iso-8859-1.

dk.text.utf8(obj)[source]

Return a utf-8 representation of obj.

dk.utidy module

Micro tidy.

Usage:

>>> print utidy('''
... <form name="FirmaForm" id="FirmaForm" method="POST" autocomplete="off"
... action="." class="fForm"><input type="hidden" name="__cmd"
... value="FirmaForm"></form>hello
... ''')
...
<form action="." autocomplete="off" class="fForm" id="FirmaForm" method="POST" name="FirmaForm">
    <input name="__cmd" type="hidden" value="FirmaForm">
</form>>
hello
class dk.utidy.HtmlTag(txt)[source]

Bases: object

attre = <_sre.SRE_Pattern object>
normalize_attrs(attrs)[source]
normalize_class(val)[source]
normalize_style(val)[source]
dk.utidy.simplify_simple_tags(html)[source]

Put tags without any nested children on one line, i.e. turn:

<h1>
    foo
</h1>

into:

<h1>foo</h1>
dk.utidy.tokenize_html(html)[source]
dk.utidy.utidy(html, level=0, indent=' ', simplify=False)[source]

micro-tidy

Normalizes the html.

dk.utils module

FIXME: many of these really should go in their own modules...

dk.utils.HourMinute(v)[source]

Format 7.10 as 7t 06m.

class dk.utils.Ordered[source]

Bases: dict

Mapping that maintains insertion order. (Should be removed and the adt versions should be used).

items()[source]
keys()[source]
values()[source]
dk.utils.dkpath(pth=None)[source]

Usage

dkpath() => (w:)/xxxxxxx/
         => (/home)/xxxxxxxx/

dkpath('app/') => ../xxxxxxxx/app/
dk.utils.hm_to_float(h, m)[source]

Convert 7, 30 to 7.5 hours.

dk.utils.hour_minute(v)[source]

Convert 7.5 (hours) to (7, 30) i.e. 7 hours and 30 minutes.

dk.utils.html2u8(s)[source]

Convert charrefs for Norwegian vowels to their utf-8 counterparts.

dk.utils.identity(x)[source]

Return the argument unchanged. This function is often called identity in programming language and type theory (the type is t -> t, which turns out to be a difficult type for most classical static type systems).

dk.utils.kr_ore(n)[source]

Convert the øre-value n to a proper NOK string value.

dk.utils.kronestring(kr)[source]

Return a string version of the integer value kr, with space as the thousand-separator.

dk.utils.latin1(obj)[source]

Return a latin-1 representation of obj.

dk.utils.lower_case(s, encoding='u8')[source]

Return a lower cased (byte-)string version of s encoded in encoding.

dk.utils.mk_post(model)[source]

Encode model (a dict-like object) into a dict where:

  • all values are strings
  • None values are removed
  • date values are expanded into year/month/day parts
Note:: this function is superceeded by maint.client._encode_date
which does this transparently for unit tests.
dk.utils.nlat(v)[source]

Normalize and recover from utf-8 stored in varchar columns.

dk.utils.normalize(v)[source]

Return a string version of v such that

normalize(u) == normalize(v) iff not (u != v)

e.g.:

normalize(None) == normalize(‘’) == normalize(u’‘)
dk.utils.orestring(n)[source]

Return a string version of the integer øre value. Either a two-digit string or a dash (as in 5,-).

dk.utils.root()[source]

Return the root of the source tree.

dk.utils.single_line(txt)[source]

Remove multiple spaces and newlines.

dk.utils.srcpath(base, pth)[source]

Return an absolute path based on the relative path pth. Useful in tests, where we don’t know what the absolute path is, and we can’t use relative paths since we don’t know which folder the tests are run from.

In a test file xxxxxxx/foo/test/test_foo.py:

path = 'foo/test'
fp = open(srcpath(path, 'data/testdata.txt'))
dk.utils.title_case(s, encoding='u8')[source]

Return a title cased (byte-)string version of s encoded in encoding.

dk.utils.title_case_lastname(s, encoding='u8')[source]

Return a title cased version of s encoded in encoding. If it looks like s is already title cased, then leave it alone (in case of manual override and complex capitalization rules for last names).

dk.utils.u(obj)

Return obj as a unicode string. If obj is a (non-)unicode string, then first try to decode it as utf-8, then as iso-8859-1.

dk.utils.u8(obj)

Return a utf-8 representation of obj.

dk.utils.ulower_case(val)[source]

Call val.lower(). Return ‘’ if val is None.

dk.utils.unhtml(s, toencoding=None)[source]

Convert charrefs for Norwegian vowels to their unicode counterparts.

dk.utils.unicode_repr(obj)[source]

Return obj as a unicode string. If obj is a (non-)unicode string, then first try to decode it as utf-8, then as iso-8859-1.

dk.utils.utf8(obj)[source]

Return a utf-8 representation of obj.

dk.utils.utitle_case(val)[source]

(safer) val.title() implementation.

dk.utils.utitle_case_lastname(s)[source]

Return a title cased version of s. If s contains a recognized special case, then return it unchanged.

Module contents

Indices and tables