• This repository has been archived on 14/Feb/2018
  • Stars
    star
    187
  • Rank 199,748 (Top 5 %)
  • Language
    Python
  • License
    BSD 3-Clause "New...
  • Created over 14 years ago
  • Updated almost 10 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Tinman is a Tornado support package including an application wrapper/runner and a set of handy decorators.

Tinman

Tinman adds a little more stack to Tornado. It is designed to speed development of Tornado applications. It includes an application wrapper and a toolbox of decorators and utilities.

PyPI version Downloads Build Status

0.9+ Version Warning

The configuration file syntax has changed and the structure of the package has changed. Please test your applications if you are upgrading from 0.4 or previous.

Features

  • A full featured application wrapper
  • Standard configuration for applications
  • Built-in configurable session management
  • Lightweight model system for NoSQL systems
  • Authentication Mixins for Github and StackExchange
  • A command-line tool, tinman-init that will create a skeleton app structure with the initial package and setup.py file.
  • Network address whitelisting decorator
  • Method/Function debug logging decorator
  • Handlers with automated connection setup for PostgreSQL, RabbitMQ and Redis
  • Support for a External Template Loaders including Tinman's CouchDB Template Loader
  • Flexible logging configuration allowing for custom formatters, filters handlers and setting logging levels for individual packages.
  • Built in support for NewRelic's Python agent library
  • RequestHandler output caching/memoization

Installation

Install via pip or easy_install:

pip install tinman

Module Descriptions

  • tinman
    • application: Application extends tornado.web.Application, handling the auto-loading of configuration for routes, logging, translations, etc.
    • auth: Authentication Mixins for GitHub, StackExchange, and HTTP Digest Authentication.
    • controller: Core tinman application controller.
    • couchdb: A CouchDB based template loader module
    • decorators: Authentication, memoization and whitelisting decorators.
    • exceptions: Tinman specific exceptions
    • handlers: Request handlers which may be used as the base handler or mix-ins.
      • base: Base request handlers including the SessionRequestHandler
      • mixins: Request Handlers mixins including support for Redis, RabbitMQ and Model API Request Handlers
    • model: Model system with base model class and various base model classes for supported storage backends.
    • process: Invoked by the controller, each Tinman process is tied to a specific HTTP server port.
    • session: Session object and storage mixins
    • utilities: Command line utilities

Requirements

  • helper
  • ipaddr
  • pyyaml

Optional Dependencies

  • Heapy: guppy,
  • LDAP: python-ldap,
  • MsgPack Sessions: msgpack,
  • NewRelic: newrelic>=1.12.0',
  • PostgreSQL: psycopg2,
  • RabbitMQ: pika>=0.9.13,
  • Redis: tornado-redis,
  • Redis Sessions: redis

Installing optional Dependencies

Use pip to install dependencies:

pip install 'tinman[Dependency Name]'

For example:

pip install 'tinman[RabbitMQ]'

Application Runner

The tinman application runner works off a YAML configuration file format and provides a convenient interface for running tornado applications interactively or as a daemon.

Command Line Syntax:

Usage: usage: tinman -c <configfile> [options]

Tinman adds a little more stack to Tornado

Options:
  -h, --help            show this help message and exit
  -c CONFIGURATION, --config=CONFIGURATION
                        Path to the configuration file
  -f, --foreground      Run interactively in console
  -p PATH, --path=PATH  Path to prepend to the Python system path

Example Handlers

Session

Sessions will automatically load on prepare and save on finish. If you extend the SessionHandler and need to use prepare or finish, make sure to call super(YourClass, self).prepare() and super(YourClass, self).on_finish() in your extended methods. By using the session mixins you can change the default session behavior to use different types of storage backends and serializers.

from tinman.handlers import session
from tornado import web

class Handler(session.SessionHandler):

  @web.asynchronous
  def get(self, *args, **kwargs):

      # Set a session attribute
      self._session.username = 'foo'
      self._session.your_variable = 'bar'

      self.write({'session_id': self._session.id,
                  'your_variable': self._session.your_variable})
      self.finish()

  def prepare(self):
      super(Handler, self).on_finished()
      # Do other stuff here

  def prepare(self):
      super(Handler, self).prepare()
      # Do other stuff here

Heapy

The Heapy handler uses the guppy library to inspect the memory stack of your running Tinman application, providing a JSON document back with the results. It is very slow and blocking and can take many MINUTES to complete so it should be used very sparingly and if used on a production application, with the whitelist decorator.

To use the Heapy handler, just add the route to your configuration:

  - [/heapy, tinman.handlers.heapy.HeapyRequestHandler]
Example Output

The following is a very abbreviated repport:

{
    "rows": [
        {
            "count": {
                "percent": 40,
                "value": 45068
            },
            "cumulative": {
                "percent": 29,
                "value": 4159016
            },
            "item": "types.CodeType",
            "referrers": {
                "rows": [
                    {
                        "count": {
                            "percent": 96,
                            "value": 7290
                        },
                        "cumulative": {
                            "percent": 96,
                            "value": 874800
                        },
                        "item": "function",
                        "size": {
                            "percent": 96,
                            "value": 874800
                        }
                    }
                ],
                "title": "Referrers by Kind (class / dict of class)",
                "total_bytes": 911160,
                "total_objects": 7593
            },
            "size": {
                "percent": 29,
                "value": 4159016
            }
        }
    ],
    "title": "Referrers by Kind (class / dict of class)",
    "total_bytes": 14584240,
    "total_objects": 113444
}

Configuration

Application Options

The following are the keys that are available to be used for your Tinman/Tornado application.

  • cookie_secret: A salt for signing cookies when using secure cookies
  • debug: Toggle tornado.Application's debug mode
  • login_url: Login URL when using Tornado's @authenticated decorator
  • newrelic_ini: Path to newrelic Python .ini file for enabling newrelic support
  • paths:
    • base: The root of the files for the application
    • static: The path to static files
    • templates: The path to template files
    • translations: The path to translation files
  • redis: If using tinman.handlers.redis.RedisRequestHandler to auto-connect to redis.
    • host: The redis server IP address
    • port: The port number
    • db: The database number
  • rabbitmq:
    • host: the hostname
    • port: the server port
    • virtual_host: the virtual host
    • username: the username
    • password: the password
  • session: Configuration if using tinman.handlers.session.SessionRequestHandler
    • adapter:
      • class: The classname for the adapter. One of FileSessionAdapter, RedisSessionAdapter
      • configuration: SessionAdapter specific configuration
    • cookie:
      • name: The cookie name for the session ID
    • duration: The duration in seconds for the session lifetime
  • template_loader: The python module.Class to override the default template loader with
  • transforms: A list of transformation objects to add to the application in module.Class format
  • ui_modules: Module for the UI modules classes, can be a single module, a mapping of modules (dict) or a list of modules.
  • xsrf_cookies: Enable xsrf_cookie mode for forms
  • whitelist: List of IP addresses in CIDR notation if whitelist decorator is to be used
Notes

The tinman-init script will create a skeleton Tinman directory structure for your project and create a setup.py that will put the static and template files in /usr/share/.

If you are not going to install your app as a python package, you should set a base_path so that tinman knows what directory to insert into the Python path to be able to load your request handlers and such.

HTTP Server Options

Configure the tornado.httpserver.HTTPServer with the following options:

  • no_keep_alive: Enable/Disable keep-alives
  • ports: Ports to listen to, one process per port will be spawned
  • ssl_options: SSL Options to pass to the HTTP Server
    • certfile: Path to the certificate file
    • keyfile: Path to the keyfile
    • cert_reqs: Certificicate required?
    • ca_certs: One of none, optional or required
  • xheaders: Enable X-Header support in tornado.httpserver.HTTPServer

Logging Options

Logging uses the dictConfig format as specified at

http://docs.python.org/library/logging.config.html#dictionary-schema-details

But is able to do a minimal logging config thanks to clihelper defaults. The following is the minimal logging configuration required:

Logging:
    tinman:
      handlers: [console]
      propagate: True
      formatter: verbose
      level: DEBUG
    tornado:
      handlers: [console]
      propagate: True
      formatter: verbose
      level: INFO

Route List

The route list is specified using the top-level Routes keyword. Routes consist of a list of individual route items that may consist of mulitiple items in a route tuple.

Traditional Route Tuples

The traditional route tuple, as expected by Tornado is a two or three item tuple that includes the route to match on, the python module specified Class to use to respond to requests on that route and an optional route settings dictionary.

Examples
Routes:
  - [/, myapp.Homepage]
  - [/images, tornado.web.StaticFileHandler, {'path': '/var/www/user_images'}]
Complex Regex Tuples for Tinman

In order to facilitate complex regex that does not break YAML files, Tinman supports a "re" flag in a Route tuple. If you find that your regex is breaking your route definition, insert the string "re" before the route regex.

Examples
Routes:
  -
    - re
    - /(c[a-f0-9]f[a-f0-9]{1,3}-[a-f0-9]{8}).gif
    - test.example.Pixel

Template Loader

The TemplateLoader configuration option is detailed the External Template Loading section of the document.

Example Configuration

The following is a "full" example tinman application configuration:

%YAML 1.2
---
Application:
  path:
    base: /home/foo/mywebsite
  debug: True
  xsrf_cookies: False
  wake_interval: 60
  # Any other vaidate Tornado application setting item

Daemon:
  pidfile: /tmp/myapp.pid
  user: www-data
  group: www-data

HTTPServer:
  no_keep_alive: False
  ports: [8000,8001]
  xheaders: True

Logging:
  version: 1
  formatters:
    verbose:
      format: '%(levelname) -10s %(asctime)s %(process)-6d %(processName) -20s %(name) -20s %(funcName) -25s: %(message)s'
      datefmt: '%Y-%m-%d %H:%M:%S'
    syslog:
      format: ' %(levelname)s <PID %(process)d:%(processName)s> %(name)s.%(funcName)s(): %(message)s'
  handlers:
    console:
      class: logging.StreamHandler
      debug_only: True
      formatter: verbose
    error:
      filename: /Users/gmr/Source/Tinman/logs/error.log
      class: logging.handlers.RotatingFileHandler
      maxBytes: 104857600
      backupCount: 6
      formatter: verbose
    file:
      filename: /Users/gmr/Source/Tinman/logs/tinman.log
      class: logging.handlers.RotatingFileHandler
      maxBytes: 104857600
      backupCount: 6
      formatter: verbose
    syslog:
      class: logging.handlers.SysLogHandler
      facility: local6
      address: /var/run/syslog
      formatter: syslog
  loggers:
    clihelper:
      handlers: [console]
      level: DEBUG
      propagate: True
      formatter: verbose
    tinman:
      handlers: [console, file]
      propagate: True
      formatter: verbose
      level: DEBUG
    tornado:
      handlers: [console, file]
      propagate: True
      formatter: verbose
      level: INFO
  root:
    handlers: [error]
    formatter: verbose
    level: ERROR
  disable_existing_loggers: True

Routes:
  -[/, test.example.Home]
  -
    # /c1f1-7c5d9e0f.gif
    - re
    - /(c[a-f0-9]f[a-f0-9]{1,3}-[a-f0-9]{8}).gif
    - test.example.Pixel
 -
    - .*
    - tornado.web.RedirectHandler
    - {"url": "http://www.github.com/gmr/tinman"}

Test Application

The tinman application runner has a built in test application. To see if the module is setup correctly simply run:

tinman -f

In your console you should see output similar to:

Configuration not specified, running Tinman Test Application
utils       # 247   INFO      2011-06-11 23:25:26,164  Log level set to 10
cli         # 145   INFO      2011-06-11 23:25:26,164  Starting Tinman v0.2.1 process for port 8000
cli         # 154   DEBUG     2011-06-11 23:25:26,169  All children spawned
application # 106   DEBUG     2011-06-11 23:25:26,170  Initializing route: / with tinman.test.DefaultHandler
application # 36    INFO      2011-06-11 23:25:26,171  Appending handler: ('/', <class 'tinman.test.DefaultHandler'>)
cli         # 171   INFO      2011-06-11 23:25:26,174  Starting Tornado v1.2.1 HTTPServer on port 8000
web         # 1235  INFO      2011-06-11 23:25:32,782  200 GET / (127.0.0.1) 1.24ms

You should now be able to access a test webpage on port 8000. CTRL-C will exit.

Decorators

Tinman has decorators to make web development easier.

tinman.whitelisted

Vaidates the requesting IP address against a list of ip address blocks specified in Application.settings

Example

from tinman.decorators import whitelist
from tornado import web

# Define the whitelist as part of your application settings
settings['whitelist'] = ['10.0.0.0/8',
                         '192.168.1.0/24',
                         '1.2.3.4/32']

application = Application(routes, **settings)

# Specify the decorator in each method of your RequestHandler class
# where you'd like to enforce the whitelist
class MyClass(web.RequestHandler):

  @whitelist.Whitelisted
  def get(self):
      self.write("IP was whitelisted")

In addition you may add the whitelist right into the configuration file:

Application:
  whitelist:
    - 10.0.0.0/8
    - 192.168.1.0/24
    - 1.2.3.4/32

tinman.decorators.memoize

A local in-memory cache decorator. RequestHandler class method calls are cached by name and arguments. Note that this monkey-patches the RequestHandler class on execution and will cache the total output created including all of the template rendering if there is anything. Local cache can be flushed with _tinman.decorators.memoize.flush()

Example

from tornado import web
from tinman.decorators import whitelist

class MyClass(web.RequestHandler):

   @tinman.memoize
   def get(self, content_id):
       self.write("Hello, World")

Modules

CouchDB Loader

Tinman includes tinman.loaders.couchdb.CouchDBLoader to enable the storage of templates in CouchDB to provide a common stemplate storage mechanism across multiple servers.

Templates stored in CouchDB are stored with the full path as the document key and the template value is stored in the document using the key "template"

When storing templates in CouchDB it is important that the forward-slash (/) is replaced with a colon (:) as the key value in CouchDB, or it will not find the stored file.

For example a template with a filesystem path of /foo/bar/template.html would be stored with a key of foo:bar:template.html in CouchDB but still referenced as /foo/bar/template.html everywhere else.

Example templates document from CouchDB

{
   "_id": "base.html",
   "_rev": "1-18d104181a15f617a929c221d01423da",
   "template": "<html>\n  <head>\n    <title>{% block \"title\" %}Title{% end %}</title>\n  </head>\n  <body>\n    <h1>Hello, World!</h1>\n  </body>\n</html>"
},
{
   "_id": "pages:home.html",
   "_rev": "2-c3c06f5a6d6a7b8149e0a700c67aeb41",
   "template": "{%  extends \"base.html\" %} \n{% block title %}Homepage{% end %}"
}

More Repositories

1

consulate

Python client for the Consul HTTP API
Python
342
star
2

pgsql-listen-exchange

RabbitMQ Exchange that publishes messages received from PostgreSQL Notifications.
Erlang
277
star
3

queries

PostgreSQL database access simplified
Python
259
star
4

rabbitpy

A pure python, thread-safe, minimalistic and pythonic RabbitMQ client library
Python
243
star
5

RabbitMQ-in-Depth

Examples and materials for RabbitMQ in Depth
Python
132
star
6

flatdict

Python module for interacting with nested dicts as a single level dict with delimited keys.
Python
109
star
7

env-aws-params

Inject AWS SSM Parameters as Environment Variables
Go
84
star
8

rejected

rejected is a consumer framework for RabbitMQ
Python
58
star
9

pamqp

Low level AMQP frame encoding and decoding library
Python
52
star
10

rabbitmq-flume-plugin

A Flume plugin that provides a RabbitMQ Source and Sink
Java
48
star
11

pycon2013-logging

Examples from my "Become a Logging Expert in 30 Minutes" talk at PyCon 2013
Python
48
star
12

glyphicons-sprite-generator

The GLYPHICONS Sprite Generator allows you to change the size and colors of the Bootstap icons using the Free or Pro versions of GLYPHICONS.
Python
47
star
13

rabbitmq-pulse

rabbitmq-pulse is a RabbitMQ plugin that publishes node and queue information, pushing stats instead of polling the Management API
Erlang
45
star
14

tornado-elasticsearch

Extends the official Elasticsearch Python API adding Tornado AsyncHTTPClient support
Python
38
star
15

influxdb-storage-exchange

Post JSON structured event messages to InfluxDB
Erlang
33
star
16

alpine-rabbitmq-autocluster

RabbitMQ image with the autocluster plugin
32
star
17

email-normalize

Return a normalized email-address stripping ISP specific behaviors
Python
30
star
18

On-Rabbits-and-Elephants

Code for my lightning talk at pgCon 2011
Python
29
star
19

helper

Development library for quickly writing configurable applications and daemons.
Python
27
star
20

pgdumplib

Python3 library for reading and writing pg_dump files using the custom format
Python
26
star
21

statelessd

statelessd is a stateless HTTP to AMQP publishing gateway prototype in Python
Python
25
star
22

srvlookup

A small wrapper for dnspython to return SRV records for a given host, protocol, and domain name as a list of namedtuples
Python
23
star
23

kvpbench

Key-Value Store Benchmark Application
Python
23
star
24

passport

Passport generates templated configuration files using Consul's Service Discovery and Key/Value database tools
Python
22
star
25

aiorabbit

An AsyncIO RabbitMQ client for Python 3
Python
21
star
26

tredis

An asynchronous Redis client for Tornado
Python
20
star
27

hockeyapp

Python Client for the HockeyApp.net API
Python
19
star
28

mredis

MRedis is a multi-server wrapper for the excellent Python Redis client.
Python
19
star
29

progrock

A multi-progressbar implementation to complement multiprocessing.Process.
Python
18
star
30

pg-statsd

pg_statsd is a set of PostgreSQL user-defined functions that provide and interface to statsd.
C
15
star
31

strftimerl

Erlang implementation of strftime
Erlang
14
star
32

urilib

A RFC-3986 URI Library for parsing and building URIs
Erlang
13
star
33

infoblox

A python library for interfacing with Infoblox NIOS.
Python
12
star
34

huesos-de-vaquero

A skeleton project for web development using Cowboy (Erlang) for back-end development and Google Web-Starter-Kit for front-end development
Erlang
12
star
35

tornado-aws

A low-level Amazon Web Services API client for Tornado
Python
12
star
36

mikkoo

Mikkoo is a PgQ to RabbitMQ Relay
Python
11
star
37

houston

Easy docker stack deployment to CoreOS clusters using Fleet and Consul
Python
11
star
38

framewerk

Framewerk is a PHP5 OO Framework
PHP
10
star
39

alpine-pgbouncer

Minimalistic Alpine Linux pgBouncer container
Shell
8
star
40

httpbl

Python client library for the project-honeypot.org Http:BL API
Python
8
star
41

cardiff

Cardiff is an extendible statsd clone written in Python that supports all statsd metric types and a variety of configurable stats destinations.
Python
8
star
42

fluent-plugin-json-in-json

Fluentd parser plugin that parses JSON attributes with JSON strings in them
Ruby
7
star
43

pgpasslib

Library for getting passwords from a PostgreSQL Password file
Python
7
star
44

erlln

Example Erlang OTP application that listens for PostgreSQL NOTIFY messages
Erlang
7
star
45

conserl

Erlang client for Consul
Erlang
6
star
46

mgmt-stress

A RabbitMQ stress-testing tool
Erlang
6
star
47

ossicons

An icon font for popular Open Source project logos
HTML
5
star
48

privatepaste

v2 of PrivatePaste.com
Erlang
5
star
49

python-tornado.tmbundle

A TextMate 2 Bundle for Tornado
5
star
50

alpine-postgres

gavinmroy/alpine-postgres is a Docker image with a small disk footprint for PostgreSQL
Shell
5
star
51

dynamodb-backup

CLI utility for backing up DynamoDB to Avro containers
Python
4
star
52

pgsql-utilities

A collection of PostgreSQL utilities
PHP
4
star
53

logging-config

A wrapper class for the Python standard logging module
Python
4
star
54

fleetpy

An opinionated fleet API client for Python
Python
4
star
55

rabbitmq-sns-plugin

RabbitMQ plugin for AWS SNS interoperability
Makefile
4
star
56

golconde

Golconde (gŏl-kŏn'dΙ™) is a queue based data-distribution solution for PostgreSQL written in Python 2.6.
Python
4
star
57

rabbitstew

A command-line tool for publishing messages to RabbitMQ
Python
4
star
58

couchclient

A light-weight, read-only CouchDB client
Python
4
star
59

pglifecycle

A PostgreSQL schema management tool
Python
3
star
60

rmq-node-report

A small set of scripts to gather information from a local RabbitMQ node
Erlang
3
star
61

pgparse

Python wrapper for libpg_query
Python
3
star
62

alpine-rabbitmq

RabbitMQ image with a small disk footprint
3
star
63

PyCon-2012-Tornado-IOLoop-Talk-Examples

Examples from my 2012 PyCon talk: "More than just a pretty web framework, the Tornado IOLoop"
Python
3
star
64

elmer

Elmer allows granular monitoring of RabbitMQ queues with Nagios and other monitoring tools using custom queue arguments.
Erlang
3
star
65

menwith

Menwith is a memcache text protocol command utilization analysis tool.
Python
3
star
66

http-exchange

RabbitMQ exchange for stateless publishing over HTTP
Erlang
3
star
67

rmq-cluster-rebalance

CLI application for rebalancing queues in a RabbitMQ cluster
Python
3
star
68

alpine-statsd

A statsd container with a small disk footprint
3
star
69

github-issue-autoresponder

Check GitHub projects periodically for new issues and automatically comment or label them based upon string matching rules
Python
3
star
70

boxcar

An experimental OS/X app for interfacing with Vagrant
Objective-C
3
star
71

rabbitmq-in-depth-cookbook

Cookbook used by Vagrant when setting up the RabbitMQ in Depth VM
Python
2
star
72

pgdumpreport

Create reports from pg_dump archives
JavaScript
2
star
73

cowboy-bones-gutenberg-generator

An #Erlang Cowboy web app Gutenberg generator with i18n, templating, and more
Erlang
2
star
74

httpc-aws

A light-weight, relatively unopinionated AWS API client for Erlang
Erlang
2
star
75

tdns

An asynchronous Tornado pycares DNS client wrapper
Python
2
star
76

rabbitmq-management-ui-prototype

A ReactJS RabbitMQ Management UI Prototype
TypeScript
2
star
77

hashicorp-packaging

Makefile and templates for creating deb packages for HashiCorp (and ecosystem) projects.
Makefile
2
star
78

formulary

Easy management of AWS Cloud Formation stacks
Python
2
star
79

alpine-redis

Redis image with a small disk footprint
Dockerfile
2
star
80

ecs-pipeline-deploy

An opinionated deployment application for ECS services
Python
2
star
81

rabbitmq-pagerduty

A RabbitMQ monitoring plugin for triggering PagerDuty alerts
Erlang
2
star
82

pg-graph-dump

Dependency graph based dump and reload of PostgreSQL DDL
Erlang
2
star
83

ppp-loan-data

PPP FOIA Data
2
star
84

pgpretty

A Postgres SQL Formatter
Python
1
star
85

mdnserl

Erlang library for providing RFC-6762 multicast-DNS announcement and discovery
Erlang
1
star
86

rmq-definitions

Deterministically sort and format RabbitMQ definition backups
Python
1
star
87

ssm-ps-template

Command line application to render templates with data from SSM Parameter Store
Python
1
star
88

telegraf-pgbouncer

pgBouncer Stats Collector for Telegraf
Python
1
star
89

estuary

Accumulates Avro datum received via RabbitMQ messages and stores them in Avro container files
Erlang
1
star
90

s3-config-overlay

Fetch config from amazon S3 for other containers
Shell
1
star
91

remy

Remy is a tool for managing Chef repositories and automating the addition and management of cookbooks with a chef server using Jenkins and GitHub.
Python
1
star
92

topological

Python3 library of topological sorting algorithms
Python
1
star
93

tornado-dynamodb

Deprecated for sprockets.clients.dynamodb
Python
1
star
94

google-apps-for-domains-utilities

Small python utilities for managing Google Apps for Domains accounts
Python
1
star
95

apiary

JavaScript
1
star
96

tornado-template-gen

This application uses the Tornado Template module to generate static HTML files while still making available a subset of the Tornado template methods like static_url.
Python
1
star
97

rabbitmq-aws

A RabbitMQ Plugin fork of httpc-aws - Now @ rabbitmq/rabbitmq-aws
Erlang
1
star