astro.services.imageview package

Submodules

astro.services.imageview.DependencyCutout module

astro.services.imageview.HTMLcolordict module

HTMLcolordict = HTMLcolorsLight = {
‘LightBlue’: ‘#add8e6’, ‘LightCoral’: ‘#f08080’, ‘LightCyan’: ‘#e0ffff’, ‘LightGoldenrodYellow’: ‘#fafad2’, ‘LightGreen’: ‘#90ee90’, ‘LightGrey’: ‘#d3d3d3’, ‘LightPink’: ‘#ffb6c1’, ‘LightSalmon’: ‘#ffa07a’, ‘LightSeaGreen’: ‘#20b2aa’, ‘LightSkyBlue’: ‘#87cefa’, ‘LightSlateGray’: ‘#778899’, ‘LightSteelBlue’: ‘#b0c4de’, ‘LightYellow’: ‘#ffffe0’}

HTMLcolordictlist = list(HTMLcolordict.keys())

astro.services.imageview.HTMLgen module

A class library for the generation of HTML documents.

Each HTML tag type has a supporting class which is responsible for emitting itself as valid HTML formatted text. An attempt is made to provide classes for newer HTML 3.2 and proposed tag elements. The definitive reference for HTML tag elements can be found at [W3C]. Also, I used the HTML book by Musciano and Kennedy from [O Reilly] (2nd. Ed.) as the guiding reference.

The Document classes are container objects which act as a focal point to populate all the contents of a particular web page. It also can enforce consistent document formating according to the guidelines from the [Yale Web Style Manual].

Features include customization of document template graphics / colors through use of resource files, minimizing the need for modifying or subclassing from the module source code. Support for tables, frames, forms (persistent and otherwise) and client-side imagemaps are included.

A newer implementation for the Table support is now included, TableLite(). In support of this there are new tag classes TD, TH, TR and Caption. These class instances can be assembled in any way to populate the TableLite container object.

[W3C]http://www.W3.org/TR/REC-html32.html
astro.services.imageview.HTMLgen.A

alias of Href

class astro.services.imageview.HTMLgen.AbstractTag(*contents, **kw)

Bases: object

Abstract base class for all tag markup classes requiring a closure tag.

append(*items)

Append one or more items to the end of the container.

attr_dict = {}
attr_template = ''
attrs = ()
copy()

Return a full copy of the object.

empty()

Empty the contents of the container.

html_escape = 'ON'
last()

Return a reference to the last item in the container.

markup(rex=None, marker=None, **kw)

Markup the contained text matching a regular expression with a tag class instance or function.

Arguments

rex – a regular expression object or pattern which will be used
to match all text patterns in the Paragraph body. Must have a single group defined. Group 1 is the matching text that will be marked. Default to all parenthetical text.
marker – an HTMLgen class instance to which the found text will
be sent for wrapping (using its __call__ method). Default is Emphasis.

Keywords

collapse – When set to 1 removes the non-grouped matching text
from the output. Default 0.

Returns the number of matching text groups.

prepend(*items)

Prepend one or more items to the top of the container.

tagname = ''
trailer = '\n'
class astro.services.imageview.HTMLgen.AbstractTagSingle(*args, **kw)

Bases: object

Abstract base class for all tag markup classes not requiring a closure tag.

attr_dict = {}
attr_template = ''
attrs = ()
tagname = ''
class astro.services.imageview.HTMLgen.Address(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

A mailing address. Not a URL.

attr_dict = {'style': '', 'id': '', 'class': ''}
attr_template = '%(class)s%(id)s%(style)s'
attrs = ('class', 'id', 'style')
tagname = 'ADDRESS'
trailer = ''
class astro.services.imageview.HTMLgen.Area(*args, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTagSingle

Specify a click-sensitive area of an image.

The area is linked to a HREF specified by the href attribute. The coords attribute is required and describes the position of an area (in pixels) of the image in comma-separated x,y coordinates where the upper-left corner is “0,0”. For shape=’rect’ (the default), it is “left,top,right,bottom”. For shape=’circle’, it is “center_x,center_y,radius”. For shape=’polygon’, it is successive x,y vertices of the polygon. If the first and last coordinates are not the same, then a segment is inferred to close the polygon. If no href keyword is given a NOHREF will be generated indicating that this region should generate no links.

Keyword Arguments

href – Typically a reference to an image coords – string holding a list of coordinates defining shape – ‘rect’|’circle’|’polygon’
attr_dict = {'alt': '', 'coords': '', 'shape': '', 'onmouseover': '', 'onmouseout': '', 'id': '', 'target': '', 'name': '', 'class': '', 'href': ' nohref'}
attr_template = '%(alt)s%(class)s%(coords)s%(href)s%(id)s%(name)s%(onmouseout)s%(onmouseover)s%(shape)s%(target)s'
attrs = ('alt', 'class', 'coords', 'href', 'id', 'name', 'onmouseout', 'onmouseover', 'shape', 'target')
tagname = 'AREA'
class astro.services.imageview.HTMLgen.AutoStringTemplate(template, substitutions=None, **kw)

Bases: astro.services.imageview.HTMLgen.StringTemplate

R = re.compile('<!--{(?P<key>[\\w_]+)}Begin-->(?P<text>.*?)<!--{\\1}End-->', re.DOTALL)
extract_template(source=None)

Convert comment-marked regions to a regular {tokens}.

Updates the substitution dictionary with the text from the region.

marker_begin = '<!--{%s}Begin-->'
marker_end = '<!--{%s}End-->'
set_template(template)

Set template string and normalize by extracting comment tokens.

class astro.services.imageview.HTMLgen.AutoTemplateDocument(template, substitutions=None, **kw)

Bases: astro.services.imageview.HTMLgen.AutoStringTemplate

Generate documents based on a template and a substitution mapping.

The primary difference between AutoTemplateDocument and TemplateDocument is that the Auto version can read through an HTML file previously generated with this class and identify the regions of text that were substituted. It then extracts that text into the substitution dictionary and can then be updated. The intent is to eliminate the need to maintain separate content files for insertion into templates. The HTML output file can double as a template for future use. Output from this class have their filled regions marked by comments:

...gets <!–{wz}Begin–>glued,<!–{wz}End–> in place...

Which came from ...gets {wz} in place... in old style template syntax.

AutoTemplateDocument is a functional superset of TemplateDocument and should be compatible.

Usage:
T = AutoTemplateDocument(‘Maine.html’) T.substitutions = {‘month’: ObjectY, ‘town’: ‘Scarborough’} or T[‘month’] = ObjectY ; T[‘town’] = ‘Scarborough’ T.write(‘Maine.html’)

A dictionary, or object that behaves like a dictionary, is assigned to the substitutions attribute which has symbols as keys to objects. Upon every occurance of these symbols surrounded by braces {} in the source template, the corresponding value is converted to a string and substituted in the output.

For example, source text which looks like:
I lost my heart at {town} Fair.
becomes:
I lost my heart at Scarborough Fair.

Symbols in braces which do not correspond to a key in the dictionary remain unchanged.

An optional third argument to the class is a list or two strings to be used as the delimiters instead of { } braces. They must be of the same length; for example [‘##+’, ‘##’] is invalid.

set_template(template)
class astro.services.imageview.HTMLgen.BR(*args, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTagSingle

Break tag. Argument is an integer integer multiplier. BR(2)==’<BR><BR>’

attr_dict = {'clear': ''}
attr_template = '%(clear)s'
attrs = ('clear',)
tagname = 'BR'
class astro.services.imageview.HTMLgen.Base(*args, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTagSingle

Specify the base URL for all relative URLs in this document.

One string argument required. It must be a complete file name, and is usually the original URL of this document. If this file is moved, having the BASE set to the original URL eliminates the need to also move all the documents which are identified by relative URL links in this document.

attr_dict = {'target': '', 'href': ''}
attr_template = '%(href)s%(target)s'
attrs = ('href', 'target')
tagname = 'BASE'
class astro.services.imageview.HTMLgen.BaseFont(*args, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTagSingle

Specify the font size for subsequent text.

attr_dict = {'color': '', 'name': '', 'size': ''}
attr_template = '%(color)s%(name)s%(size)s'
attrs = ('color', 'name', 'size')
tagname = 'BASEFONT'
class astro.services.imageview.HTMLgen.BasicDocument(*args, **kw)

Bases: object

Base class to define an HTML document.

Non-keyword arguments are taken as the initial contents for this object.

Keyword arguments:
title – HTML TITLE attribute for document bgcolor – background color expressed in hex-triplet or names from HTMLcolors. background – background image filename cgi – flag to indicate if this is used in CGI context (1 if it is) textcolor – color to use for normal text linkcolor – color to use for hyperlinks vlinkcolor – color to use for visited hyperlinks alinkcolor – color to use when hyperlink is active
alinkcolor = None
append(*items)

Add content to the Document object.

Arg items can be plain text or objects; multiple arguments supported.

append_file(filename, marker_function=None)

Add the contents of a file to the document.

filename – the filename of the file to be read [string] marker_function – a callable object which the text read from

the file will be passed through before being added to the document.
background = None
bgcolor = None
cgi = None
copy()

Return a complete copy of the current Document object.

html_body_tag()

Return BODY tag with attributes.

html_head()

Generate the HEAD, TITLE and BODY tags.

linkcolor = None
prepend(*items)

Add content to the beginning of the Document object.

Arg items can be plain text or objects; multiple arguments supported.

textcolor = None
title = ''
vlinkcolor = None
write(filename=None)

Emit the Document HTML to a file or standard output.

In Unix you can use environment variables in filenames. Will print to stdout if no argument.

class astro.services.imageview.HTMLgen.Big(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Format text in a bigger font.

attr_dict = {'style': '', 'id': '', 'class': ''}
attr_template = '%(class)s%(id)s%(style)s'
attrs = ('class', 'id', 'style')
tagname = 'BIG'
trailer = ''
class astro.services.imageview.HTMLgen.Blockquote(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Indent text as a block quotation.

attr_dict = {'style': '', 'id': '', 'class': ''}
attr_template = '%(class)s%(id)s%(style)s'
attrs = ('class', 'id', 'style')
tagname = 'BLOCKQUOTE'
astro.services.imageview.HTMLgen.Bold

alias of Strong

astro.services.imageview.HTMLgen.BulletList

alias of List

class astro.services.imageview.HTMLgen.Caption(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Define a caption for a table.

attr_dict = {'style': '', 'align': '', 'id': '', 'valign': '', 'class': ''}
attr_template = '%(class)s%(id)s%(style)s%(align)s%(valign)s'
attrs = ('class', 'id', 'style', 'align', 'valign')
tagname = 'CAPTION'
class astro.services.imageview.HTMLgen.Center(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Center the text.

attr_dict = {}
attr_template = ''
attrs = ()
tagname = 'center'
class astro.services.imageview.HTMLgen.Cite(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

A citation.

attr_dict = {'style': '', 'id': '', 'class': ''}
attr_template = '%(class)s%(id)s%(style)s'
attrs = ('class', 'id', 'style')
tagname = 'CITE'
trailer = ''
class astro.services.imageview.HTMLgen.Code(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Code sample. Escaping of special characters is not performed.

To enable escaping set html_escape=’ON’.

attr_dict = {'style': '', 'id': '', 'class': ''}
attr_template = '%(class)s%(id)s%(style)s'
attrs = ('class', 'id', 'style')
html_escape = 'OFF'
tagname = 'CODE'
class astro.services.imageview.HTMLgen.Comment(text='')

Bases: object

Place a comment internal to the HTML document.

Will not be visible from the browser.

class astro.services.imageview.HTMLgen.Container(*args, **kw)

Bases: object

A holder for a list of HTMLgen objects.

append(*items)

Add content to the Document object.

Arg items can be plain text or objects; multiple arguments supported.

append_file(filename, marker_function=None)

Add the contents of a file to the document.

filename – the filename of the file to be read [string] marker_function – a callable object which the text read from

the file will be passed through before being added to the document.
copy()

Return a complete copy of the current Container object.

prepend(*items)

Add content to the beginning of the Document object.

Arg items can be plain text or objects; multiple arguments supported.

astro.services.imageview.HTMLgen.DL

alias of DefinitionList

class astro.services.imageview.HTMLgen.Define(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Format as definition text.

attr_dict = {'style': '', 'id': '', 'class': ''}
attr_template = '%(class)s%(id)s%(style)s'
attrs = ('class', 'id', 'style')
tagname = 'DFN'
class astro.services.imageview.HTMLgen.DefinitionList(list=None, **kw)

Bases: astro.services.imageview.HTMLgen.List

Show a series of items and item definitions.

Arg is a list of tuple pairs: [(string/object,string/object),(,)...] 1st item in each pair is the word to be defined. It will be rendered in bold. 2nd is the string which will be indented to it’s next-line-right. If the compact flag is set to non-empty, the definition side will be placed on the same line. Example

DefinitionList([( 4 , ‘Number after 3’) , ( 1 , ‘Unity’)] ) will emit: 4

Number after 3
1
Unity
attrs = ('class', 'id', 'style')
flags = ('compact',)
render_list_item(item)

Overload method to perform DT/DD markup.

tagname = 'DL'
class astro.services.imageview.HTMLgen.Div(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Specify a division within a document.

attr_dict = {'align': '', 'id': '', 'nowrap': '', 'style': '', 'lang': '', 'class': ''}
attr_template = '%(class)s%(id)s%(style)s%(align)s%(lang)s%(nowrap)s'
attrs = ('class', 'id', 'style', 'align', 'lang', 'nowrap')
tagname = 'DIV'
astro.services.imageview.HTMLgen.Document

alias of SeriesDocument

astro.services.imageview.HTMLgen.EM

alias of Emphasis

class astro.services.imageview.HTMLgen.Embed(*args, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTagSingle

Embed an application in this document.

attr_dict = {'vspace': '', 'hspace': '', 'src': '', 'hidden': '', 'units': '', 'border': '', 'align': '', 'type': '', 'palette': '', 'height': '', 'pluginspage': '', 'width': '', 'name': ''}
attr_template = '%(align)s%(border)s%(height)s%(hidden)s%(hspace)s%(name)s%(palette)s%(pluginspage)s%(src)s%(type)s%(units)s%(vspace)s%(width)s'
attrs = ('align', 'border', 'height', 'hidden', 'hspace', 'name', 'palette', 'pluginspage', 'src', 'type', 'units', 'vspace', 'width')
tagname = 'EMBED'
class astro.services.imageview.HTMLgen.Emphasis(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Format with additional emphasis. (usually italics)

attr_dict = {'style': '', 'id': '', 'class': ''}
attr_template = '%(class)s%(id)s%(style)s'
attrs = ('class', 'id', 'style')
tagname = 'EM'
trailer = ''
class astro.services.imageview.HTMLgen.Font(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Set the size or color of the text.

attr_dict = {'color': '', 'face': '', 'size': ''}
attr_template = '%(color)s%(face)s%(size)s'
attrs = ('color', 'face', 'size')
tagname = 'FONT'
trailer = ''
class astro.services.imageview.HTMLgen.Form(cgi=None, **kw)

Bases: object

Define a user filled form. Uses POST method. MT 2004: GET instead of POST

cgi is the URL to the CGI processing program. Input objects (any others as well) are appended to this container widget.

Keywords

name – name of the form submit – The Input object to be used as the submit button.

If none specified a Submit button will automatically be appended to the form. Do not manually append your submit button. HTMLgen will append it for you.

reset – Input object to be used as a reset button. target – set a TARGET attribute enctype – specify an Encoding type. onSubmit – script, which is executed, when the form is submitted

append(*items)

Append any number of items to the form container.

class astro.services.imageview.HTMLgen.Frame(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Define the characteristics of an individual frame.

Keywords Arguments

src – is a HREF which points to the initial contents of the frame. name – is the window name used by others to direct content into this frame. marginwidth – is the number of pixels used to pad the left and right

sides of the frame.
marginheight – is the number of pixels used to pad the top and bottom
sides of the frame.

scrolling – is used to indicate scrolling policy set to ‘yes’|’no’|’auto’ noresize – is a flag which instructs the browser to disallow frame resizing.

set to non zero lock size ( noresize=1 ).
attr_dict = {'bordercolor': '', 'marginheight': '', 'align': '', 'frameborder': '', 'src': '', 'scrolling': '', 'noresize': '', 'name': '', 'marginwidth': ''}
attr_template = '%(align)s%(bordercolor)s%(frameborder)s%(marginheight)s%(marginwidth)s%(name)s%(noresize)s%(scrolling)s%(src)s'
attrs = ('align', 'bordercolor', 'frameborder', 'marginheight', 'marginwidth', 'name', 'noresize', 'scrolling', 'src')
tagname = 'FRAME'
class astro.services.imageview.HTMLgen.Frameset(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Define a Frameset to contain Frames or more Framesets

attr_dict = {'bordercolor': '', 'framespacing': '', 'onblur': '', 'frameborder': '', 'rows': '', 'border': '', 'onload': '', 'onunload': '', 'onfocus': '', 'cols': ''}
attr_template = '%(border)s%(bordercolor)s%(cols)s%(frameborder)s%(framespacing)s%(onblur)s%(onfocus)s%(onload)s%(onunload)s%(rows)s'
attrs = ('border', 'bordercolor', 'cols', 'frameborder', 'framespacing', 'onblur', 'onfocus', 'onload', 'onunload', 'rows')
tagname = 'FRAMESET'
class astro.services.imageview.HTMLgen.FramesetDocument(*args, **kw)

Bases: astro.services.imageview.HTMLgen.BasicDocument

A minimal document suitable for entering Framesets.

Arguments are for contents NOT a document resource file.

Keyword Parameters

title – string to be used as the document title. base – object of the Base class meta – object of the Meta class cgi – if non zero will issue a mime type of text/html script – a single or list of Script objects to be included in the <HEAD>

No <body> markup. Instead add Frameset(s) with the constructor or append method.

base = None
cgi = None
meta = None
script = None
astro.services.imageview.HTMLgen.H

alias of Heading

class astro.services.imageview.HTMLgen.HR(*args, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTagSingle

Break the current text flow and insert a horizontal rule.

attr_dict = {'color': '', 'align': '', 'class': '', 'style': '', 'id': '', 'width': '', 'noshade': '', 'size': ''}
attr_template = '%(align)s%(class)s%(id)s%(color)s%(noshade)s%(size)s%(style)s%(width)s'
attrs = ('align', 'class', 'id', 'color', 'noshade', 'size', 'style', 'width')
tagname = 'HR'
astro.services.imageview.HTMLgen.HREF

alias of Href

astro.services.imageview.HTMLgen.Head

alias of Heading

astro.services.imageview.HTMLgen.Header

alias of Heading

class astro.services.imageview.HTMLgen.Heading(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Heading markups for H1 - H6

Heading(level, text, **kw)

The level arg is an integer for the level of the heading. Valid levels are 1-6. The text arg is a string (or any object) for the text of the heading. Keyword arguments are align, Class, and style.

For example: h = Heading(2, ‘Chapter 3’, align=’center’)

attr_dict = {'style': '', 'align': '', 'id': '', 'class': ''}
attr_template = '%(class)s%(id)s%(style)s%(align)s'
attrs = ('class', 'id', 'style', 'align')
tagname = ''
class astro.services.imageview.HTMLgen.Href(url='', text='', **kw)

Bases: object

Generate a hyperlink.

Argument 1 is the URL and argument 2 is the hyperlink text.

Keyword arguments

target – is an optional target symbol onClick – is the script-code which is executed when link is clicked. onMouseOver – the script-code which is executed when the mouse

moves over the link.
onMouseOut – the script-code which is executed when the mouse
moves off the link.
append(content)
astro.services.imageview.HTMLgen.IMG

alias of Image

class astro.services.imageview.HTMLgen.Image(*args, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTagSingle

Inlined Image

The filename argument is a filename, or URL of a graphic image, or a triple of ( filename, width, height ) where dimensions are in pixels. Where the filename is found to be a valid pathname to an existing graphic file that file will be read to determine its width and height properties. GIF, JPEG, and PNG files are understood.

Keyword Arguments

width – (int) Width in pixels height – (int) Height in pixels border – (int) Border width in pixels align – (string) ‘top’|’middle’|’bottom’|’right’|’left’ alt – (string) Text to substitute for the image in nonGUI browsers usemap – Imagemap name or Map object ismap – Flag (1|0) indicating if a server side imagemap is available. absolute – Absolute path to the directory containing the image prefix – Relative path or URL to directory containing the image hspace – Number of pixels to be added to the left and right of the image. vspace – Number of pixels to be added to the top and bottom of the image. name – A name for this image to be used by JavaScript Class – A CSS class this tag belongs to. style – A CSS inline style specification.
attr_dict = {'alt': '', 'usemap': '', 'hspace': '', 'vspace': '', 'border': '', 'lowsrc': '', 'src': '', 'ismap': '', 'align': '', 'style': '', 'height': '', 'id': '', 'width': '', 'name': '', 'class': ''}
attr_template = '%(src)s%(height)s%(width)s%(alt)s%(border)s%(align)s%(class)s%(id)s%(hspace)s%(vspace)s%(lowsrc)s%(name)s%(style)s%(usemap)s%(ismap)s'
attrs = ('src', 'height', 'width', 'alt', 'border', 'align', 'class', 'id', 'hspace', 'vspace', 'lowsrc', 'name', 'style', 'usemap', 'ismap')
calc_rel_path(from_dir=None)

Calculate the relative path from ‘from_dir’ to the absolute location of the image file.

Sets self.prefix.

process_arg(arg)
tagname = 'IMG'
class astro.services.imageview.HTMLgen.ImageBulletList(list=None, **kw)

Bases: astro.services.imageview.HTMLgen.List

Show a list of images with adjoining text(or object).

Arg is a list of tuple pairs: [(Image_obj, string/object),(,)...] Generates an inlined image then the text followed by a <BR> for each element.

attrs = ()
flags = ()
render_list_item(item)

Overload method to take first item from an item tuple and setting it next to the second item, using BR to separate list items.

tagname = 'UL'
astro.services.imageview.HTMLgen.Indent

alias of Blockquote

class astro.services.imageview.HTMLgen.InitialCaps(text='', upsize='+2', downsize='+1')

Bases: object

Utility class to process text into Initial Upper Case style using Font specifications. All text is converted to upper case and the initial characters are altered by the size given by the optional second argument. The rest of the characters are altered by the size given in the optional third argument.

For example:

InitialCaps(‘We the people’, ‘+3’, ‘+1’)
class astro.services.imageview.HTMLgen.Input(**kw)

Bases: object

General Form Input tags.

Keyword Arguments

type – ‘TEXT’ (default) Supported types include password, checkbox,
radio, file, submit, reset, hidden.

name – provides the datum name value – the initial value of the input item checked – flag indicating if the item is checked initially size – size of the widget (e.g. size=10 for a text widget is it’s width) maxlength – maximum number of characters accepted by the textfield. border – border width in pixels for an image type. align – top|middle|bottom align w.r.t. adjoining text for image types. llabel – an optional string set to the left of the widget rlabel – an optional string set to the right of the widget onBlur – script, which is executed, when the field loses focus,

useful for the text-type
onChange – script, which is executed, when the field value changed,
useful for the text-type
onClick – script, which is executed, when the field in clicked,
useful for the button, checkbox, radio, submit, reset type
onFocus – script, which is executed, when the field receives focus,
useful for the text-type
onSelect – script, which is executed, when part of the field
is selected, useful for the text-type
re_type = re.compile('text|password|checkbox|radio|image|button|file|submit|reset|hidden', re.IGNORECASE)
astro.services.imageview.HTMLgen.Italic

alias of Emphasis

class astro.services.imageview.HTMLgen.KBD(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Keyboard-like input.

attr_dict = {'style': '', 'id': '', 'class': ''}
attr_template = '%(class)s%(id)s%(style)s'
attrs = ('class', 'id', 'style')
html_escape = 'OFF'
tagname = 'KBD'
class astro.services.imageview.HTMLgen.List(list=None, **kw)

Bases: collections.UserList

Will generate a bulleted list given a list argument.

Now supports rendering a list into multiple columns by setting the columns attribute to a number greater than one. This is implemented using tables and you can also set a background color for the list itself by using the bgcolor attribute.

Supports nested lists, i.e. lists of lists. Each time a list is encountered in a list it will indent those contents w.r.t. the prior list entry. This can continue indefinitely through nested lists although there are only three different bullets provided by the browser (typically).

Optional keyword indent can be used to indicate whether you want the list to start left justified or indented. indent=0 will make it left justified. The default is to indent.

Optional keyword type can be set to either disk, circle, or square to specify what kind of symbol is used for each list item’s bullet. (Netscape extension)

Since we inherit from the UserList class any normal list operations work on instances of this class. Any list contents will do. Each of the items will be emitted in html if they are themselves objects from this module. Aliases: UL, BulletList

I_am_a_list = 1
append(*items)

Append entries to the end of the list

attrs = ('type', 'align', 'class', 'id', 'style')
bgcolor = ''
column_slices(columns=1)

Calculate a list of index pairs bounding column slices.

columns = 1
end_element()

Closes the HTML element

flags = ('compact',)
indent = 1
multi_column_table()

Return a table containing the list sliced into columns.

pad = ' '
render_list_item(item)

Renders the individual list items

Overloaded by child classes to represent other list styles.

start_element()

Generic creator for the HTML element opening tag.

Reads tagname, attrs and flags to return appropriate tag.

sub_list(list)

Recursive method for generating a subordinate list

tagname = 'UL'
astro.services.imageview.HTMLgen.MAILTO

alias of MailTo

class astro.services.imageview.HTMLgen.MailTo(address='', text=None, subject=None)

Bases: object

A Mailto href

First argument is an email address, optional second argument is the text shown as the underlined hyperlink. Default is the email address. Optional third argument is a Subject: for the email.

antispam(address)

Process a string with HTML encodings to defeat address spiders.

astro.services.imageview.HTMLgen.Mailto

alias of MailTo

class astro.services.imageview.HTMLgen.Map(areas=None, **kw)

Bases: object

Used to name and describe a client-side image map.

The areas argument is a list of Area objects. Keyword arg is supported for name, which defines the map name to be used with the usemap attribute of an Image class instance.

class astro.services.imageview.HTMLgen.Meta(**kw)

Bases: object

Set document Meta-information.

The META element is used within the HEAD element to embed document meta-information not defined by other HTML elements.

Keywords supported

name – NAME element attribute (default: ‘keywords’) equiv – will map to the HTTP-EQUIV attribute content – mandatory attribute (default: ‘python,HTMLgen’) url – URL naturally

Example:

Meta( name=’keywords’, content=’eggs,spam,beans’ )
astro.services.imageview.HTMLgen.MinimalDocument

alias of SimpleDocument

astro.services.imageview.HTMLgen.NAME

alias of Name

class astro.services.imageview.HTMLgen.Name(url='', text='', **kw)

Bases: astro.services.imageview.HTMLgen.Href

Generate a named anchor.

Arg url is a string or URL object, Arg text is optional string or object to be highlighted as the anchor.

class astro.services.imageview.HTMLgen.NoFrames(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Issue a message on browsers that don’t support frames

attr_dict = {}
attr_template = ''
attrs = ()
tagname = 'NOFRAMES'
class astro.services.imageview.HTMLgen.Nobr(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Specify non-breaking text.

attr_dict = {}
attr_template = ''
attrs = ()
tagname = 'NOBR'
trailer = ''
class astro.services.imageview.HTMLgen.NonBulletList(list=None, **kw)

Bases: astro.services.imageview.HTMLgen.List

Generate a raw indented list without bullet symbols.

Arg is a list of python objects:

attrs = ()
flags = ()
render_list_item(item)

Overload method to take first item from an item tuple and setting it next to the second item, using BR to separate list items.

tagname = 'UL'
astro.services.imageview.HTMLgen.NumberedList

alias of OrderedList

astro.services.imageview.HTMLgen.OL

alias of OrderedList

class astro.services.imageview.HTMLgen.OrderedList(list=None, **kw)

Bases: astro.services.imageview.HTMLgen.List

Will generate a numbered list given a list arg.

Optional keyword type can be used to specify whether you want the list items marked with: capital letters (type=’A’), small letters (type=’a’), large Roman numerals (type=’I’), small Roman numerals (type=’i’). The default is arabic numbers. The other types are HTML3.2 only and may not be supported by browsers yet. Any list contents will do. Each of the items will be emitted in HTML if they are themselves objects.

attrs = ('type', 'class', 'id', 'style')
tagname = 'OL'
class astro.services.imageview.HTMLgen.P

Bases: object

Just echo a <P> tag.

astro.services.imageview.HTMLgen.PRE

alias of Pre

astro.services.imageview.HTMLgen.Para

alias of Paragraph

class astro.services.imageview.HTMLgen.Paragraph(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Define a Paragraph.

Takes a single string/object argument and the optional keyword argument ‘align’ which may be one of (left, right, center). As always, Class and style keywords are supported. Not to be confused with class P. That is just for inserting a para break.

Example:

Paragraph(‘Some text to center’, align=’center’)
attr_dict = {'style': '', 'align': '', 'id': '', 'class': ''}
attr_template = '%(class)s%(id)s%(style)s%(align)s'
attrs = ('class', 'id', 'style', 'align')
tagname = 'P'
class astro.services.imageview.HTMLgen.Pre(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Render the text verbatim honoring line breaks and spacing.

Does not escape special characters. To override this set html_escape to ‘ON’.

attr_dict = {'width': ''}
attr_template = '%(width)s'
attrs = ('width',)
html_escape = 'OFF'
tagname = 'PRE'
class astro.services.imageview.HTMLgen.RawText(text='')

Bases: object

Class to encapsulate raw text. Does NOT escape special characters.

append(text)
astro.services.imageview.HTMLgen.STRONG

alias of Strong

class astro.services.imageview.HTMLgen.Sample(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Sample text. Escaping of special characters is not performed.

To enable escaping set html_escape=’ON’.

attr_dict = {'style': '', 'id': '', 'class': ''}
attr_template = '%(class)s%(id)s%(style)s'
attrs = ('class', 'id', 'style')
html_escape = 'OFF'
tagname = 'SAMP'
class astro.services.imageview.HTMLgen.Script(**kw)

Bases: object

Construct a Script

Keyword Arguments

Defaults in (parenthesis). Keyword parameters may be set as attributes of the instantiated script object as well.

language – specifies the language (‘JavaScript’) src – specifies the location code – script code, which is printed in comments, to hide it from non

java-script browsers
append(s)
class astro.services.imageview.HTMLgen.Select(data=None, **kw)

Bases: collections.UserList

Used to define a list widget or option widget.

Pass a list of strings to show a list with those values. Alternatively can pass a list of tuple pairs. Each pair contains the displayed string and it’s associatated value mapping. If no value mapping is needed just use something that evaluates to None.

Keyword Arguments:

name – provides the datum name size – the visual size. 1 means use an option popup widget.

>=2 means use a list widget with that many lines.

multiple – flag to indicate whether multiple selections are supported. selected – list of values to be shown as pre-selected. onBlur – script, which is executed, when the field loses focus onChange – script, which is executed, when the field value changed onFocus – script, which is executed, when the field receives focus

class astro.services.imageview.HTMLgen.SeriesDocument(resource=None, **kw)

Bases: astro.services.imageview.HTMLgen.SimpleDocument

Primary container class for an HTML document as part of a series.

Formerly known as Document().

Navigation mechanisms are provided.

Single optional string argument for the path to a resource file used to specify document parameters. This helps minimize the need for subclassing from this class. Keyword parameters may be used for any of the following class attributes. See HTMLtest.py for example usage.

Class instance attributes and keyword arguments

base – object of the Base class meta – object of the Meta class cgi – if non zero will issue a mime type of text/html logo – (‘filename’, width, height) All images are specified

with a tuple of string, int, int. If the size of the graphic is unknown, use 0, 0. This one is the little graphic on the footer of each page.
banner – (‘filename’, width, height) Banner graphic at
the top of page. Can also be set to a string filename or an Image object. Can be autosized if it’s a GIF.

title – string to be used as the document title. subtitle – string to be used as the document subtitle.

If non-nil, this string will be used for the doc title instead of title.

author – String used in the copyright notice email – Email address for feedback mailto: tag zone – string used to label the time zone if datetime

is used. By default not used.
bgcolor – Color string (can use variables from
HTMLcolors.py)
background – string filename of a graphic used as the
doc background.
textcolor – Color string used for text. (can use
variables from HTMLcolors.py)

linkcolor – Color string used for hyperlinked text. vlinkcolor – Color string used for visited hypertext. alinkcolor – Color string used for active hypertext. place_nav_buttons – Flag to enable/disable the use of

navigation buttons. Default is on. Set to 0 to disable.

blank – Image tuple for the transparent spacer gif prev – Image tuple for the Previous Page button next – Image tuple for the Next Page button top – Image tuple for the Top of Manual button home – Image tuple for the site Home Page button goprev – URL string for the prev button gonext – URL string for the next button gotop – URL string for the top button gohome – URL string for the home button script – a single or list of Script objects to be included in the <HEAD> onLoad – Script, which is executed when the document is loaded onUnload – Script, which is executed when the document is unloaded

author = 'Micky Mouse'
banner = ('/image/banner.gif', 472, 30)
blank = ('../image/blank.gif', 71, 19)
email = 'micky@disney.com'
footer()

Generate the standard footer markups.

gohome = None
gonext = None
goprev = None
gotop = None
header()

Generate the standard header markups.

home = ('../image/BTN_HomePage.gif', 74, 19)
nav_buttons()

Generate hyperlinked navigation buttons.

If a self.go* attribute is null that corresponding button is replaced with a transparent gif to properly space the remaining buttons.

next = ('../image/BTN_NextPage.gif', 71, 19)
place_nav_buttons = 'yes'
prev = ('../image/BTN_PrevPage.gif', 71, 19)
subtitle = None
top = ('../image/BTN_ManualTop.gif', 74, 19)
zone = ' Central US'
class astro.services.imageview.HTMLgen.SimpleDocument(resource=None, **kw)

Bases: astro.services.imageview.HTMLgen.BasicDocument

Supports all features of a self contained document.

This includes support for CSS1, meta and base tags, and embedded scripts.

First constructor argument is resource file containing document attribute settings.

base = None
html_body_tag()

Return BODY tag with attributes.

html_head()

Generate the HEAD TITLE and BODY tags.

meta = None
onLoad = None
onUnload = None
script = None
style = None
stylesheet = None
class astro.services.imageview.HTMLgen.Small(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Render in a smaller font.

attr_dict = {'style': '', 'id': '', 'class': ''}
attr_template = '%(class)s%(id)s%(style)s'
attrs = ('class', 'id', 'style')
tagname = 'SMALL'
trailer = ''
class astro.services.imageview.HTMLgen.Span(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Generic tag to mark text for a style application.

attr_dict = {'style': '', 'id': '', 'class': ''}
attr_template = '%(class)s%(id)s%(style)s'
attrs = ('class', 'id', 'style')
tagname = 'SPAN'
class astro.services.imageview.HTMLgen.Strike(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

The text is struck trough with a horizontal line.

attr_dict = {'style': '', 'id': '', 'class': ''}
attr_template = '%(class)s%(id)s%(style)s'
attrs = ('class', 'id', 'style')
tagname = 'STRIKE'
trailer = ''
class astro.services.imageview.HTMLgen.StringTemplate(template, substitutions=None, **kw)

Bases: object

Generate documents based on a template and a substitution mapping.

Must use Python 1.5 or newer. Uses re and the get method on dictionaries.

Usage:
T = TemplateDocument(‘Xfile’) T.substitutions = {‘month’: ObjectY, ‘town’: ‘Scarborough’} T.write(‘Maine.html’)

A dictionary, or object that behaves like a dictionary, is assigned to the substitutions attribute which has symbols as keys to objects. Upon every occurance of these symbols surrounded by braces {} in the source template, the corresponding value is converted to a string and substituted in the output.

For example, source text which looks like:
I lost my heart at {town} Fair.
becomes:
I lost my heart at Scarborough Fair.

Symbols in braces which do not correspond to a key in the dictionary remain unchanged.

An optional third argument to the class is a list or two strings to be used as the delimiters instead of { } braces. They must be of the same length; for example [‘##+’, ‘##’] is invalid.

keys()
set_template(template)
write(filename=None)

Emit the Document HTML to a file or standard output.

Will not overwrite file is it exists and is textually the same. In Unix you can use environment variables in filenames. Will print to stdout if no argument given.

class astro.services.imageview.HTMLgen.Strong(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Strongly emphasize the text.

attr_dict = {'style': '', 'id': '', 'class': ''}
attr_template = '%(class)s%(id)s%(style)s'
attrs = ('class', 'id', 'style')
tagname = 'STRONG'
trailer = ''
class astro.services.imageview.HTMLgen.Sub(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Render as subscript.

attr_dict = {'style': '', 'id': '', 'class': ''}
attr_template = '%(class)s%(id)s%(style)s'
attrs = ('class', 'id', 'style')
tagname = 'SUB'
trailer = ''
class astro.services.imageview.HTMLgen.Sup(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Render as subscript.

attr_dict = {'style': '', 'id': '', 'class': ''}
attr_template = '%(class)s%(id)s%(style)s'
attrs = ('class', 'id', 'style')
tagname = 'SUP'
trailer = ''
class astro.services.imageview.HTMLgen.TD(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Define a table data cell.

attr_dict = {'bordercolor': '', 'bordercolorlight': '', 'nowrap': '', 'valign': '', 'colspan': '', 'style': '', 'align': '', 'bordercolordark': '', 'rowspan': '', 'background': '', 'bgcolor': '', 'height': '', 'id': '', 'width': '', 'class': ''}
attr_template = '%(class)s%(id)s%(style)s%(nowrap)s%(align)s%(valign)s%(background)s%(bordercolor)s%(bordercolordark)s%(bordercolorlight)s%(rowspan)s%(colspan)s%(height)s%(width)s%(bgcolor)s'
attrs = ('class', 'id', 'style', 'nowrap', 'align', 'valign', 'background', 'bordercolor', 'bordercolordark', 'bordercolorlight', 'rowspan', 'colspan', 'height', 'width', 'bgcolor')
tagname = 'TD'
trailer = ''
class astro.services.imageview.HTMLgen.TH(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Define a table header cell.

attr_dict = {'bordercolor': '', 'bordercolorlight': '', 'nowrap': '', 'bordercolordark': '', 'valign': '', 'colspan': '', 'background': '', 'align': '', 'rowspan': '', 'style': '', 'bgcolor': '', 'height': '', 'id': '', 'width': '', 'class': ''}
attr_template = '%(class)s%(id)s%(style)s%(nowrap)s%(align)s%(valign)s%(rowspan)s%(colspan)s%(height)s%(width)s%(bgcolor)s%(background)s%(bordercolor)s%(bordercolordark)s%(bordercolorlight)s'
attrs = ('class', 'id', 'style', 'nowrap', 'align', 'valign', 'rowspan', 'colspan', 'height', 'width', 'bgcolor', 'background', 'bordercolor', 'bordercolordark', 'bordercolorlight')
tagname = 'TH'
trailer = ''
class astro.services.imageview.HTMLgen.TR(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Define a row of cells within a table.

attr_dict = {'bordercolor': '', 'bordercolorlight': '', 'align': '', 'bordercolordark': '', 'nowrap': '', 'style': '', 'bgcolor': '', 'id': '', 'valign': '', 'class': ''}
attr_template = '%(class)s%(id)s%(style)s%(align)s%(bgcolor)s%(bordercolor)s%(bordercolordark)s%(bordercolorlight)s%(nowrap)s%(valign)s'
attrs = ('class', 'id', 'style', 'align', 'bgcolor', 'bordercolor', 'bordercolordark', 'bordercolorlight', 'nowrap', 'valign')
tagname = 'TR'
class astro.services.imageview.HTMLgen.TT(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Format teletype style.

attr_dict = {'style': '', 'id': '', 'class': ''}
attr_template = '%(class)s%(id)s%(style)s'
attrs = ('class', 'id', 'style')
tagname = 'TT'
trailer = ''
class astro.services.imageview.HTMLgen.Table(tabletitle='', **kw)

Bases: object

Construct a Table with Python lists.

Instantiate with a string argument for the table’s name (caption). Set object.heading to a list of strings representing the column headings. Set object.body to a list of lists representing rows. WARNING: the body attribute will be edited to conform to html. If you don’t want your data changed make a copy of this list and use that with the table object.

Keyword Parameters

Defaults in (parenthesis). Keyword parameters may be set as attributes of the instantiated table object as well.

caption_align – ‘top’|’bottom’ specifies the location of the table title (‘top’) border – the width in pixels of the bevel effect around the table (2) cell_padding – the distance between cell text and the cell boundary (4) cell_spacing – the width of the cell borders themselves (1) width – the width of the entire table wrt the current window width (‘100%’) colspan – a list specifying the number of columns spanned by that heading

index. e.g. t.colspan = [2,2] will place 2 headings spanning 2 columns each (assuming the body has 4 columns).
heading – list of strings, the length of which determine the number of
columns. ( [‘&nbsp’]*3 )
heading_align – ‘center’|’left’|’right’
horizontally align text in the header row (‘center’)
heading_valign – ‘middle’ |’top’|‘bottom’
vertically align text in the header row (‘middle’)

body_color – a list of colors, for each column (None) heading_color – a list of color for each column heading (None)

For both these the index used is i%len(..._color) so the color cycles through the columns
body – a list of lists in row major order containing strings or objects
to populate the body of the table. ( [[‘&nbsp’]*3] )

column1_align – ‘left’|’right’|’center’ text alignment of the first column cell_align – ‘left’|’right’|’center’ text alignment for all other cells cell_line_breaks – 1|0 flag to determine if newline char in body text will be

converted to <br> symbols; 1 they will, 0 they won’t. (1)
get_body_color(colors, i)

Return bgcolor argument for column number i

class astro.services.imageview.HTMLgen.TableLite(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Container class for TH TD TR and Caption objects.

attr_dict = {'bordercolor': '', 'cellpadding': '', 'bordercolorlight': '', 'nowrap': '', 'hspace': '', 'vspace': '', 'border': '', 'cellspacing': '', 'valign': '', 'cols': '', 'style': '', 'align': '', 'bordercolordark': '', 'rules': '', 'background': '', 'bgcolor': '', 'frame': '', 'id': '', 'width': '', 'height': '', 'class': ''}
attr_template = '%(class)s%(id)s%(style)s%(align)s%(background)s%(border)s%(bordercolor)s%(bordercolordark)s%(bordercolorlight)s%(cols)s%(frame)s%(cellpadding)s%(cellspacing)s%(height)s%(hspace)s%(width)s%(bgcolor)s%(nowrap)s%(rules)s%(valign)s%(vspace)s'
attrs = ('class', 'id', 'style', 'align', 'background', 'border', 'bordercolor', 'bordercolordark', 'bordercolorlight', 'cols', 'frame', 'cellpadding', 'cellspacing', 'height', 'hspace', 'width', 'bgcolor', 'nowrap', 'rules', 'valign', 'vspace')
tagname = 'TABLE'
class astro.services.imageview.HTMLgen.TemplateDocument(template, substitutions=None, **kw)

Bases: astro.services.imageview.HTMLgen.StringTemplate

Generate documents based on a template and a substitution mapping.

Must use Python 1.5 or newer. Uses re and the get method on dictionaries.

Usage:
T = TemplateDocument(‘Xfile’) T.substitutions = {‘month’: ObjectY, ‘town’: ‘Scarborough’} T.write(‘Maine.html’)

A dictionary, or object that behaves like a dictionary, is assigned to the substitutions attribute which has symbols as keys to objects. Upon every occurance of these symbols surrounded by braces {} in the source template, the corresponding value is converted to a string and substituted in the output.

For example, source text which looks like:
I lost my heart at {town} Fair.
becomes:
I lost my heart at Scarborough Fair.

Symbols in braces which do not correspond to a key in the dictionary remain unchanged.

An optional third argument to the class is a list or two strings to be used as the delimiters instead of { } braces. They must be of the same length; for example [‘##+’, ‘##’] is invalid.

set_template(template)
class astro.services.imageview.HTMLgen.Text(text='')

Bases: object

Class to encapsulate text. Escape special characters for HTML.

append(text='')

Concatenate text characters onto the end.

Will escape special characters.

class astro.services.imageview.HTMLgen.Textarea(text='', **kw)

Bases: object

Used for an entry widget to type multi-line text (for forms).

Keyword Arguments:

rows – sets the number of text rows. (default=4) cols – sets the number of text columns. (default=40) onBlur – script, which is executed, when the field loses focus onChange – script, which is executed, when the field value changed onFocus – script, which is executed, when the field receives focus onSelect – script, which is executed, when part of the field

is selected
astro.services.imageview.HTMLgen.Typewriter

alias of TT

class astro.services.imageview.HTMLgen.U(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Underlined text.

attr_dict = {'style': '', 'id': '', 'class': ''}
attr_template = '%(class)s%(id)s%(style)s'
attrs = ('class', 'id', 'style')
tagname = 'U'
trailer = ''
astro.services.imageview.HTMLgen.UL

alias of List

class astro.services.imageview.HTMLgen.URL(url)

Bases: object

Represent a Universal Resource Locator.

Assumed to be of the form: http://www.node.edu/directory/file.html with http being an example protocol, www.node.edu being an example network node, directory being the directory path on that node, and file.html being the target filename. The argument string is parsed into attributes .proto , .node , .dir , .file respectively and may be altered individually after instantiation. The __str__ method simply reassembles the components into a full URL string.

copy()

No argument. Return a copy of this object.

parse(url)
split(p)

Same as posixpath.split()

Copied here for availability on the Mac.

class astro.services.imageview.HTMLgen.Var(*contents, **kw)

Bases: astro.services.imageview.HTMLgen.AbstractTag

Used for variable names.

attr_dict = {'style': '', 'id': '', 'class': ''}
attr_template = '%(class)s%(id)s%(style)s'
attrs = ('class', 'id', 'style')
tagname = 'VAR'
trailer = ''
astro.services.imageview.HTMLgen.compare_f2f(f1, f2)

Helper to compare two files, return 0 if they are equal.

astro.services.imageview.HTMLgen.compare_s2f(s, f2)

Helper to compare a string to a file, return 0 if they are equal.

astro.services.imageview.HTMLgen.escape(text, replace=<method 'replace' of 'str' objects>)

Converts the special characters ‘<’, ‘>’, and ‘&’.

RFC 1866 specifies that these characters be represented in HTML as &lt; &gt; and &amp; respectively. In Python 1.5 we use the new string.replace() function for speed.

astro.services.imageview.HTMLgen.markup_re(text, rex=None, marker=None, collapse=0)

Markup the contained text with a given re pattern/object with a given tag class instance. Uses re module.

Arguments

text – string to act on rex – a regular expression object or pattern from the re module which will be used

to match all text patterns in the Paragraph body. Must have a single group defined. Group 1 is the matching text that will be marked. Defaults to all parenthetical text.
marker – an HTMLgen class instance to which the found text will
be sent for wrapping (using its __call__ method). Default is Emphasis. Can be your function as well.
collapse – Optional flag. When set to 1 removes the non-
grouped matching text from the output. Default 0.

Returns tuple pair of the marked text and the number of matching text groups.

astro.services.imageview.HTMLgen.mpath(path)

Converts a POSIX path to an equivalent Macintosh path.

Works for ./x ../x /x and bare pathnames. Won’t work for ‘../../style/paths’.

Also will expand environment variables and Cshell tilde notation if running on a POSIX platform.

astro.services.imageview.HTMLgen.overlay_values(obj, dict)

Adds each item from dict to the given object iff there already exists such a key. Raises KeyError if you try to update the value of non-existing keys.

astro.services.imageview.HTMLgen.relpath(path1, path2)

Return the relative path from directory ‘path1’ to directory ‘path2’

Both arguments are assumed to be directory names as there is no way to really distinguish a file from a directory by names alone. To loosen this restriction one can either assume that both arguments represent files or directories currently extant so that they can be tested, or add extra arguments to flag the path types (file or directory).

I chose to impose this restriction because I will use this function in places where the pathnames are for files yet to be created.

astro.services.imageview.HTMLinputpage module

# —————————————————————————– class HTMLinputpage:

‘’‘Generate HTML menus and inputforms to be shown in the clients browser

HTML user-interface to call the current (CGI)script ‘’’ def QForminit(self,cginame,Queryselect):

‘’‘This thing is called when the image viewer front page is created’‘’ # uniform form-submitbutton: standard submit-button cannot be resized, size= .., style= not OK # replace by HTML code via enlarge_inputbutton sqlforminit = Form(cgi=cginame, submit=Input(type=’submit’,name=”ENTER”,value=”submit”)) hQueryselect= Input(type=’hidden’, name=’Queryselect’, value=Queryselect) sqlforminit.append(hQueryselect) return sqlforminit
def QF_introspect(self,cginame):
‘’‘Query-form to produce main-menu ; calls query Q_introspect’‘’ sqlform= self.QForminit(cginame,”Find_Tables”) sqlform.append(Heading(1, ‘AWE Image Viewer ‘,align=’center’ )) sqlform.append(BR(5),4*”&nbsp;”,Href(url=process_depco_address,text=Strong(‘Dependency Cutout service generates cutouts for sources’),target=’_blank’),BR(2)) sqlform.append(4*”&nbsp;”,Href(url=process_RGBM_address ,text=Strong(‘RgbMaker service combines the common cutout (area) of three frames to an RGB image’),target=’_blank’),BR(5)) sqlform=str(sqlform).replace(‘’‘<INPUT TYPE=”submit” NAME=”ENTER” VALUE=”submit”>’‘’,””) # form without input return sqlform
def contentsHTMLpage(self, servraddress):

‘’‘HTML-output homepage’‘’ CGIscript = “/” # os.path.basename(sys.argv[0]) onUnloadpar= “” # “alert(‘SHUTDOWN WINDOW close: current directory removed ?’)” onLoadpar = “” sqldoc = SimpleDocument(title=”AWE Image Viewer”, bgcolor=”#e6e6fa”,onLoad=”%s” % onLoadpar,onUnload=”%s” % onUnloadpar) #E1FFF0 QForms = [self.QF_introspect(CGIscript)] for QForm in QForms:

sqldoc.append(QForm)

# ========================== windowrefsjsurl = “%s?Queryselect=admininfo” % servraddress windowrefjs = ‘’‘javascript:a=window.open(‘%s‘, ‘%s’,’alwaysRaised=yes,height=400,width=800,resizable=yes,scrollbars=1’);a.focus();’‘’ % (windowrefsjsurl,”ADMIN_INFO”) linktolog = Href(url=windowrefsjsurl,text=” [ i]”, target = “_blank” ) # ====================================

sqldoc.append(HR()) version = Small(‘ nov 25 2008 ‘) sqldoc.append(Href(url=omegacenurl,text=’OmegaCEN home page’,target=’_blank’),4*”&nbsp;”,

Href(url=dbviewurl,text=’DBviewer’,target=’_blank’),4*”&nbsp;”,HOMEref,4*”&nbsp;”, Mailto(replymail,Strong(‘contact’),’AWE viewer comment’), 4*”&nbsp;”,version,linktolog,BR(1))

return str(sqldoc)

def writeHTMLinputpagetoFile(self,servaddress,file_name):
‘’’ test function only’‘’ HTMLdoc = self.contentsHTMLpage(servaddress) print(“

Load %s in browser to view %s/%s” % (file_name,servaddress,file_name))

open(file_name, ‘w’).write(str(HTMLdoc))
def writeHTMLinputpagetoServer(self, servaddress):

print(“default page written to server at %s” % servaddress) HTMLdoc = self.contentsHTMLpage(servaddress) if __name__ == ‘__main__’:

print(str(HTMLdoc))
else:
self.wfile.write(HTMLdoc.encode())
def writeHTMLerrorpage(self, servaddress, mess):
print(“error page written to server at %s” % servaddress) self.wfile.write((“++++++++ %s %s ++++++++++++++++++” % (error_str, mess)).encode())

astro.services.imageview.HtmlDependencyCutout module

astro.services.imageview.HtmlRgbMaker module

astro.services.imageview.ImgCleanup module

astro.services.imageview.ImgQHconfig module

Configuration of the image server

astro.services.imageview.ImgQHconfig.get_image_path(filename, quote=False)

return full path to generated image

astro.services.imageview.ImgQHconfig.imgserverspecs(qpar)

imgage-server name, address, user-file location ; provide full server-adress for links : necessary for HTML-pages downloaded to client

astro.services.imageview.ImgQueryHandler3 module

astro.services.imageview.ImgXmlHandler module

class astro.services.imageview.ImgXmlHandler.ImageServerXmlHandler

Bases: xml.sax.handler.ContentHandler

class for parsing a xml file from the image server which contains an overview of the cutouts, result is a dict with {sid : filename}

characters(content)

content of an element, set in result

endDocument()
endElement(name)

an element has ended, clean

startDocument()
startElement(name, attrs)

an element has started, store name

astro.services.imageview.ImgXmlHandler.do_xml_request(slid, server='imageview.astro-wise.org')

do a xml request to the image server in the Env and return the result a dictionary with {slid:filename}

astro.services.imageview.ImgXmlHandler.xml_unquote(in_string)

replace special characthers &,< and > to xml encoding

astro.services.imageview.Output module

Output.py for imageview: stripped-down version from DBview

class astro.services.imageview.Output.Output

Bases: object

output_switch(SQLoutput, Query, CGIscript, qpar, TitleMess)

Output from server is directed to screen or file-output, different formats

writeHTMLoutput(qpar, TitleMess, SQLtable, Query, SQLInputForms)

write server-output from queries (tables, forms) via browser to clients’screen in HTML format

astro.services.imageview.RawFrameCutout module

astro.services.imageview.RgbMaker module

astro.services.imageview.file_menu_manager module

import os, traceback, glob, time, subprocess

from common.log.ThreadedLog import log from common.util.imports_2to3 import urllib_quote, urllib_unquote

from astro.services.imageview.HTMLgen import Href, BR, SimpleDocument, Paragraph, Strong, Table, Pre from astro.services.imageview.ImgQHconfig import fitsfilecache, db_img_path, db_cutout_path, cutout_path, log_path, dataserverurl

from astro.services.imageview.fitsfile_manager import fitsfilelock_dict

‘’’ functions dealing with managing temp. local files via menus ‘’’ class file_menu_manager: # to be inherited by class ImgQueryHandler

demo_turnpage_number = 105

def check_tmpdirs(self): # temp not used
‘’’ fitsfiles and specific subdirs in directory [fitsfilecache] : show message on contents ‘’’ filesizelist = [os.path.getsize(x) for x in glob.glob(os.path.join(fitsfilecache, “*.fits”))] sumfilesize = sum(filesizelist) nfitsfiles = len(filesizelist) subdirlist = glob.glob(db_cutout_path) return sumfilesize,nfitsfiles,len(subdirlist)
def check_clean_tmpdir(self):
‘’’ !!!! Cleaning is moved to separate Cleanup thread, see ImgCleanup !!!! activated when manually viewing directory on image-server from directory-link. ‘’’ filesizelist = [os.path.getsize(x) for x in glob.glob(os.path.join(fitsfilecache, “.fits”))] sumfilesize = sum(filesizelist) nfitsfiles = len(filesizelist) # subdirlist = glob.glob(db_cutout_path) subdirlist = glob.glob(os.path.join(cutout_path,””)) # subdirlistSL= glob.glob(db_img_path) subdirlistSL= glob.glob(os.path.join(db_cutout_path,”*”)) fitsfileindicator = str(BR()) + “Content of directories after file-management of temp files and dirs: ” + str(BR()) + str(Strong(“Imageview subdirectories contain: N fitsfiles: %s, MBytes : %s, N M*s subdirs : %s, N SLID* %s ;” % (nfitsfiles, int(sumfilesize/1000000),len(subdirlist), len(subdirlistSL) ))) + str(BR()) + str(Strong( ” CWD : %s” % os.getcwd()) ) return fitsfileindicator
def readlogfile(self,qpar):

‘’’ reads text from logfile indicated in link in function admininfo ‘’’ pathlogfile = qpar.get(“pathlogfile”,[“”])[0] logfiletext = str(Strong(“Content of image-server log-file : %s : ” % os.path.basename(pathlogfile))) + str(BR()) try:

logfile = open(pathlogfile) for line in logfile:

logfiletext += line

logfile.close()

except Exception as e:
logfiletext += “– error reading logfile –” log.write(‘Error in readlogfile: %s’ % e) traceback.print_exc()

return Pre(logfiletext), qpar

def admininfo(self,qpar): # dec from dbview

‘’‘Experimental info and download-window for administrator

Available as the “[_i]” link at the bottom of the front page of the image viewer. ‘’’ infodoc = SimpleDocument(title=”%s %s” % (“imageview”,”info”), bgcolor = ‘#f08080’) infotext1 = Paragraph(Strong(“Experimental info for administrator :”)) infotext2 = Paragraph(“Download logfiles for inspection into browser-window”) infodoc.append(infotext1,infotext2,BR()) keeploglist = loglist = glob.glob(os.path.join(os.getcwd(), log_path, “*.log”)) # logfilename to be synchronized with server

keeploglist.sort() if len(keeploglist) > 0:

loglisttable = Table(tabletitle=”files”, width=‘80%’,column1_align=’center’,cell_align=’center’) loglisttable.heading =[‘ age (days)’, ‘size (KB)’, ‘logfilename’] loglisttable_body = [[]] n = 0 for logfile in keeploglist:

n += 1 t= os.path.getctime(logfile) size= int(os.path.getsize(logfile)/1000) linktolog = str(Href(url=”%s?Queryselect=readlogfile&pathlogfile=%s” % (self.schemehost,logfile),text = ‘%s’ % os.path.basename(logfile),target = ‘_blank’ )) loglisttable_body.append([int((time.time() -t)/(3600*24)), size, linktolog])

loglisttable_body.sort() # sorts all columns loglisttable.body = loglisttable_body infodoc.append(loglisttable)

dataservers1= Href(url=”%s/status” % dataserverurl, text =”dataservers1”, target=”_blank”) infodoc.append(BR(),”Status :”,dataservers1)

# command = ‘ps v -C awe’ # local host command = ‘ps v U imageview’ infotext = Paragraph(Strong(“Process status via %s: ” % command)) #m = subprocess.getoutput(command) m = subprocess.Popen([command,], stdout=subprocess.PIPE).communicate()[0] infodoc.append(infotext,Pre(m))

command = ‘free -m’ infotext = Paragraph(Strong(“Memory status (MB) via %s: ” % command)) #m = subprocess.getoutput(command) m = subprocess.Popen([command,], stdout=subprocess.PIPE).communicate()[0] infodoc.append(infotext,Pre(m))

infotext = Paragraph(Strong(“The filelock dict :”)) msg = ‘’ for fn in list(fitsfilelock_dict.keys()) :

msg += ‘ %s : %s
‘ % (fn, fitsfilelock_dict.get(fn, ‘does not exist anymore’))

infodoc.append(infotext, Pre(msg))

fitsfileindicator = self.check_clean_tmpdir() infodoc.append(BR(),fitsfileindicator)

# do not eliminate files here nov 18

return infodoc, qpar

def Download_list(self,qpar):

‘’’ directory view, file and subdir manipulation’‘’ try:

subdir= qpar.get(“subdir”,[“mt33”])[0] list_selector = qpar.get(“list_selector”,[“.“])[0] path=qpar.get(‘subdir’)[0] downloadlist= glob.glob(os.path.join(path,list_selector.replace(“_”,””))) # ‘.

Download_table = Table(“File view, subdirectory %s” % subdir,body_color=[‘#f0e68c’]) # , width=”70%” basenamedlist = [Href(url=urllib_quote(“%s/%s” % (path,fname)) ,text= fname) for fname in [os.path.basename(pfname) for pfname in downloadlist]] # db_img_path if list_selector in [“.”,”*.fits_”]:

base_imagelist = self.imglist_read_store(“read”,”base_imgslist.py”,”x”) basenamedlist +=base_imagelist # add list of links to reduced original fts-images

fileaddresslist = [basenamedlist[zzz:zzz+3] for zzz in range(0,len(basenamedlist),3)] # 3 columns if len(fileaddresslist) < 1:

Download_table.body = [[“no list or no such subdirectory”]]
else:
Download_table.body= fileaddresslist
except Exception as e:
log.write(‘Error in Download_list: %s’ % e) traceback.print_exc()

subdir = qpar.get(“subdir”,[“mt33”])[0] # pself_address = “%s://%s” % (scheme,host) pself_address = “/” selectorstr = “Queryselect=Download_list&subdir=%s&list_selector=” % subdir linktoFITSdir = Href(“%s?%s*.fits_;” % (pself_address,selectorstr),text=”[.fits]”) linktoJPGx2dir = Href(“%s?%s*x2.jpg_” % (pself_address,selectorstr),text=”[*x2.jpg]” ) linktoJPGdir = Href(“%s?%s.jpg_” % (pself_address,selectorstr),text=”[.jpg ]” ) linktoTIFdir = Href(“%s?%s.tif_” % (pself_address,selectorstr),text=”[.TIF]” ) linktoPNGdir = Href(“%s?%s.png_” % (pself_address,selectorstr),text=”[.png ]” ) linktoZIPdir = Href(“%s?%s.zip_” % (pself_address,selectorstr),text=”[.zip]” ) linktoALLdir = Href(“%s?%s.*” % (pself_address,selectorstr),text=”[. : ALL]” ) linktoCLEARdir = ” ” # Href(“%s?Queryselect=clear_currentsubdir&subdir=%s&list_selector=%s” % (pself_address,subdir,list_selector),text=”[CLEAR files: %s]” % list_selector) # ,target=”_blank”

fitsfileindicator = “–” # moved to info

# =============================================== windowrefsjsurl = “%s?Queryselect=admininfo&subdir=%s” % (self.schemehost,subdir) # js window without navigation-bar tp prevent going back to invalid past state windowrefjs = ‘’‘javascript:a=window.open(‘%s‘, ‘%s’,’alwaysRaised=yes,height=400,width=800,resizable=yes,scrollbars=1’);a.focus();’‘’ % (windowrefsjsurl,”ADMIN INFO”) # linktolog = Href(url=windowrefjs,text=” [ INFO VIEW ]” ) # linktolog = Href(url=windowrefjs,text=” [ i]” ) # windows without bars linktolog = Href(url=windowrefsjsurl,text=” [ i]”, target = “_blank” ) # ================================================

html_output= ” %s %s %s %s %s %s %s %s” % (linktoPNGdir,linktoJPGx2dir,linktoZIPdir,linktoFITSdir,linktoALLdir, fitsfileindicator, linktolog, Download_table) # %s %s %s %s return html_output,qpar

def Show_baseimg_list(self,qpar):
‘’’ list of images-names to be produced in reduced size ‘’’ Download_table = Table(“Demo Download Table”,body_color=[‘#f0e68c’]) base_imagelist = self.imglist_read_store(“read”,”base_imgslist.py”,”x”) # if qpar.get(“Queryselect”)[0] in [“Show_baseimg_list”] : baseimagelist = [demofitsfile1] # obsolete, called from Entryform Download_table.body = [base_imagelist] k = “unknown” k = Paragraph(“number of subimages %s numbr of images %s” % (len(self.x), self.nmbr_images)) return str(Download_table) + str(k),qpar
def Entry_form(self,qpar,subimgnumber=demo_turnpage_number): # 200 april 8 obsolete

pself_address = cginame= self.imageserver_name E_form = “” # formulier-object E_form = Form(cgi = cginame, submit = Input(type=’submit’,name=”ENTER”,value=”submit”)) windowrefreduced= ‘’‘javascript:a=window.open(‘%s?Queryselect=NewWindowWithReducedImage&filename=%s&subdir=%s’,’Reduced’,’height=1000,width=1000,resizable=yes,scrollbars=1’);a.focus();’‘’ % (self.schemehost,urllib_quote(urllib_quote(self.filename)),subdir) # pself_address, windowrefreducedlist = ‘’‘javascript:a=window.open(‘%s?Queryselect=Show_baseimg_list&subdir=%s’,’ReducedList‘ ,’height=200,width=300,resizable=yes,scrollbars=1’);a.focus();a.moveTo(100,100);’‘’ % (self.schemehost,subdir) # pself_address, addrlists = [[Href(“%s?Queryselect=SubImageszip&filename=%s&numberofimages=%s&subdir=%s&NEG=Y” % (self.schemehost,urllib_quote(demofitsfile1),subimgnumber,subdir),text=”SUBimages DEMOlist POS [n=%s]” % 1000,target=”_blank”)],

[Href(“%s?Queryselect=SubImageszip&filename=%s&numberofimages=%s&subdir=%s&NEG=N” % (self.schemehost,urllib_quote(demofitsfile1),subimgnumber,subdir),text=”SUBimages DEMOlist NEG [n=%s]” % 1000,target=”_blank”)],
[Href(url=”#”,text=”REDUCED LARGE IMAGE DEMO [8000x8000, 290 Mb]”,onClick=windowrefreduced)],

[Href(“%s?Queryselect=Download_list&subdir=%s” % (pself_address,subdir),text=”[FILE OPS *.fits %s ]” % subdir,target=”_blank”)]]

atable1 = Table(“Demo Link Table”,body_color=[‘#f0e68c’], width=”70%”) atable1.body = addrlists E_form.append(atable1) DirDel = Input(type=’hidden’,name=”DirDel”,value=subdir) E_form.append(DirDel) E_form=str(E_form).replace(‘’‘<INPUT TYPE=”submit” NAME=”ENTER” VALUE=”submit”>’‘’,””) # form without input return E_form

astro.services.imageview.fitsfile_manager module

astro.services.imageview.imageview module

astro.services.imageview.imgclient module

imgclient.py is a client for the AWE-imageview-server, to be used from a python prompt. Under the AWE-prompt, target-adresses are taken from the environment. imgclient expects instantiation by sky or grid coordinates via lists or dictionaries; Numbers to be rendered an size of images can be changed from default.

#1 dictionary of image-names and RA-DEC data-lists (as in #2) obtained from
  • methods in SourceList and AssociateList classes [see visualization-howto]:

    def make_image_dict_on_sources(self, sids, mode=’sky’) def make_image_dict_on_associates(self, aids, mode=’sky’)

    see documentation of classes.

  • OBSOLETE: SourceLists identified by SLID number(s). input : e.g SLIDlist =[54052,54050]

#2 dictionary of imagenames and list of tuples of positions of subimage-centers exampledict :{“imgname1”:[[RA,DEC]..[RA,DEC]],”imgname2”:[[RA,DEC]..[RA,DEC]], etc} option: individual width and height of cut-out image : {“imgname1”:[[RA,DEC, width]..[RA,DEC,width,heigth]]

#3 dictionary of imagenames and dictionary of RA,DEC,width,height and FITS-whateverheader-info [uppercase,lowercase,crval1,crval2 are understood; height = width for width-only input; height = width = 50 for no input] exampledict :{“imgname1”:[{“RA”:xxx,”DEC”:yyy,”width”:qqq, “height”:zzz},{“RA”:xxx,”DEC”:yyy,”width”:qqq, “height”:zzz}], “imgname2”:[{“RA”:xxx,”DEC”:yyy,”width”:qqq, “height”:zzz,”SLID” ; ssss,”Comment” : “abcdef”},{“RA”:xxx,”DEC”:yyy,”width”:qqq, “height”:zzz}]} option: use PIX_X and PIX_Y instead of RA and DEC to enter pixel-coordinates option: use FTAG to have a user-defined name for output-filename of getzipfile() : [NB output for single zipped file is unzipped fits] option: use pixelcoordinates XMIN,YMIN,XMAX,YMAX to specify a rectangle; in this mode, the imiage-server does NOT check for out of bound coordinates, producing an error [when used as module] or eror-message in this client. NB: individual files in a zipfile are not tagged; option: use any alternative KEY to incorporate a name : value into the fitsheader

#4 list of lists to control layout to form a HTML-table of joint dictionaries of imagenames (key : FILE) plus RA, DEC etc , and strings as headers.
see example in stestdata.py

use methods m.getimg() [links to webpage with picture-format images, and zipped fit-cutouts] or m.getzipfile() [zipped fit-cutouts only] option: m.filename contains the filename the downloaded file: a single fitsfile or a single zip file

Optionally : retrieves and loads into default browser; downloads subimages in single zipfile

For tests-purposes: - add -F to Output parameter to switch off direct-access cut-out in the image-server.

eg: clt.getzipfile(Output=”zippedfile -F”) or clt.getimg(Output= “html -F” ) instead of clt.getzipfile() or clt.getimg()
  • suppress printing by client: use verbose=False switch when initializing : eg: clt = imgclient(data,verbose=False)
  • suppress log from imageserver: showLog=False

to operate from prompt: import imgclient x=imgclient(userdict,wide_high) to check the dictionary and convert into url for image-server, or x=imgclient(SLIDlist,maxn,wide_high) for input of Slidnumbers en output-limit per number of sources per image wide_high=[100,100] for alternative generic width and height of the images and windows

x.getimg() to retrieve HTML file with links to images or x.viewimg() to retrieve idem and view in default browser or x.getzipfile() to retrieve into the current directory fits subimages in fitsformat as a single zipfile, or non-zipped for a single subimage. x.getzipfile(Output=”zippedfitsPNG”) to retrieve into the current directory fits subimages in PNG as a single zipfile,

class astro.services.imageview.imgclient.imgclient(dicts={'empty': 0}, nmax='nomax', wide_high=[50, 50], verbose=True, showLog=True)

Bases: astro.services.imageview.imgclient.sendToAWImgserver

alias for sendToAWImgserver

class astro.services.imageview.imgclient.sendToAWImgserver(dicts={'empty': 0}, nmax='nomax', wide_high=[50, 50], verbose=True, showLog=True)

Bases: object

cprint(message)
get_file_object_or_name(host, ImgserverOutput, Output)

‘get file-like object or HTML-file-name from HTTP response

getimg(Output='html', imgserveraddress='http://imageview.astro-wise.org')

alias for post_url

getzipfile(Output='zippedfile', imgserveraddress='http://imageview.astro-wise.org')

alias for post_url

initialize_request(host, path, postdata)

initialize and return the request object

make_url(Output, imgserveraddress, Fflag)

url for dbview, imageview , imageserver, dataserver; exitname imgserver_url to be changed

post_url(Output, imgserveraddress)

send data and download HTML file with adresses to images and files

send_to_browser(Output, imgserveraddress)

download HTML file via post_url and read into web-browser

strip_Flag_Output(Outputparameter)

get rid of any flag after - sign in Output parameter

viewimg(Output='html', imgserveraddress='http://imageview.astro-wise.org')

alias for send_to_browser

astro.services.imageview.stestdata module

astro.services.imageview.testdata module

Module contents