tangelo web framework documentationtangelo web framework documentation, release 0.0 tangelo is a...

41
Tangelo Web Framework Documentation Release 0.0 Kitware, Inc. February 28, 2014

Upload: others

Post on 25-Jun-2020

22 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web FrameworkDocumentation

Release 0.0

Kitware, Inc.

February 28, 2014

Page 2: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,
Page 3: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Contents

i

Page 4: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

ii

Page 5: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

Tangelo is a general-purpose web server framework, built on top of CherryPy. Once it’s set up, it stays out of yourway, clearing the path for you to use HTML5, CSS, JavaScript, and other web technologies such as

• JQuery

• D3

• Bootstrap

• WebGL

• Canvas

• Vega

to create rich web applications - from traditional, static pages, to cutting-edge, visual, dynamic displays. Tangelo alsolets you include Python scripts as part of your application, alongside your HTML and Javascript files, runningthem on your behalf to do anything from retrieving a few database results for display, to engaging with powerfulcomputational engines such as Hadoop to compute complex results.

To help in creating these applications, Tangelo exports the Tangelo API, which exists as a collection of Python func-tions, JavaScript functions, and a set of rules for creating flexible and powerful web services. This document describesall the pieces that fit together to make Tangelo work.

Please visit the Tangelo homepage or the GitHub repository for more information.

Contents 1

Page 6: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

2 Contents

Page 7: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

CHAPTER 1

Quick Start

1. Install Git.

2. Install CMake.

3. Open a shell and run the following:

git clone https://github.com/Kitware/tangelo.gitcd tangelomkdir buildcd buildcmake ..makepip install dist/Tangelo-[version].tar.gz # May require sudotangelo start

4. Visit your Tangelo instance at http://localhost:8000.

3

Page 8: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

4 Chapter 1. Quick Start

Page 9: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

CHAPTER 2

Quick Start for Windows

Windows machines are “special”. Take these steps to get things going.

1. Install Git.

2. Install CMake.

3. Install Python 2.7 Windows X86-64 installer.

4. Install Windows Python packages for pip, pymongo, and twisted. Choose the package links ending inamd64-py2.7.exe.

5. Open the Git Bash shell and run the following:

git clone https://github.com/Kitware/tangelo.gitcd tangelomkdir buildcd buildcurl -OL https://github.com/martine/ninja/releases/download/v1.4.0/ninja-win.zipunzip ninja-win.zipcmake -G Ninja ..ninja/c/Python27/Scripts/pip install dist/Tangelo-[version].tar.gz/c/Python27/Scripts/tangelo start

6. Visit your Tangelo instance at http://localhost:8000.

5

Page 10: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

6 Chapter 2. Quick Start for Windows

Page 11: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

CHAPTER 3

Using Tangelo

3.1 Installation

Tangelo currently runs on Linux, OS X, and Windows. It may run on other UNIXlike operating systems as well, butthese are the three supported platforms.

3.1.1 Linux and OS X

1. Install software dependencies

Install the following software, which is required to download, build, deploy, and run Tangelo:

• GNU Make

• CMake

• Git

• Python 2.7

2. Check out the Tangelo source code

Issue this git command to clone the Tangelo repository:

git clone git://github.com/Kitware/tangelo.git

This will create a directory called tangelo containing the source code.

3. Configure the build

Create a build directory and move into it:

cd tangelomkdir build

Run cmake or ccmake to configure, supplying the source code directory as its argument.

cd buildcmake ..

4. Build the server

Run the make command:

make

7

Page 12: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

This will create a Python package Tangelo-[version].tar.gz in the dist directory.

5. Install the package

To install this package into your Python environment, run:

pip install dist/Tangelo-[version].tar.gz

This installs the tangelo Python package along with its dependencies and places the tangelo executable in a standardlocation such as /usr/local/bin. After this step you should be able to execute which tangelo to see whereit has been installed.

If you are reinstalling Tangelo after a git pull or source code change, run the following:

makepip uninstall tangelopip install dist/Tangelo-[version].tar.gz

6. Start the server!

The tangelo program controls startup and shutdown of the Tangelo server. Run:

tangelo start

to launch the server (on localhost:8000 by default). Point your browser there and you should see a collection of demoapplications to get you started.

3.1.2 Windows

1. Install Git

GitHub has great instructions for setting up Git.

2. Install CMake

Download and install the latest version of CMake. Use the link marked Win32 Installer.

3. Install Python

Download and install Python 2.7. Use the link marked Windows X86-64 MSI Installer.

4. Install Python packages

Download and install the Windows Python packages for pip, pymongo, and twisted. Choose the package linksending in amd64-py2.7.exe.

5. Clone the Tangelo Repository

Open the Git Bash shell and execute the following:

cd ~git clone https://github.com/Kitware/tangelo.git

This will create a new directory in your home directory called tangelo containing the Tangelo sources.

6. Install Ninja

Create a build directory:

cd tangelomkdir build

Download and unzip Ninja. This extracts to the single file ninja.exe. We’ll want the Ninja executable handy, so we’llput it into your build directory. You can do this all from the Git Bash shell:

8 Chapter 3. Using Tangelo

Page 13: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

cd buildcurl -OL https://github.com/martine/ninja/releases/download/v1.4.0/ninja-win.zipunzip ninja-win.zip

7. Configure and build

From the build directory, configure the Tangelo build using CMake:

cmake -G Ninja ..

Then build the project using the ninja build tool:

ninja

8. Install the package

To install this package into your Python environment, run:

/c/Python27/Scripts/pip install dist/Tangelo-[version].tar.gz

This installs the tangelo Python package along with its dependencies and places the tangelo executable in/c/Python27/Scripts.

If you are reinstalling Tangelo after a git pull or source code change, run the following from the build directory:

ninja/c/Python27/Scripts/pip uninstall tangelo/c/Python27/Scripts/pip install dist/Tangelo-[version].tar.gz

9. Start the server!

The tangelo program controls startup and shutdown of the Tangelo server. Run:

/c/Python27/Scripts/tangelo start

to launch the server (on localhost:8000 by default). Point your browser there and you should see a collection of demoapplications to get you started.

3.1.3 Example App Setup

Named Entities

In order to run the named entities example at http://localhost:8000/examples/ner/, you need to install NLTK anddownload some datasets. On Mac and Linux, simply run:

pip install nltk

In a Windows Git Bash shell:

/c/Python27/Scripts/pip install pyyaml nltk

To get the NLTK datasets needed, run python from the shell (/c/Python27/python from Git Bash on Windows)and execute the following:

import nltknltk.download()

From the window that appears, go to the Models tab and download the maxent_ne_chunker, max-ent_treebank_pos_tagger, and punkt models by clicking on each and pressing the download button. Similarly down-load the words dataset from the Corpora tab. After closing the download window, quit() will exit the Pythonshell.

3.1. Installation 9

Page 14: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

3.1.4 Testing

First, install Selenium and the Python Imaging Library with:

pip install selenium PIL

Next, install the Chrome Selenium driver for your platform by downloading the binary and copying it to a directory inyour system path, e.g. on Mac/Linux:

mv /path/to/chromedriver /usr/local/bin/

In order to test Tangelo, build your project by running make or ninja, then execute ctest in the Tangelo builddirectory.

3.2 Basic Usage

Once it is set up and running, Tangelo’s basic usage is relatively straightforward. This chapter explains how Tangeloserves web content, a best practices guide for organizing your content, and how to use HTTP authentication to protectyour content.

3.2.1 Serving Web Content

Tangelo’s most basic purpose is to serve web content. Once Tangelo is running, it will serve content it finds in severalplaces.

User home directories. If you visit a URL whose first path component begins with a tilde (“~”), such ashttp://localhost:8080/~spock, Tangelo will attempt to serve content from the tangelo_html directory of userspock‘s home directory. On a Linux system, this might be the directory /home/spock/tangelo_html.

Web root directory. Visiting other URLs (that do not begin with a tilde) will cause Tangelo to serve contentout of the web root directory, which is the web subdirectory of the directory where Tangelo is deployed (see In-stallation). For example, if Tangelo has been deployed to /opt/tangelo, the web root directory would be/opt/tangelo/web, visiting http://localhost:8080/ would serve content from /opt/tangelo/web, and vis-iting http://localhost:8080/app would serve content from /opt/tangelo/web/app, etc.

The streaming API. The URL http://localhost:8080/stream is reserved; it is the interface to the Streaming API. Ifthere is a file or directory in the web root directory named stream, it will not be served by Tangelo.

The foregoing examples demonstrate how Tangelo associates URLs to directories and files in the filesystem. URLsreferencing particular files will cause Tangelo to serve that file immediately. URLs reference a directory behaveaccording to the following cascade of rules:

1. If the directory contains a file named index.html, that file will be served.

2. Otherwise, if the directory contains a file named index.htm, that file will be served.

3. Otherwise, Tangelo will generate a directory listing for that directory and serve that. This listing will includehyperlinks to the files contained therein.

As mentioned already, the URL http://localhost:8080/stream is special and does not serve any static content from disk.Similarly, a URL referring to a Python script, but lacking the final .py, names a web service; such URLs do not servestatic content, but rather run the referred Python script and serve the results (see Tangelo Web Services).

10 Chapter 3. Using Tangelo

Page 15: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

3.2.2 HTTP Authentication

Tangelo supports HTTP Digest Authentication to password protect web directories. The process to protect a directoryis as follows:

1. Go to the directory you wish to protect:

cd ~laforge/tangelo_html/DilithiumChamberStats

The idea is, this directory (which is accessible on the web ashttp://localhost:8080/~laforge/DilithiumChamberStats) contains sensitive information, and should be re-stricted to just certain people who have a password.

2. Create a file there called .htaccess and make it look like the following example, customizing it to fit yourneeds:

AuthType digestAuthRealm USS Enterprise NCC-1701-DAuthPasswordFile /home/laforge/secret/dilithiumpw.txt

This file requestes digest authnetication on the directory, sets the authentication realm to be the string “USSEnterprise NCC-1701-D”, and specifies that the acceptable usernames and passwords will be found in the file/home/laforge/secret/dilithiumpw.txt.

Currently, the only supported authentication type is digest. The realm will be displayed to the user whenprompted for a username and password.

3. Create the password file, using the tangelo-passwd program (see tangelo-passwd):

$ tangelo-passwd -c ~laforge/secret/dilithiumpw.txt "USS Enterprise NCC-1701-D" picardEnter password for picard@USS Enterprise NCC-1701-D: <type password here>Re-enter password: <retype password here>

This will create a new password file. If you inspect the file, you will see a user picard associated with an md5hash of the password that was entered. You can add more users by repeating the command without the -c flag,and changing the username.

At this point, the directory is password protected - when you visit the page, you will be prompted for a usernameand password, and access to the page will be restricted until you provide valid ones.

3.3 Tangelo Web Services

Tangelo’s special power lies in its ability to run user-created web services as part of a larger web application. Essen-tially, each Python file in Tangelo’s web space is associated to a URL; requesting this URL (e.g., by visiting it in abrowser) will cause Tangelo to load the file as a Python module, run a particular function found within it, and returnthe output as the content for the URL.

In other words, Tangelo web services mean that Python code can become web resources. Python is a flexible andpowerful programming language with a comprehensive standard library and a galaxy of third-party modules providingaccess to all kinds of APIs and software libraries.

Tangelo web services are exactly as powerful as the Python code that drives them, so Tangelo web services are verypowerful.

3.3.1 General Services

Let’s begin with a really simple example. Suppose /home/riker/tangelo_html/calc.py reads as follows:

3.3. Tangelo Web Services 11

Page 16: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

allowed = ["add", "subtract", "multiply", "divide"]

def run(operation, a=None, b=None):if a is None:

return "Parameter ’a’ is missing!"elif b is None:

return "Parameter ’b’ is missing!"

try:a = float(a)

except ValueError:return "Argument ’a’ (’%s’) must be a number!" % (a)

try:b = float(b)

except ValueError:return "Argument ’b’ (’%s’) must be a number!" % (b)

try:if operation == "add":

return a + belif operation == "subtract":

return a - belif operation == "multiply":

return a * belif operation == "divide":

return a / belse:

return "Unsupported operation: %s\nAllowed operations are: %s" % (operation, ", ".join(allowed))except ValueError:

return "Could not %s ’%s’ and ’%s’" % (operation, a, b)

This is a Python module named calc, implementing a very rudimentary four-functioncalculator in the run() function. Tangelo will respond to a request for the URLhttp://localhost:8080/~riker/calc/add?a=33&b=14 (without the trailing .py) by loadingcalc.py as a Python module, executing its run() function, and returning the result - in this case, the string 47 - asthe contents of the URL.

The run() function takes three arguments: a positional argument named operation, and two keyword argumentsnamed a and b. Tangelo maps the positional arguments to any “path elements” found after the name of the script inthe URL (in this case, add), while keyword arguments are mapped to query parameters (33 and 14 in this case). Inother words, the example URL is the equivalent of running the following short Python script:

import calcprint calc.run("add", "33", "14")

Note that all arguments are passed as strings. This is due to the way URLs and associated web technologies work -the URL itself is simply a string, so it is chunked up into tokens which are then sent to the server. These argumentsmust therefore be cast to appropriate types at run time.

Generally speaking, the web endpoints exposed by Tangelo for each Python file are not meant to be visited directly ina web browser; instead, they provide data to a web application using Ajax calls to retrieve the data. Suppose we wishto use calc.py in a web calculator application, which includes an HTML file with two fields for the user to typeinputs into, and four buttons, one for each arithmetic operation. An associated Javascript file might have code like thefollowing:

function do_arithmetic(op) {var a_val = $("#input-a").val();

12 Chapter 3. Using Tangelo

Page 17: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

var b_val = $("#input-a").val();

$.ajax({url: "calc/" + op,data: {

a: a_val,b: b_val

},dataType: "text",success: function (response) {

$("#result").text(response);}

});}

$("#plus").click(function () {do_arithmetic("add");

};

$("#minus").click(function () {do_arithmetic("subtract");

};

$("#times").click(function () {do_arithmetic("multiply");

};

$("#divide").click(function () {do_arithmetic("divide");

};

The do_arithmetic() function is called whenever the operation buttons are clicked; it contains a call to theJQuery ajax() function, which prepares a URL with query parameters then retrieves data from it. The successcallback then takes the response from the URL and places it on the webpage so the user can see the result. In this way,your web application front end can connect to the Python back end via Ajax.

Return Types

The type of the value returned from the run() function determines how Tangelo creates content for the associatedweb end point. In the example above, the function returns a number; Tangelo receives this number and turns it into astring (which is then delivered to the success callback in the Javascript code above). In general, Tangelo followsthis set of steps to determine what to do with the returned value from a Python service:

1. If the return value is a Python object containing a next() method, Tangelo stores the object in the streamingtable, and its contents can be retrieved via the streaming API (see below).

2. Otherwise, if the return value is a JSON-serializable Python object, Tangelo calls json.dumps() on it toconvert it into a string, and then delivers that string as the content.

Python’s numeric types are JSON-serializable by default, as is the value None. Lists and tuples of seri-alizable items are converted into JSON lists, while dictionaries with serializable keys and values are con-verted into JSON objects. Finally, any Python object can be made JSON-serializable by making them extendjson.JSONEncoder (see the Python documentation for more information).

If a non-JSON-serializable object is returned, this will result in a server error.

3. Otherwise, if the return value is a string, then Tangelo treats the return value as the final result; i.e., it deliversthe return value without changing it.

3.3. Tangelo Web Services 13

Page 18: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

4. Finally, if the return value somehow does not fit into any of the above steps, Tangelo will report a server error.

3.3.2 RESTful Services

Tangelo also supports the creation of REST services. Instead of placing functionality in a run() function, sucha service has one function per desired REST verb. For example, a rudimentary service to manage a collection ofdatabases might look like the following:

import tangeloimport lcarsdb

@tangelo.restfuldef get(dbname, query):

db = lcarsdb.connect("enterprise.starfleet.mil", dbname)if not db:

return Noneelse:

return db.find(query)

3.3.3 Configuration

You can optionally include a configuration file alongside the service itself. For instance, suppose we have the followingservice in autodestruct.py:

import tangeloimport starship

def run(officer=None, code=None, countdown=20*60):config = tangelo.config()

if officer is None or code is None:return { "status": "failed",

"reason": "missing officer or code argument" }

if officer != config["officer"]:return { "status": "failed",

"reason": "unauthorized" }elif code != config["code"]:

return { "status": "failed","reason": "incorrect code" }

starship.autodestruct(countdown)

return { "status": "complete","message": "Auto destruct in %d seconds!" % (countdown) }

Via the tangelo.config() function, this service attempts to match the input data against credentials stored in the modulelevel configuration, which is stored in autodestruct.json:

{"officer": "picard","code": "echo november golf alpha golf echo four seven enable"

}

The two files must have the same base name (autodestruct in this case) and be in the same location. Any time themodule for a service is loaded, the configuration file will be parsed and loaded as well. Changing either file will cause

14 Chapter 3. Using Tangelo

Page 19: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

the module to be reloaded the next time it is invoked. The tangelo.config() function returns a copy of the configurationdictionary, to prevent an errant service from updating the configuration in a persistent way. For this reason, it isadvisable to only call this function once, capturing the result in a variable, and retrieving values from it as needed.

3.3.4 Streaming

3.4 Integrating Tangelo with Other Platforms

3.4.1 Apache

3.4. Integrating Tangelo with Other Platforms 15

Page 20: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

16 Chapter 3. Using Tangelo

Page 21: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

CHAPTER 4

Command Line Utilities

4.1 tangelo

4.2 tangelo-passwd

17

Page 22: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

18 Chapter 4. Command Line Utilities

Page 23: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

CHAPTER 5

The Tangelo API

5.1 Python Web Service API

tangelo.content_type([type])Returns the content type for the current request, as a string. If type is specified, also sets the content type tothe specified string.

tangelo.log(msg[, context ])Writes a message msg to the log file. If context is supplied, it will be prepended to the message within thelog file. This function may be useful for debugging or otherwise tracking a service’s activities as it runs.

tangelo.request_path()Returns the path of the current request. This is generally the sequence of path components following the domainand port number in a URL.

tangelo.paths(paths)Augments the Python system path with the list of web directories specified in paths. Each path must be withinthe web root directory or within a user’s web home directory. For example, /~troi/libs would be al-lowed, as would /section31/common/ because both directories are subdirectories of a top-level web direc-tory - one in a user’s home directory, and the other under the web root. However, /~picard/../../libswould be illegal, since it does not refer to any file accessible via Tangelo.

This function can be used to let web services access commonly used functions that are implemented in theirown Python modules somewhere in the web filesystem.

@tangelo.restfulMarks a function in a Python service file as being part of that service’s RESTful API. This prevents accidentalexposure of unmarked support functions as part of the API, and also enables the use of arbitrary words as RESTverbs (so long as those words are also valid Python function names). An example usage might look like thefollowing, which uses a both a standard verb (“GET”) and a custom one (“NORMALIZE”).

import tangelo

@tangelo.restfuldef get(foo, bar, baz=None):

pass

@tangelo.restfuldef normalize():

pass

The decorator also has the effect of preventing accidental exposure of support functions in a RESTful service.

19

Page 24: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

Note that Tangelo automatically converts the verb used by the web client to all lowercase letters before searchingthe Python module for a matching function to call.

class tangelo.HTTPStatusCode(code[, description])Construct an HTTP status object signalling the status code given by code and a custom description of the statusgiven by description. If description is not specified, then a standard description will appear based onthe code (e.g., “Not Found” for code 404, etc.).

An HTTPStatusCode object can be returned from a Python service to cause the server to raise that codeinstead of sending back a response. This can be useful to signal situations like bad arguments, failure to find therequested object, etc.

5.2 Tangelo Javascript API

5.2.1 jQuery plugins

jQuery.landingPage(cfg)

Arguments

• cfg.specFile (string) – JSON file describing what applications will be listed on the page.

• cfg.leftColumn (string) – CSS selector for left text column

• cfg.rightColumn (string) – CSS selector for right text column

• cfg.leftExternalColumn (string) – CSS selector for left text column for external applica-tions

• cfg.rightExternalColumn (string) – CSS selector for right text column for external appli-cations

Constructs a landing page describing one or more other applications on a server. cfg.specFile points to a JSONfile containing a single object with two fields, apps and external. The apps field is a list of objects, each ofwhich has three fields: name, giving the title (and link text) for an application; path, giving the link target for theapp; and description, containing descriptive HTML text that will describe the application within the list. Theexternal field also contains a list of objects, with the following fields: name, as before; link, containing a linkto the external webpage for the project; institution, giving the name of the organization that hosts the externalproject; institution_link, giving a link target for the institution; and description, as before.

This function lists out the projects in the JSON file columnwise into two columns (specified by cfg.leftColumn,cfg.rightColumn, cfg.leftExternalColumn, and cfg.rightExternalColumn), placing links and descriptive text ap-propriately.

jQuery.controlPanel(cfg)

drawer_size()Returns the height of the drawer handle icon (for use in laying out drawer elements).

drawer_toggle(container, icon)

Arguments

• container (string) – CSS selector for the element containing the control panel drawer

• icon (string) – CSS selector for the element containing the drawer handle icon

Returns a function that can be used as the open/close callback for a control panel. The function causes the heightof the control panel element to toggle between full height (open) and zero height (closed).

jQuery.svgColorLegend(cfg)

20 Chapter 5. The Tangelo API

Page 25: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

Arguments

• cfg.legend (string) – CSS selector for SVG group element that will contain the legend

• cfg.cmap_func (function) – A colormapping function to create color patches for the legendentries

• cfg.xoffset (int) – How far, in pixels, to set the legend from the left edge of the parent SVGelement.

• cfg.yoffset (int) – How far, in pixels, to set the legend from the top edge of the parent SVGelement.

• cfg.categories (string[]) – A list of strings naming the categories represented in the legend.

• cfg.height_padding (int) – How much space, in pixels, to place between legend entries.

• cfg.width_padding (int) – How much space, in pixels, to place between a color patch andits associated label

• cfg.text_spacing (int) – How far, in pixels, to raise text labels (used to vertically center textwithin the vertical space occupied by a color patch).

• cfg.legend_margins (object) – An object with (optional) fields top, bottom, left, and right,specifying how much space, in pixels, to leave between the edge of the legend and theentries.

• cfg.clear (bool) – Whether to clear out the previous contents of the element selected bycfg.legend.

Constructs an SVG color legend in the <g> element specified by cfg.legend, mapping colors from the elementsof cfg.categories through the function cfg.cmap_func.

jQuery.navbar(cfg)

5.2.2 tangelo

tangelo.version()Returns the version as string of the form "x.y.z".

tangelo.identityThe identity function: function (d) { return d; }.

tangelo.isNumber(x)Returns true if x is a number.

tangelo.isBoolean(x)Returns true if x is a boolean.

tangelo.isArray(x)Returns true if x is an array.

tangelo.isObject(x)Returns true if x is an object.

tangelo.isString(x)Returns true if x is a string.

tangelo.accessor(spec, default)

Arguments

• spec.value – If this attribute is present, creates a function that returns the specified constantvalue.

5.2. Tangelo Javascript API 21

Page 26: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

• spec.field (string) – If this attribute is present, creates a function that returns the specifiedconstant value. The field may be dot-separated to reference nested attributes. For example,"foo.bar" will return the bar sub-attribute of the foo attribute. Passing the string "."will return the identity function.

• default – The default value returned if spec.field is not present.

Returns a function which takes an object and returns a value according to the spec.

tangelo.hasNaN(values)Returns true if any of the elements in the array values are NaN.

tangelo.appendFunction(f1, f2)Returns a new function which first calls f1 then calls f2. All arguments are passed to each function.

tangelo.requireCompatibleVersion(reqvstr)Returns true if tangelo.version() returns a version >= the version specified in reqvstr.

tangelo.getMongoRange(host, database, collection, field, callback)

Arguments

• host (string) – MongoDB hostname

• database (string) – MongoDB database on host

• collection (string) – MongoDB collection in database

• field (string) – Target field within collection

• callback (function) – Function to call on range results

Finds the two extreme values in field field of collection in database on Mongo server host, thencalls callback passing these two values as arguments.

This function could be used, for example, to find the earliest and latest events in a Mongo collection, then usethat information to set up a date selector element in the webpage.

tangelo.allDefined([arg1, ..., argN ])Returns true if all arguments are defined, and false otherwise.

class tangelo.defaults(inputSpec, callback)Constructs a key/value store object, initializing it with the information found in inputSpec.

If inputSpec is a Javascript object, its contents are used directly as the initialization data for the defaults object.Otherwise, if inputSpec is a string, it is treated as the path to a JSON file that encodes a single Javascript object- this file is loaded via ajax and its contents then used as the initialization data.

If ajax is used to load the initialization data, callback - if specified - will be invoked on the newly created defaultsobject when the ajax call finishes. This can be used to specify, for example, the continuation of the containingfunction so as to ensure that the object is created and ready when the continuation is invoked (in other words,using the callback is the asynchronous version of returning the new object directly from the call to the defaultsfunction).

The defaults object has two methods: get(key) returns the value associated to key (or undefined if key isnot present); set(key, value) associates value to key.

This object can be used to set up default configuration options for a web application. The following exampleshows one useful pattern:

tangelo.util.defaults("defaults.json", function (config) {var opt = {

color: "red",fontsize: 12

22 Chapter 5. The Tangelo API

Page 27: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

};

for (o in opt) {config.set(o, config.get(o) || opt[o]);

}

.

.

.});

This code snippet reads in values from a file and fills in hardcoded default values for anything missing in thefile. This pattern can be deployed somewhere, and the site maintainer can supply a defaults.json file tovary the default values. If the file is omitted, then the hardcoded defaults will kick in.

tangelo.uniqueID()Returns a unique string ID for use as, e.g., ids for dynamically generated html elements, etc.

class tangelo.GoogleMapSVG(elem, mapoptions, cfg, cont)

tangelo.resolve(spec, done)

5.2.3 tangelo.data

tangelo.data.tree(spec)

Arguments

• spec.data (object) – The array of nodes.

• spec.id (Accessor) – An accessor for the ID of each node in the tree.

• spec.idChild (Accessor) – An accessor for the ID of the elements of the children array.

• spec.children (Accessor) – An accessor to retrieve the array of children for a node.

Converts an array of nodes with ids and child lists into a nested tree structure. The nested treeformat with a standard children attribute is the required format for other Tangelo functions such astangelo.vis.dendrogram().

As an example, evaluating:

var tree = tangelo.data.tree({data: [

{name: "a", childNodes: [{child: "b", child: "c"}]},{name: "b", childNodes: [{child: "d"}]},{name: "c"},{name: "d"}

],id: {field: "name"},idChild: {field: "child"},children: {field: "childNodes"}

});

will return the following nested tree (note that the original childNodes attributes will also remain intact):

{name: "a",children: [

{name: "b",

5.2. Tangelo Javascript API 23

Page 28: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

children: [{

name: "d"}

]},{

name: "c"}

]}

5.2.4 tangelo.ui

tangelo.ui.html(spec)

Arguments

• spec.el (Element) – The parent DOM element.

• spec.html (string) – The HTML content string.

Appends the specified arbitrary HTML content under the specified element.

tangelo.ui.rangeslider(spec)

Arguments

• spec.el (Element) – The parent DOM element.

• spec.range (object) – An object of the form {min: minValue, max:maxValue} containing the full range of the slider. The values spec.range.min andspec.range.max must be numeric.

• spec.value (object) – An object of the form {min: minValue, max: maxValue}containing the initial selected range of the slider. The values spec.range.min andspec.range.max must be numeric.

• spec.date (boolean) – If true, display the values as if they were milliseconds since January1, 1980 (i.e. interpret as the date new Date(value)).

• spec.on.change (function) – When the slider is dragged, spec.on.change(value) iscalled with the current value of the form {min: minValue, max: maxValue}.

Creates a double-handled range slider control appended to the specified parent element.

tangelo.ui.select(spec)

Arguments

• spec.el (Element) – The parent DOM element.

• spec.data (array) – An array, one for each option in the drop-down.

• spec.id (Accessor) – The accessor for a unique identifier for each object.

• spec.label (Accessor) – The accessor for a label to be shown in the drop-down (default:spec.id).

• spec.on.change (function) – When the drop-down selection changes,spec.on.change(value) is called with the data element that was selected.

• spec.value – The identifier of the object to initially select.

24 Chapter 5. The Tangelo API

Page 29: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

Creates a drop-down selection menu (HTML <select> element) with the specified options.

5.2.5 tangelo.vis

class tangelo.vis.dendrogram(spec)

Arguments

• spec.el (Element) – The parent DOM element.

• spec.data (object) – A nested tree object where child nodes are stored in the children at-tribute.

• spec.label (Accessor) – The accessor for displaying tree node labels.

• spec.distance (Accessor) – The accessor for the numeric value of each node to its parent(default: 1).

• spec.id (Accessor) – The accessor for the node ID.

• spec.nodeLimit (int) – The maximum number of nodes to display in the dendrogram. Ifthere are more nodes in the current display, the view will hide nodes with the highest distancefrom the root.

• spec.root (object) – The root of the subtree in the current display (default: spec.data, thefull tree).

• spec.mode (string) – The current interaction mode of the tree. The "hide" mode willalternately collapse or expand clicked subtrees. The "focus" mode will set the currentlydisplayed root to the clicked node. The "label" mode will toggle the label visibility forthe clicked node.

Constructs an interactive dendrogram.

update(spec)Updates the dendrogram attributes based on the attributes set in spec. The possible content of spec matchesthe constructor options.

reset()Resets the view by expanding all collapsed nodes and resetting the root to the full tree.

download(format)Downloads the view in the specified format. Currently only the "pdf" format is supported.

class tangelo.vis.geodots(spec)

class tangelo.vis.geonodelink(spec)

class tangelo.vis.mapdots(spec)

class tangelo.vis.nodelink(spec)

class tangelo.vis.timebar(spec)

class tangelo.vis.timeline(spec)

5.2. Tangelo Javascript API 25

Page 30: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

26 Chapter 5. The Tangelo API

Page 31: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

CHAPTER 6

Tutorials

6.1 Building a Tangelo Web Application from Scratch

27

Page 32: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

28 Chapter 6. Tutorials

Page 33: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

CHAPTER 7

Information for Developers

7.1 Coding Style Guidelines

JavaScript is notorious for its mix of powerful, expressive programming constructs and its poor, sometimes brokenlanguage features. It is therefore prone to easily hidden, difficult to track programming errors. To mitigate thisproblem, Tangelo avoids many of the poor practices by using JSLint to enforce strict coding practices. JSLint is astatic analysis tool that warns about several such poor coding practices, as well as a particular stylistic convention,which is documented in this article.

Though JSLint is used as something of a gold standard, there are other conventions that JSLint has no opinion on, suchas programming patterns for implementing namespaces or constructing objects. The preferred practices for Tangeloare also listed here.

7.1.1 Code style

This section concerns written code format, with the goal of clear, readbale, and consistent code.

Indentation

Indentation is used to provide visual cues about the syntactic scope containing particular line of code. Good indentationpractice dramaticaly improves code readability.

Four-space indentation. Each additional indentation level shall be exactly four spaces.

Indentation policy. The following structures shall require incrementing the indentation level:

Statements belonging to any block.

Chained function calls:

obj.call1().call2().call3();

Properties in a literal object:

obj = {prop1: 10,prop2: 3

};

29

Page 34: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

Curly bracket placement. The left curly bracket that introduces a new indentation level shall appear at the end of theline that uses it; the right curly bracket that delimits the indented statements shall appear on the line following the lastindented statement, at the decremented indentation:

[some statement...] {^

.

.

.}^

Naming

Use camelCase for visualization, property, method, and local variable names.

Curly brackets

JavaScript uses curly brackets to delimit blocks. Blocks are required by the language when functions are defined. Theyare also required for executing more than one statement within control flow constructs such as if and while. Whilethe option exists not to use curly brackets for a single statement in such cases, that practice can lead to errors (when,e.g., a new feature requires the single statement to be replaced by several statements).

Always use blocks in control flow statements. Every use of control flow operators (if, while, do) shall use curlybrackets for its associated statement block, even if only a single statement appears therein.

Space placement

Parentheses are required in several places in JavaScript. Proper space placement can help make such constructs morereadable.

Keyword-condition separation. A single space shall appear in the following situations.

Between a control-flow operator and its parenthesized condition:

if (condition...) {^

Between a parenthesized condition and its following curly bracket:

if (condition...) {^

Between a function argument list and its following curly bracket:

function foobar(x, y, z) {^

Between the function keyword and the argument list, in anonymous functions:

f = function (a, b) {^

After every comma.

On either side of a binary operator:

30 Chapter 7. Information for Developers

Page 35: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

x = 3 + 4;^ ^

Extraneous spaces. The last character in any given line shall not be a space.

Blank lines. Blank lines should be used to set apart sequences of statements that logically belong together.

Chained if/else-if/else statements.

A common programming pattern is to test a sequence of conditions, selecting a single action to take when one of themis satisfied. In JavaScript, this is accomplished with an if block followed by a number of else if blocks, followedby an else block. try catch blocks have a similar syntax.

Single line else if, else, and catch. The else if, else, and catch keyword phrases shall appear on asingle line, with a right curly bracket on their left and a left curly bracket on their right:

if (condition) {action();

} else if {other_action();

} else {default_action();

}

new Array and new Object

The new keyword is problematic in JavaScript. If it is omitted by mistake, the code will run without error, but will notdo the right thing. Furthermore, built in constructors like Array and Object can be reimplemented by other code.

Use [] and {}. All construction of arrays and objects shall use the literal [] and {} syntax. The sequence ofstatements x = [];, then x.length = N; shall replace new Array(N).

7.1.2 Code structure

This section concerns the structure of functions and modules, how constructs at a larger scale than individual statementsand expressions should be handled.

JSLint directives

JSLint reads two special comments appearing at the top of files it is working on. The first appears in the followingform:

/*jslint browser: true */

and specifies options to JSLint. Because Tangelo is a web project, every JavaScript file should have the comment thatappears above as the first line. The other recognized directive in the global name list:

/*globals d3, $, FileReader */

This directive prevents JSLint from complaining that the listed names are global variables, or undefined. It is meantfor valid names, such as standard library objects or linked libraries used in the file.

7.1. Coding Style Guidelines 31

Page 36: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

Lexical scopes

JavaScript has only two scope levels: global and function. In particular, blocks following, e.g., for and if statementsdo not introduce an inner scope. Despite this fact, JavaScript allows for variables to be declared within such blocks,causing seasoned C and C++ programmers to assume something false about the lifetime of such variables.

Single var declaration. Every function shall contain a single var declaration as its first statement, which shall listevery local variable used by that function, listed one per line.

function foobar(){var width,

height,i;

.

.

.}

This declaration statement shall not include any initializers (this promotes clearer coding, as the “initializers” can bemoved below the declaration, and each one can retain its own comment to explain the initialization).

Global variables. Global variables shall not be used, unless as a namespace-like container for variables and namesthat would otherwise have to be global. When such namespace-like containers are used in a JavaScript file, they shallappear in the JSLint global name specifier.

Strict Mode

JavaScript has a “strict mode” that disallows certain actions technically allowed by the language. These are such thingsas using variables before they are defined, etc. It can be enabled by including "use strict"; as the first statementin any function:

function foobaz() {"use strict";...

}

Strict mode functions. All functions shall be written to use strict mode.

A note on try...catch blocks

JSLint complains if the exception name bound to a catch block is the same as the exception name bound to a previouscatch block. This is due to an ambiguity in the ECMAScript standard regarding the semantics of try...catchblocks. Because using a unique exception name in each catch block just to avoid errors from JSLint seems tointroduce just as much confusion as it avoids, the current practice is not to use unique exception names for eachcatch block.

Use e for exception name. catch blocks may all use the name e for the bound exception, to aid in scanning oversimilar messages in the JSLint output. This rule is subject to change in the future.

A note on “eval is evil”

JSLint claims that eval is evil. However, it is actually dangerous, and not evil. Accordingly, eval should be keptaway from most JavaScript code. However, to take one example, one of Tangelo’s main dependencies, Vega, makes

32 Chapter 7. Information for Developers

Page 37: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

use of compiler technology that generates JavaScript code. evaling this code is reasonable and necessary in thisinstance.

eval is misunderstood. If a JavaScript file needs to make use of eval, it shall insert an evil: true directiveinto the JSLint options list. All other JavaScript files shall not make use of eval.

7.1.3 Packaging and Object Orientation

This section concerns the highest-level expressions of packaging code into modules for external use, and how toimplement object oriented programming in JavaScript.

7.2 Tangelo System and Application Architecture

This page will discuss Tangelo’s architecture at two levels: the overall system architecture, and generally recommendedapplication architecture.

7.2.1 System architecture

The Tangelo framework is built on top of CherryPy, a Python-based web server that can serve web content from staticfiles (as a traditional web server does) or as the result of executing some Python code. Tangelo is set up to serve staticfiles from a particular directory (/web), and return the result of Python code from another (/service).

This is the major feature of the Tangelo system architecture: web pages are served from one directory, while webservices are served from another. How this distinction is used to create web applications is discussed next.

7.2.2 Application Architecture

A particular web application consists of a collection of web pages and a collection of web services. The web pagesare just HTML files with associated JavaScript or CSS files - the usual notion of a web page. On the other hand, webservices are Python functions exposed by the server as web addresses. Essentially, the server will run these functionsfor you when you visit a particular URL.

Web Services

When someone visits the URL for some web service in a web browser, the text they will see is the result of runningthe Python function. Because Python is a flexible, general purpose language with an extensive standard library, andwide support among software developers, Tangelo web services can be very powerful tools.

Web service modules are found in the /modules directory. Each service appears in a single Python file. For example,the following code might appear in a file named add.py:

import tangelo

class Handler:def go(self, a=None, b=None):

response = tangelo.empty_response()

class BreakOut:pass

try:

7.2. Tangelo System and Application Architecture 33

Page 38: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

if a == None or b == None:response["error"] = "Two arguments are required"raise BreakOut()

else:try:

a = float(a)b = float(b)

except ValueError:response["error"] = "Arguments must be numeric"raise BreakOut()

response["result"] = a + bexcept BreakOut:

pass

return tangelo.dumps(response)

After starting the server, visiting a URL like http://localhost:8080/service/add?a=5&b=10 wouldshow a response similar to the following:

{ "error": null, "result": 15 }

The tangelo.dumps() function converts a Python object to JSON, a useful format for communicating betweenthe server and client side. In this example, you can see that there was no error reported, and the sum of 5 and 10appears in the “result” field.

Of course, rather than visiting this page directly, an application writer would instead use an[Ajax](http://en.wikipedia.org/wiki/Ajax_(programming)) call to send the request and retrieve the result, per-haps something like the following:

$.ajax({url: "/service/add",data: {a: 5, b: 10},dataType: "json",success: function(response){

alert("The sum is " + response.result);}

});

This example shows how a JavaScript function might make use of the web service to display a sum. Of course, webservices in production applications will not simply add numbers together. The example Tangelo applications includeweb services that retrieve records from a Mongo database instance for use in the web page portion of the application,and one that performs “named entity recognition” using the Natural Language Toolkit Python interface.

The ability to write web services in Python is what sets Tangelo apart from an ordinary web server. They enable richweb applications by bringing the power of Python to bear on any problem you might wish to solve.

7.3 Developing Visualizations

7.3.1 Extend jQuery Widget

Tangelo visualizations are implemented as jQuery widgets. They extend the base jQuery UI widget class, but otherwisedo not need to depend on anything else from jQuery UI.

34 Chapter 7. Information for Developers

Page 39: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

7.3.2 Visualization Options

Basic Options

• data - The data associated with the visualization, normally an array.

• width, height - The width and height of the visualization, in pixels. If omitted, the visualization should resize tofit the DOM element.

Visualization Mapping Options

The following options are optional, but if your visualization is able to map data element properties to visual attributeslike size, color, and label, you should use this standard naming convention. If you have multiple sets of visual elements(such as nodes and links in a graph), prefix these attributes as appropriate (e.g. nodeSize, nodeStrokeWidth).

• size - The size of the visual element as a number of pixels. For example, if drawing a square for each dataelement, the squares should have sizes equal to the square-root of what the size option returns for each dataelement.

• color - The main color of the visual element, specified as a CSS color string.

• symbol - The symbol to use for the visual element. This should use D3’s standard set of symbol names.

• label - The label for the visual element (a string).

• stroke - The color of the stroke (outline) of the visual element specified in pixels.

• strokeWidth - The width of the stroke of the visual element in pixels.

• opacity - The opacity of the entire visual element, as a number between 0 to 1.

7.3.3 Accessor Specifications

AccessorSpec

Each visual mapping should take an AccessorSpec for a value. Accessor specifications work much like DataRef specsdo in Vega, though they also allow programmatic ways to generate arbitrary accessors and scales.

• function (d) { ... } - The most general purpose way to generate a visual mapping. The argument isthe data element and the return value is the value for the visual property.

• {value: v} - Sets the visual property to the same constant value v for all data elements.

• {field: "dot.separated.name"} - Retrieves the specified field or subfield from the data element andpasses it through the visualization’s default scale for that visual property. Unlike Vega, fields from the originaldata do not need to be prefixed by "data.". The special field name "." refers to the entire data element.

• {field: "dot.separated.name", scale: ScaleSpec} - Overrides the default scale using ascale specification. Set scale to tangelo.identity to use a field directly as the visual property.

ScaleSpec

A scale specification defines how to map data properties to visual properties. For example, if you want to color yourvisual elements using a data field continent containing values such as North America, Europe, Asia, etc. you will needa scale that maps North America to "blue", Europe to "green", etc. Vega has a number of built-in named scalesthat together define the ScaleSpec. In Tangelo, a ScaleSpec may also be an arbitrary function.

7.3. Developing Visualizations 35

Page 40: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

Tangelo Web Framework Documentation, Release 0.0

7.3.4 Callbacks

Data Callbacks

• enter

• update

• exit

Interaction Callbacks

• click

• dblclick

• mouseover

• mouseout

Behavior Callbacks

• select

• focus

• toggle

36 Chapter 7. Information for Developers

Page 41: Tangelo Web Framework DocumentationTangelo Web Framework Documentation, Release 0.0 Tangelo is a general-purpose web server framework, built on top ofCherryPy. Once it’s set up,

CHAPTER 8

Indices and tables

• genindex

• modindex

• search

37