From d6c081302e14e4148159fbd81b24ae9447a2fede Mon Sep 17 00:00:00 2001 From: Fergal Moran Date: Fri, 7 Jan 2011 17:52:03 +0000 Subject: [PATCH] Files added --- __init__.py | 0 app.yaml | 11 + auth/__init__.py | 0 auth/rpxtokenurl.py | 34 + bottle.py | 2219 +++++++++++++++++ gae_index.py | 24 + html/index.html | 166 ++ html/qrcode.html | 124 + html/qrcode.png | Bin 0 -> 4287 bytes html/style.css | 27 + index.py | 82 + model/__init__.py | 0 model/controller.py | 9 + model/user.py | 27 + qrmaker/QRMaker.py | 46 + qrmaker/QRPageHandler.py | 7 + qrmaker/__init__.py | 0 qrmaker/pygooglechart.py | 1161 +++++++++ .../07968d7c-1a57-11e0-b3ab-001ec9ff1126.png | Bin 0 -> 2318 bytes .../0891e970-19cf-11e0-a16e-001ec9ff1126.png | Bin 0 -> 1381 bytes .../322fcf7a-1a53-11e0-8a59-001ec9ff1126.png | Bin 0 -> 1405 bytes .../3526ee82-19ce-11e0-ab4b-001ec9ff1126.png | Bin 0 -> 1381 bytes .../3582b2e6-1a53-11e0-8a59-001ec9ff1126.png | Bin 0 -> 1381 bytes .../3ba09c50-19cd-11e0-b1fb-001ec9ff1126.png | Bin 0 -> 1381 bytes .../4318653c-1a57-11e0-92f9-001ec9ff1126.png | Bin 0 -> 2661 bytes .../519ad578-19cf-11e0-b288-001ec9ff1126.png | Bin 0 -> 1381 bytes .../6ef91b96-1a53-11e0-97bd-001ec9ff1126.png | Bin 0 -> 1390 bytes .../a69fb7ae-1a52-11e0-8a59-001ec9ff1126.png | Bin 0 -> 1405 bytes .../ca163ebc-19ce-11e0-a16e-001ec9ff1126.png | Bin 0 -> 1381 bytes .../e0a25cc6-19cc-11e0-8480-001ec9ff1126.png | Bin 0 -> 1381 bytes static/images/favicon.ico | Bin 0 -> 318 bytes .../0891e970-19cf-11e0-a16e-001ec9ff1126.png | Bin 0 -> 1381 bytes .../3ba09c50-19cd-11e0-b1fb-001ec9ff1126.png | Bin 0 -> 1381 bytes .../519ad578-19cf-11e0-b288-001ec9ff1126.png | Bin 0 -> 1381 bytes .../ca163ebc-19ce-11e0-a16e-001ec9ff1126.png | Bin 0 -> 1381 bytes static/images/qrcode.png | Bin 0 -> 1387 bytes test.py | 4 + views/css/blue.uni-form.css | 149 ++ views/css/dark.uni-form.css | 137 + views/css/default.uni-form.css | 153 ++ views/css/ready.uni-form.css | 155 ++ views/css/uni-form.css | 164 ++ views/js/uni-form-validation.jquery.js | 607 +++++ views/js/uni-form.jquery.js | 101 + views/qrcode.tpl | 144 ++ views/qrform.tpl | 167 ++ 46 files changed, 5718 insertions(+) create mode 100644 __init__.py create mode 100644 app.yaml create mode 100644 auth/__init__.py create mode 100644 auth/rpxtokenurl.py create mode 100755 bottle.py create mode 100644 gae_index.py create mode 100644 html/index.html create mode 100644 html/qrcode.html create mode 100644 html/qrcode.png create mode 100644 html/style.css create mode 100644 index.py create mode 100644 model/__init__.py create mode 100644 model/controller.py create mode 100644 model/user.py create mode 100644 qrmaker/QRMaker.py create mode 100644 qrmaker/QRPageHandler.py create mode 100644 qrmaker/__init__.py create mode 100644 qrmaker/pygooglechart.py create mode 100644 static/cache/07968d7c-1a57-11e0-b3ab-001ec9ff1126.png create mode 100644 static/cache/0891e970-19cf-11e0-a16e-001ec9ff1126.png create mode 100644 static/cache/322fcf7a-1a53-11e0-8a59-001ec9ff1126.png create mode 100644 static/cache/3526ee82-19ce-11e0-ab4b-001ec9ff1126.png create mode 100644 static/cache/3582b2e6-1a53-11e0-8a59-001ec9ff1126.png create mode 100644 static/cache/3ba09c50-19cd-11e0-b1fb-001ec9ff1126.png create mode 100644 static/cache/4318653c-1a57-11e0-92f9-001ec9ff1126.png create mode 100644 static/cache/519ad578-19cf-11e0-b288-001ec9ff1126.png create mode 100644 static/cache/6ef91b96-1a53-11e0-97bd-001ec9ff1126.png create mode 100644 static/cache/a69fb7ae-1a52-11e0-8a59-001ec9ff1126.png create mode 100644 static/cache/ca163ebc-19ce-11e0-a16e-001ec9ff1126.png create mode 100644 static/cache/e0a25cc6-19cc-11e0-8480-001ec9ff1126.png create mode 100755 static/images/favicon.ico create mode 100644 static/images/permalinked/0891e970-19cf-11e0-a16e-001ec9ff1126.png create mode 100644 static/images/permalinked/3ba09c50-19cd-11e0-b1fb-001ec9ff1126.png create mode 100644 static/images/permalinked/519ad578-19cf-11e0-b288-001ec9ff1126.png create mode 100644 static/images/permalinked/ca163ebc-19ce-11e0-a16e-001ec9ff1126.png create mode 100644 static/images/qrcode.png create mode 100644 test.py create mode 100755 views/css/blue.uni-form.css create mode 100755 views/css/dark.uni-form.css create mode 100755 views/css/default.uni-form.css create mode 100755 views/css/ready.uni-form.css create mode 100755 views/css/uni-form.css create mode 100755 views/js/uni-form-validation.jquery.js create mode 100755 views/js/uni-form.jquery.js create mode 100644 views/qrcode.tpl create mode 100644 views/qrform.tpl diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app.yaml b/app.yaml new file mode 100644 index 0000000..f24e37b --- /dev/null +++ b/app.yaml @@ -0,0 +1,11 @@ +application: qrconvert +version: 1 +runtime: python +api_version: 1 + +handlers: +- url: /html + static_dir: html + +- url: /.* + script: index.py diff --git a/auth/__init__.py b/auth/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/auth/rpxtokenurl.py b/auth/rpxtokenurl.py new file mode 100644 index 0000000..8b6c30a --- /dev/null +++ b/auth/rpxtokenurl.py @@ -0,0 +1,34 @@ +import logging +import urllib +import urllib2 +import json +import pdb + +def rpx_response(token): + api_params = { + 'token': token, + 'apiKey': 'e58e8ad7f740831452c51e3ad40b80eba388a551', + 'format': 'json', + } + + # make the api call + http_response = urllib2.urlopen( + 'https://rpxnow.com/api/v2/auth_info', + urllib.urlencode(api_params)) + + # read the json response + auth_info_json = http_response.read() + + # Step 3) process the json response + auth_info = json.loads(auth_info_json) + + # Step 4) use the response to sign the user in + if auth_info['stat'] == 'ok': + logging.debug( 'Signed in succesfully' ) + return auth_info + else: + logging.debug( 'An error occured: ' + auth_info['err']['msg'] ) + return 'An error occured: ' + auth_info['err']['msg'] + + + diff --git a/bottle.py b/bottle.py new file mode 100755 index 0000000..8fbaede --- /dev/null +++ b/bottle.py @@ -0,0 +1,2219 @@ +# -*- coding: utf-8 -*- +""" +Bottle is a fast and simple micro-framework for small web applications. It +offers request dispatching (Routes) with url parameter support, templates, +a built-in HTTP Server and adapters for many third party WSGI/HTTP-server and +template engines - all in a single file and with no dependencies other than the +Python Standard Library. + +Homepage and documentation: http://bottle.paws.de/ + +Copyright (c) 2010, Marcel Hellkamp. +License: MIT (see LICENSE.txt for details) +""" + +from __future__ import with_statement + +__author__ = 'Marcel Hellkamp' +__version__ = '0.9.dev' +__license__ = 'MIT' + +import base64 +import cgi +import email.utils +import functools +import hmac +import httplib +import itertools +import mimetypes +import os +import re +import subprocess +import sys +import tempfile +import thread +import threading +import time +import warnings + +from Cookie import SimpleCookie +from tempfile import TemporaryFile +from traceback import format_exc +from urllib import quote as urlquote +from urlparse import urlunsplit, urljoin + +try: from collections import MutableMapping as DictMixin +except ImportError: # pragma: no cover + from UserDict import DictMixin + +try: from urlparse import parse_qs +except ImportError: # pragma: no cover + from cgi import parse_qs + +try: import cPickle as pickle +except ImportError: # pragma: no cover + import pickle + +try: from json import dumps as json_dumps +except ImportError: # pragma: no cover + try: from simplejson import dumps as json_dumps + except ImportError: # pragma: no cover + try: from django.utils.simplejson import dumps as json_dumps + except ImportError: # pragma: no cover + json_dumps = None + +if sys.version_info >= (3,0,0): # pragma: no cover + # See Request.POST + from io import BytesIO + from io import TextIOWrapper + class NCTextIOWrapper(TextIOWrapper): + ''' Garbage collecting an io.TextIOWrapper(buffer) instance closes the + wrapped buffer. This subclass keeps it open. ''' + def close(self): pass + def touni(x, enc='utf8'): + """ Convert anything to unicode """ + return str(x, encoding=enc) if isinstance(x, bytes) else str(x) +else: + from StringIO import StringIO as BytesIO + bytes = str + NCTextIOWrapper = None + def touni(x, enc='utf8'): + """ Convert anything to unicode """ + return x if isinstance(x, unicode) else unicode(str(x), encoding=enc) + +def tob(data, enc='utf8'): + """ Convert anything to bytes """ + return data.encode(enc) if isinstance(data, unicode) else bytes(data) + +# Convert strings and unicode to native strings +if sys.version_info >= (3,0,0): + tonat = touni +else: + tonat = tob +tonat.__doc__ = """ Convert anything to native strings """ + + +# Backward compatibility +def depr(message, critical=False): + if critical: raise DeprecationWarning(message) + warnings.warn(message, DeprecationWarning, stacklevel=3) + + +# Small helpers + +def makelist(data): + if isinstance(data, (tuple, list, set, dict)): return list(data) + elif data: return [data] + else: return [] + + +class cached_property(object): + """ Decorator to create properties that are computed only once per instance + and then saved as normal attributes. Works for any new-style classes + with a __dict__ (no slots). """ + def __init__(self, func, name=None, doc=None): + self.__name__ = name or func.__name__ + self.__doc__ = doc or func.__doc__ + self.__module__ = func.__module__ + self.func = func + def __get__(self, obj, type=None): + if obj is None: return self + value = obj.__dict__[self.__name__] = self.func(obj) + return value + + + +############################################################################### +# Exceptions and Events ######################################################## +############################################################################### + +class BottleException(Exception): + """ A base class for exceptions used by bottle. """ + pass + + +class HTTPResponse(BottleException): + """ Used to break execution and immediately finish the response """ + def __init__(self, output='', status=200, header=None): + super(BottleException, self).__init__("HTTP Response %d" % status) + self.status = int(status) + self.output = output + self.headers = HeaderDict(header) if header else None + + def apply(self, response): + if self.headers: + for key, value in self.headers.iterallitems(): + response.headers[key] = value + response.status = self.status + + +class HTTPError(HTTPResponse): + """ Used to generate an error page """ + def __init__(self, code=500, output='Unknown Error', exception=None, traceback=None, header=None): + super(HTTPError, self).__init__(output, code, header) + self.exception = exception + self.traceback = traceback + + def __repr__(self): + return template(ERROR_PAGE_TEMPLATE, e=self) + + + + + + +############################################################################### +# Routing ###################################################################### +############################################################################### + +class RouteError(BottleException): + """ This is a base class for all routing related exceptions """ + + +class RouteSyntaxError(RouteError): + """ The route parser found something not supported by this router """ + + +class RouteBuildError(RouteError): + """ The route could not been built """ + + +class Route(object): + ''' Represents a single route and can parse the dynamic route syntax ''' + syntax = re.compile(r'(?' % part if part else '(?:' + else: out += '%s)' % (part or self.default) + return out + + def flat_re(self): + ''' Return a regexp pattern with non-grouping parentheses ''' + rf = lambda m: m.group(0) if len(m.group(1)) % 2 else m.group(1) + '(?:' + return re.sub(r'(\\*)(\(\?P<[^>]*>|\((?!\?))', rf, self.group_re()) + + def format_str(self): + ''' Return a format string with named fields. ''' + out, c = '', 0 + for i, part in enumerate(self.tokens): + if i%3 == 0: out += part.replace('\\:',':').replace('%','%%') + elif i%3 == 1: + if not part: part = 'anon%d' % c; c+=1 + out += '%%(%s)s' % part + return out + + @property + def static(self): + return len(self.tokens) == 1 + + def __repr__(self): + return "" % repr(self.realroute) + + def __eq__(self, other): + return (self.realroute) == (other.realroute) + + +class Router(object): + ''' A route associates a string (e.g. URL) with an object (e.g. function) + Some dynamic routes may extract parts of the string and provide them as + a dictionary. This router matches a string against multiple routes and + returns the associated object along with the extracted data. + ''' + + def __init__(self): + self.routes = [] # List of all installed routes + self.named = {} # Cache for named routes and their format strings + self.static = {} # Cache for static routes + self.dynamic = [] # Search structure for dynamic routes + self.compiled = False + + def add(self, route, target=None, **ka): + """ Add a route->target pair or a :class:`Route` object to the Router. + Return the Route object. See :class:`Route` for details. + """ + if not isinstance(route, Route): + route = Route(route, target, **ka) + if self.get_route(route): + return RouteError('Route %s is not uniqe.' % route) + self.routes.append(route) + self.compiled, self.named, self.static, self.dynamic = False, {}, {}, [] + return route + + def get_route(self, route, target=None, **ka): + ''' Get a route from the router by specifying either the same + parameters as in :meth:`add` or comparing to an instance of + :class:`Route`. Note that not all parameters are considered by the + compare function. ''' + if not isinstance(route, Route): + route = Route(route, **ka) + for known in self.routes: + if route == known: + return known + return None + + def match(self, uri): + ''' Match an URI and return a (target, urlargs) tuple ''' + if uri in self.static: + return self.static[uri], {} + for combined, subroutes in self.dynamic: + match = combined.match(uri) + if not match: continue + target, args_re = subroutes[match.lastindex - 1] + args = args_re.match(uri).groupdict() if args_re else {} + return target, args + if not self.compiled: # Late check to reduce overhead on hits + self.compile() # Compile and try again. + return self.match(uri) + return None, {} + + def build(self, _name, **args): + ''' Build an URI out of a named route and values for the wildcards. ''' + try: + return self.named[_name] % args + except KeyError, e: + if not self.compiled: # Late check to reduce overhead on hits + self.compile() # Compile and try again. + return self.build(_name, **args) + if _name not in self.named: + raise RouteBuildError("No route found with name '%s'." % _name) + raise RouteBuildError("Missing argument: %s." % e.args[0]) + + def compile(self): + ''' Build the search structures. Call this before actually using the + router.''' + self.named = {} + self.static = {} + self.dynamic = [] + for route in self.routes: + if route.name: + self.named[route.name] = route.format_str() + if route.static: + self.static[route.route] = route.target + continue + gpatt = route.group_re() + fpatt = route.flat_re() + try: + gregexp = re.compile('^(%s)$' % gpatt) if '(?P' in gpatt else None + combined = '%s|(^%s$)' % (self.dynamic[-1][0].pattern, fpatt) + self.dynamic[-1] = (re.compile(combined), self.dynamic[-1][1]) + self.dynamic[-1][1].append((route.target, gregexp)) + except (AssertionError, IndexError), e: # AssertionError: Too many groups + self.dynamic.append((re.compile('(^%s$)'%fpatt), + [(route.target, gregexp)])) + except re.error, e: + raise RouteSyntaxError("Could not add Route: %s (%s)" % (route, e)) + self.compiled = True + + def __eq__(self, other): + return self.routes == other.routes + + + + + + +############################################################################### +# Application Object ########################################################### +############################################################################### + +class Bottle(object): + """ WSGI application """ + + def __init__(self, catchall=True, autojson=True, config=None): + """ Create a new bottle instance. + You usually don't do that. Use `bottle.app.push()` instead. + """ + self.routes = Router() + self.mounts = {} + self.error_handler = {} + self.catchall = catchall + self.config = config or {} + self.serve = True + self.castfilter = [] + if autojson and json_dumps: + self.add_filter(dict, dict2json) + self.hooks = {'before_request': [], 'after_request': []} + + def optimize(self, *a, **ka): + depr("Bottle.optimize() is obsolete.") + + def mount(self, app, script_path): + ''' Mount a Bottle application to a specific URL prefix ''' + if not isinstance(app, Bottle): + raise TypeError('Only Bottle instances are supported for now.') + script_path = '/'.join(filter(None, script_path.split('/'))) + path_depth = script_path.count('/') + 1 + if not script_path: + raise TypeError('Empty script_path. Perhaps you want a merge()?') + for other in self.mounts: + if other.startswith(script_path): + raise TypeError('Conflict with existing mount: %s' % other) + @self.route('/%s/:#.*#' % script_path, method="ANY") + def mountpoint(): + request.path_shift(path_depth) + return app.handle(request.path, request.method) + self.mounts[script_path] = app + + def add_filter(self, ftype, func): + ''' Register a new output filter. Whenever bottle hits a handler output + matching `ftype`, `func` is applied to it. ''' + if not isinstance(ftype, type): + raise TypeError("Expected type object, got %s" % type(ftype)) + self.castfilter = [(t, f) for (t, f) in self.castfilter if t != ftype] + self.castfilter.append((ftype, func)) + self.castfilter.sort() + + def match_url(self, path, method='GET'): + """ Find a callback bound to a path and a specific HTTP method. + Return (callback, param) tuple or raise HTTPError. + method: HEAD falls back to GET. All methods fall back to ANY. + """ + path, method = path.strip().lstrip('/'), method.upper() + callbacks, args = self.routes.match(path) + if not callbacks: + raise HTTPError(404, "Not found: " + path) + if method in callbacks: + return callbacks[method], args + if method == 'HEAD' and 'GET' in callbacks: + return callbacks['GET'], args + if 'ANY' in callbacks: + return callbacks['ANY'], args + allow = [m for m in callbacks if m != 'ANY'] + if 'GET' in allow and 'HEAD' not in allow: + allow.append('HEAD') + raise HTTPError(405, "Method not allowed.", + header=[('Allow',",".join(allow))]) + + def get_url(self, routename, **kargs): + """ Return a string that matches a named route """ + scriptname = request.environ.get('SCRIPT_NAME', '').strip('/') + '/' + location = self.routes.build(routename, **kargs).lstrip('/') + return urljoin(urljoin('/', scriptname), location) + + def route(self, path=None, method='GET', no_hooks=False, decorate=None, + template=None, template_opts={}, callback=None, **kargs): + """ Decorator: Bind a callback function to a request path. + + :param path: The request path or a list of paths to listen to. See + :class:`Router` for syntax details. If no path is specified, it + is automatically generated from the callback signature. See + :func:`yieldroutes` for details. + :param method: The HTTP method (POST, GET, ...) or a list of + methods to listen to. (default: GET) + :param decorate: A decorator or a list of decorators. These are + applied to the callback in reverse order. + :param no_hooks: If true, application hooks are not triggered + by this route. (default: False) + :param template: The template to use for this callback. + (default: no template) + :param template_opts: A dict with additional template parameters. + :param static: If true, all paths are static even if they contain + dynamic syntax tokens. (default: False) + :param name: The name for this route. (default: None) + :param callback: If set, the route decorator is directly applied + to the callback and the callback is returned instead. This + equals ``Bottle.route(...)(callback)``. + """ + # @route can be used without any parameters + if callable(path): path, callback = None, path + # Build up the list of decorators + decorators = makelist(decorate) + if template: decorators.insert(0, view(template, **template_opts)) + if not no_hooks: decorators.append(self._add_hook_wrapper) + def wrapper(func): + callback = func + for decorator in reversed(decorators): + callback = decorator(callback) + functools.update_wrapper(callback, func) + for route in makelist(path) or yieldroutes(func): + for meth in makelist(method): + route = route.strip().lstrip('/') + meth = meth.strip().upper() + old = self.routes.get_route(route, **kargs) + if old: + old.target[meth] = callback + else: + self.routes.add(route, {meth: callback}, **kargs) + return func + return wrapper(callback) if callback else wrapper + + def _add_hook_wrapper(self, func): + ''' Add hooks to a callable. See #84 ''' + @functools.wraps(func) + def wrapper(*a, **ka): + for hook in self.hooks['before_request']: hook() + response.output = func(*a, **ka) + for hook in self.hooks['after_request']: hook() + return response.output + return wrapper + + def get(self, path=None, method='GET', **kargs): + """ Decorator: Bind a function to a GET request path. + See :meth:'route' for details. """ + return self.route(path, method, **kargs) + + def post(self, path=None, method='POST', **kargs): + """ Decorator: Bind a function to a POST request path. + See :meth:'route' for details. """ + return self.route(path, method, **kargs) + + def put(self, path=None, method='PUT', **kargs): + """ Decorator: Bind a function to a PUT request path. + See :meth:'route' for details. """ + return self.route(path, method, **kargs) + + def delete(self, path=None, method='DELETE', **kargs): + """ Decorator: Bind a function to a DELETE request path. + See :meth:'route' for details. """ + return self.route(path, method, **kargs) + + def error(self, code=500): + """ Decorator: Register an output handler for a HTTP error code""" + def wrapper(handler): + self.error_handler[int(code)] = handler + return handler + return wrapper + + def hook(self, name): + """ Return a decorator that adds a callback to the specified hook. """ + def wrapper(func): + self.add_hook(name, func) + return func + return wrapper + + def add_hook(self, name, func): + ''' Add a callback from a hook. ''' + if name not in self.hooks: + raise ValueError("Unknown hook name %s" % name) + if name in ('after_request'): + self.hooks[name].insert(0, func) + else: + self.hooks[name].append(func) + + def remove_hook(self, name, func): + ''' Remove a callback from a hook. ''' + if name not in self.hooks: + raise ValueError("Unknown hook name %s" % name) + self.hooks[name].remove(func) + + def handle(self, url, method): + """ Execute the handler bound to the specified url and method and return + its output. If catchall is true, exceptions are catched and returned as + HTTPError(500) objects. """ + if not self.serve: + return HTTPError(503, "Server stopped") + try: + handler, args = self.match_url(url, method) + return handler(**args) + except HTTPResponse, e: + return e + except Exception, e: + if isinstance(e, (KeyboardInterrupt, SystemExit, MemoryError))\ + or not self.catchall: + raise + return HTTPError(500, 'Unhandled exception', e, format_exc(10)) + + def _cast(self, out, request, response, peek=None): + """ Try to convert the parameter into something WSGI compatible and set + correct HTTP headers when possible. + Support: False, str, unicode, dict, HTTPResponse, HTTPError, file-like, + iterable of strings and iterable of unicodes + """ + # Filtered types (recursive, because they may return anything) + for testtype, filterfunc in self.castfilter: + if isinstance(out, testtype): + return self._cast(filterfunc(out), request, response) + + # Empty output is done here + if not out: + response.headers['Content-Length'] = 0 + return [] + # Join lists of byte or unicode strings. Mixed lists are NOT supported + if isinstance(out, (tuple, list))\ + and isinstance(out[0], (bytes, unicode)): + out = out[0][0:0].join(out) # b'abc'[0:0] -> b'' + # Encode unicode strings + if isinstance(out, unicode): + out = out.encode(response.charset) + # Byte Strings are just returned + if isinstance(out, bytes): + response.headers['Content-Length'] = str(len(out)) + return [out] + # HTTPError or HTTPException (recursive, because they may wrap anything) + if isinstance(out, HTTPError): + out.apply(response) + return self._cast(self.error_handler.get(out.status, repr)(out), request, response) + if isinstance(out, HTTPResponse): + out.apply(response) + return self._cast(out.output, request, response) + + # File-like objects. + if hasattr(out, 'read'): + if 'wsgi.file_wrapper' in request.environ: + return request.environ['wsgi.file_wrapper'](out) + elif hasattr(out, 'close') or not hasattr(out, '__iter__'): + return WSGIFileWrapper(out) + + # Handle Iterables. We peek into them to detect their inner type. + try: + out = iter(out) + first = out.next() + while not first: + first = out.next() + except StopIteration: + return self._cast('', request, response) + except HTTPResponse, e: + first = e + except Exception, e: + first = HTTPError(500, 'Unhandled exception', e, format_exc(10)) + if isinstance(e, (KeyboardInterrupt, SystemExit, MemoryError))\ + or not self.catchall: + raise + # These are the inner types allowed in iterator or generator objects. + if isinstance(first, HTTPResponse): + return self._cast(first, request, response) + if isinstance(first, bytes): + return itertools.chain([first], out) + if isinstance(first, unicode): + return itertools.imap(lambda x: x.encode(response.charset), + itertools.chain([first], out)) + return self._cast(HTTPError(500, 'Unsupported response type: %s'\ + % type(first)), request, response) + + def wsgi(self, environ, start_response): + """ The bottle WSGI-interface. """ + try: + environ['bottle.app'] = self + request.bind(environ) + response.bind() + out = self.handle(request.path, request.method) + out = self._cast(out, request, response) + # rfc2616 section 4.3 + if response.status in (100, 101, 204, 304) or request.method == 'HEAD': + if hasattr(out, 'close'): out.close() + out = [] + status = '%d %s' % (response.status, HTTP_CODES[response.status]) + start_response(status, response.headerlist) + return out + except (KeyboardInterrupt, SystemExit, MemoryError): + raise + except Exception, e: + if not self.catchall: raise + err = '

Critical error while processing request: %s

' \ + % environ.get('PATH_INFO', '/') + if DEBUG: + err += '

Error:

\n
%s
\n' % repr(e) + err += '

Traceback:

\n
%s
\n' % format_exc(10) + environ['wsgi.errors'].write(err) #TODO: wsgi.error should not get html + start_response('500 INTERNAL SERVER ERROR', [('Content-Type', 'text/html')]) + return [tob(err)] + + def __call__(self, environ, start_response): + return self.wsgi(environ, start_response) + + + + + + +############################################################################### +# HTTP and WSGI Tools ########################################################## +############################################################################### + +class Request(threading.local, DictMixin): + """ Represents a single HTTP request using thread-local attributes. + The Request object wraps a WSGI environment and can be used as such. + """ + def __init__(self, environ=None): + """ Create a new Request instance. + + You usually don't do this but use the global `bottle.request` + instance instead. + """ + self.bind(environ or {},) + + def bind(self, environ): + """ Bind a new WSGI environment. + + This is done automatically for the global `bottle.request` + instance on every request. + """ + self.environ = environ + # These attributes are used anyway, so it is ok to compute them here + self.path = '/' + environ.get('PATH_INFO', '/').lstrip('/') + self.method = environ.get('REQUEST_METHOD', 'GET').upper() + + @property + def _environ(self): + depr("Request._environ renamed to Request.environ") + return self.environ + + def copy(self): + ''' Returns a copy of self ''' + return Request(self.environ.copy()) + + def path_shift(self, shift=1): + ''' Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa. + + :param shift: The number of path fragments to shift. May be negative + to change the shift direction. (default: 1) + ''' + script_name = self.environ.get('SCRIPT_NAME','/') + self['SCRIPT_NAME'], self.path = path_shift(script_name, self.path, shift) + self['PATH_INFO'] = self.path + + def __getitem__(self, key): return self.environ[key] + def __delitem__(self, key): self[key] = ""; del(self.environ[key]) + def __iter__(self): return iter(self.environ) + def __len__(self): return len(self.environ) + def keys(self): return self.environ.keys() + def __setitem__(self, key, value): + """ Shortcut for Request.environ.__setitem__ """ + self.environ[key] = value + todelete = [] + if key in ('PATH_INFO','REQUEST_METHOD'): + self.bind(self.environ) + elif key == 'wsgi.input': todelete = ('body','forms','files','params') + elif key == 'QUERY_STRING': todelete = ('get','params') + elif key.startswith('HTTP_'): todelete = ('headers', 'cookies') + for key in todelete: + if 'bottle.' + key in self.environ: + del self.environ['bottle.' + key] + + @property + def query_string(self): + """ The part of the URL following the '?'. """ + return self.environ.get('QUERY_STRING', '') + + @property + def fullpath(self): + """ Request path including SCRIPT_NAME (if present). """ + return self.environ.get('SCRIPT_NAME', '').rstrip('/') + self.path + + @property + def url(self): + """ Full URL as requested by the client (computed). + + This value is constructed out of different environment variables + and includes scheme, host, port, scriptname, path and query string. + """ + scheme = self.environ.get('wsgi.url_scheme', 'http') + host = self.environ.get('HTTP_X_FORWARDED_HOST') + host = host or self.environ.get('HTTP_HOST', None) + if not host: + host = self.environ.get('SERVER_NAME') + port = self.environ.get('SERVER_PORT', '80') + if (scheme, port) not in (('https','443'), ('http','80')): + host += ':' + port + parts = (scheme, host, urlquote(self.fullpath), self.query_string, '') + return urlunsplit(parts) + + @property + def content_length(self): + """ Content-Length header as an integer, -1 if not specified """ + return int(self.environ.get('CONTENT_LENGTH', '') or -1) + + @property + def header(self): + depr("The Request.header property was renamed to Request.headers") + return self.headers + + @property + def headers(self): + ''' Request HTTP Headers stored in a dict-like object. + + This dictionary uses case-insensitive keys and native strings as + keys and values. See :class:`WSGIHeaderDict` for details. + ''' + if 'bottle.headers' not in self.environ: + self.environ['bottle.headers'] = WSGIHeaderDict(self.environ) + return self.environ['bottle.headers'] + + @property + def GET(self): + """ The QUERY_STRING parsed into an instance of :class:`MultiDict`. + + If you expect more than one value for a key, use ``.getall(key)`` on + this dictionary to get a list of all values. Otherwise, only the + first value is returned. + """ + if 'bottle.get' not in self.environ: + data = parse_qs(self.query_string, keep_blank_values=True) + get = self.environ['bottle.get'] = MultiDict() + for key, values in data.iteritems(): + for value in values: + get[key] = value + return self.environ['bottle.get'] + + @property + def POST(self): + """ The combined values from :attr:`forms` and :attr:`files`. Values are + either strings (form values) or instances of + :class:`cgi.FieldStorage` (file uploads). + + If you expect more than one value for a key, use ``.getall(key)`` on + this dictionary to get a list of all values. Otherwise, only the + first value is returned. + """ + if 'bottle.post' not in self.environ: + self.environ['bottle.post'] = MultiDict() + self.environ['bottle.forms'] = MultiDict() + self.environ['bottle.files'] = MultiDict() + safe_env = {'QUERY_STRING':''} # Build a safe environment for cgi + for key in ('REQUEST_METHOD', 'CONTENT_TYPE', 'CONTENT_LENGTH'): + if key in self.environ: safe_env[key] = self.environ[key] + if NCTextIOWrapper: + fb = NCTextIOWrapper(self.body, encoding='ISO-8859-1', newline='\n') + # TODO: Content-Length may be wrong now. Does cgi.FieldStorage + # use it at all? I think not, because all tests pass. + else: + fb = self.body + data = cgi.FieldStorage(fp=fb, environ=safe_env, keep_blank_values=True) + for item in data.list or []: + if item.filename: + self.environ['bottle.post'][item.name] = item + self.environ['bottle.files'][item.name] = item + else: + self.environ['bottle.post'][item.name] = item.value + self.environ['bottle.forms'][item.name] = item.value + return self.environ['bottle.post'] + + @property + def forms(self): + """ POST form values parsed into an instance of :class:`MultiDict`. + + This property contains form values parsed from an `url-encoded` + or `multipart/form-data` encoded POST request bidy. The values are + native strings. + + If you expect more than one value for a key, use ``.getall(key)`` on + this dictionary to get a list of all values. Otherwise, only the + first value is returned. + """ + if 'bottle.forms' not in self.environ: self.POST + return self.environ['bottle.forms'] + + @property + def files(self): + """ File uploads parsed into an instance of :class:`MultiDict`. + + This property contains file uploads parsed from an + `multipart/form-data` encoded POST request body. The values are + instances of :class:`cgi.FieldStorage`. + + If you expect more than one value for a key, use ``.getall(key)`` on + this dictionary to get a list of all values. Otherwise, only the + first value is returned. + """ + if 'bottle.files' not in self.environ: self.POST + return self.environ['bottle.files'] + + @property + def params(self): + """ A combined :class:`MultiDict` with values from :attr:`forms` and + :attr:`GET`. File-uploads are not included. """ + if 'bottle.params' not in self.environ: + self.environ['bottle.params'] = MultiDict(self.GET) + self.environ['bottle.params'].update(dict(self.forms)) + return self.environ['bottle.params'] + + @property + def body(self): + """ The HTTP request body as a seekable file-like object. + + This property returns a copy of the `wsgi.input` stream and should + be used instead of `environ['wsgi.input']`. + """ + if 'bottle.body' not in self.environ: + maxread = max(0, self.content_length) + stream = self.environ['wsgi.input'] + body = BytesIO() if maxread < MEMFILE_MAX else TemporaryFile(mode='w+b') + while maxread > 0: + part = stream.read(min(maxread, MEMFILE_MAX)) + if not part: #TODO: Wrong content_length. Error? Do nothing? + break + body.write(part) + maxread -= len(part) + self.environ['wsgi.input'] = body + self.environ['bottle.body'] = body + self.environ['bottle.body'].seek(0) + return self.environ['bottle.body'] + + @property + def auth(self): #TODO: Tests and docs. Add support for digest. namedtuple? + """ HTTP authorization data as a (user, passwd) tuple. (experimental) + + This implementation currently only supports basic auth and returns + None on errors. + """ + return parse_auth(self.headers.get('Authorization','')) + + @property + def COOKIES(self): + """ Cookies parsed into a dictionary. Secure cookies are NOT decoded + automatically. See :meth:`get_cookie` for details. + """ + if 'bottle.cookies' not in self.environ: + raw_dict = SimpleCookie(self.headers.get('Cookie','')) + self.environ['bottle.cookies'] = {} + for cookie in raw_dict.itervalues(): + self.environ['bottle.cookies'][cookie.key] = cookie.value + return self.environ['bottle.cookies'] + + def get_cookie(self, key, secret=None): + """ Return the content of a cookie. To read a `Secure Cookies`, use the + same `secret` as used to create the cookie (see + :meth:`Response.set_cookie`). If anything goes wrong, None is + returned. + """ + value = self.COOKIES.get(key) + if secret and value: + dec = cookie_decode(value, secret) # (key, value) tuple or None + return dec[1] if dec and dec[0] == key else None + return value or None + + @property + def is_ajax(self): + ''' True if the request was generated using XMLHttpRequest ''' + #TODO: write tests + return self.header.get('X-Requested-With') == 'XMLHttpRequest' + + + +class Response(threading.local): + """ Represents a single HTTP response using thread-local attributes. + """ + + def __init__(self): + self.bind() + + def bind(self): + """ Resets the Response object to its factory defaults. """ + self._COOKIES = None + self.status = 200 + self.headers = HeaderDict() + self.content_type = 'text/html; charset=UTF-8' + + @property + def header(self): + depr("Response.header renamed to Response.headers") + return self.headers + + def copy(self): + ''' Returns a copy of self. ''' + copy = Response() + copy.status = self.status + copy.headers = self.headers.copy() + copy.content_type = self.content_type + return copy + + def wsgiheader(self): + ''' Returns a wsgi conform list of header/value pairs. ''' + for c in self.COOKIES.values(): + if c.OutputString() not in self.headers.getall('Set-Cookie'): + self.headers.append('Set-Cookie', c.OutputString()) + # rfc2616 section 10.2.3, 10.3.5 + if self.status in (204, 304) and 'content-type' in self.headers: + del self.headers['content-type'] + if self.status == 304: + for h in ('allow', 'content-encoding', 'content-language', + 'content-length', 'content-md5', 'content-range', + 'content-type', 'last-modified'): # + c-location, expires? + if h in self.headers: + del self.headers[h] + return list(self.headers.iterallitems()) + headerlist = property(wsgiheader) + + @property + def charset(self): + """ Return the charset specified in the content-type header. + + This defaults to `UTF-8`. + """ + if 'charset=' in self.content_type: + return self.content_type.split('charset=')[-1].split(';')[0].strip() + return 'UTF-8' + + @property + def COOKIES(self): + """ A dict-like SimpleCookie instance. Use :meth:`set_cookie` instead. """ + if not self._COOKIES: + self._COOKIES = SimpleCookie() + return self._COOKIES + + def set_cookie(self, key, value, secret=None, **kargs): + ''' Add a cookie. If the `secret` parameter is set, this creates a + `Secure Cookie` (described below). + + :param key: the name of the cookie. + :param value: the value of the cookie. + :param secret: required for secure cookies. (default: None) + :param max_age: maximum age in seconds. (default: None) + :param expires: a datetime object or UNIX timestamp. (defaut: None) + :param domain: the domain that is allowed to read the cookie. + (default: current domain) + :param path: limits the cookie to a given path (default: /) + + If neither `expires` nor `max_age` are set (default), the cookie + lasts only as long as the browser is not closed. + + Secure cookies may store any pickle-able object and are + cryptographically signed to prevent manipulation. Keep in mind that + cookies are limited to 4kb in most browsers. + + Warning: Secure cookies are not encrypted (the client can still see + the content) and not copy-protected (the client can restore an old + cookie). The main intention is to make pickling and unpickling + save, not to store secret information at client side. + ''' + if secret: + value = touni(cookie_encode((key, value), secret)) + elif not isinstance(value, basestring): + raise TypeError('Secret missing for non-string Cookie.') + + self.COOKIES[key] = value + for k, v in kargs.iteritems(): + self.COOKIES[key][k.replace('_', '-')] = v + + def delete_cookie(self, key, **kwargs): + ''' Delete a cookie. Be sure to use the same `domain` and `path` + parameters as used to create the cookie. ''' + kwargs['max_age'] = -1 + kwargs['expires'] = 0 + self.set_cookie(key, '', **kwargs) + + def get_content_type(self): + """ Current 'Content-Type' header. """ + return self.headers['Content-Type'] + + def set_content_type(self, value): + self.headers['Content-Type'] = value + + content_type = property(get_content_type, set_content_type, None, + get_content_type.__doc__) + + + + + + +############################################################################### +# Common Utilities ############################################################# +############################################################################### + +class MultiDict(DictMixin): + """ A dict that remembers old values for each key """ + # collections.MutableMapping would be better for Python >= 2.6 + def __init__(self, *a, **k): + self.dict = dict() + for k, v in dict(*a, **k).iteritems(): + self[k] = v + + def __len__(self): return len(self.dict) + def __iter__(self): return iter(self.dict) + def __contains__(self, key): return key in self.dict + def __delitem__(self, key): del self.dict[key] + def keys(self): return self.dict.keys() + def __getitem__(self, key): return self.get(key, KeyError, -1) + def __setitem__(self, key, value): self.append(key, value) + + def append(self, key, value): self.dict.setdefault(key, []).append(value) + def replace(self, key, value): self.dict[key] = [value] + def getall(self, key): return self.dict.get(key) or [] + + def get(self, key, default=None, index=-1): + if key not in self.dict and default != KeyError: + return [default][index] + return self.dict[key][index] + + def iterallitems(self): + for key, values in self.dict.iteritems(): + for value in values: + yield key, value + + +class HeaderDict(MultiDict): + """ Same as :class:`MultiDict`, but title()s the keys and overwrites by default. """ + def __contains__(self, key): return MultiDict.__contains__(self, self.httpkey(key)) + def __getitem__(self, key): return MultiDict.__getitem__(self, self.httpkey(key)) + def __delitem__(self, key): return MultiDict.__delitem__(self, self.httpkey(key)) + def __setitem__(self, key, value): self.replace(key, value) + def get(self, key, default=None, index=-1): return MultiDict.get(self, self.httpkey(key), default, index) + def append(self, key, value): return MultiDict.append(self, self.httpkey(key), str(value)) + def replace(self, key, value): return MultiDict.replace(self, self.httpkey(key), str(value)) + def getall(self, key): return MultiDict.getall(self, self.httpkey(key)) + def httpkey(self, key): return str(key).replace('_','-').title() + + +class WSGIHeaderDict(DictMixin): + ''' This dict-like class wraps a WSGI environ dict and provides convenient + access to HTTP_* fields. Keys and values are native strings + (2.x bytes or 3.x unicode) and keys are case-insensitive. If the WSGI + environment contains non-native string values, these are de- or encoded + using a lossless 'latin1' character set. + + The API will remain stable even on changes to the relevant PEPs. + Currently PEP 333, 444 and 3333 are supported. (PEP 444 is the only one + that uses non-native strings.) + ''' + + def __init__(self, environ): + self.environ = environ + + def _ekey(self, key): # Translate header field name to environ key. + return 'HTTP_' + key.replace('-','_').upper() + + def raw(self, key, default=None): + ''' Return the header value as is (may be bytes or unicode). ''' + return self.environ.get(self._ekey(key), default) + + def __getitem__(self, key): + return tonat(self.environ[self._ekey(key)], 'latin1') + + def __setitem__(self, key, value): + raise TypeError("%s is read-only." % self.__class__) + + def __delitem__(self, key): + raise TypeError("%s is read-only." % self.__class__) + + def __iter__(self): + for key in self.environ: + if key[:5] == 'HTTP_': + yield key[5:].replace('_', '-').title() + + def keys(self): return list(self) + def __len__(self): return len(list(self)) + def __contains__(self, key): return self._ekey(key) in self.environ + + + + + +class AppStack(list): + """ A stack implementation. """ + + def __call__(self): + """ Return the current default app. """ + return self[-1] + + def push(self, value=None): + """ Add a new Bottle instance to the stack """ + if not isinstance(value, Bottle): + value = Bottle() + self.append(value) + return value + +class WSGIFileWrapper(object): + + def __init__(self, fp, buffer_size=1024*64): + self.fp, self.buffer_size = fp, buffer_size + for attr in ('fileno', 'close', 'read', 'readlines'): + if hasattr(fp, attr): setattr(self, attr, getattr(fp, attr)) + + def __iter__(self): + read, buff = self.fp.read, self.buffer_size + while True: + part = read(buff) + if not part: break + yield part + + + + + + +############################################################################### +# Application Helper ########################################################### +############################################################################### + +def dict2json(d): + response.content_type = 'application/json' + return json_dumps(d) + + +def abort(code=500, text='Unknown Error: Application stopped.'): + """ Aborts execution and causes a HTTP error. """ + raise HTTPError(code, text) + + +def redirect(url, code=303): + """ Aborts execution and causes a 303 redirect """ + scriptname = request.environ.get('SCRIPT_NAME', '').rstrip('/') + '/' + location = urljoin(request.url, urljoin(scriptname, url)) + raise HTTPResponse("", status=code, header=dict(Location=location)) + + +def send_file(*a, **k): #BC 0.6.4 + """ Raises the output of static_file(). (deprecated) """ + raise static_file(*a, **k) + + +def static_file(filename, root, guessmime=True, mimetype=None, download=False): + """ Opens a file in a safe way and returns a HTTPError object with status + code 200, 305, 401 or 404. Sets Content-Type, Content-Length and + Last-Modified header. Obeys If-Modified-Since header and HEAD requests. + """ + root = os.path.abspath(root) + os.sep + filename = os.path.abspath(os.path.join(root, filename.strip('/\\'))) + header = dict() + + if not filename.startswith(root): + return HTTPError(403, "Access denied.") + if not os.path.exists(filename) or not os.path.isfile(filename): + return HTTPError(404, "File does not exist.") + if not os.access(filename, os.R_OK): + return HTTPError(403, "You do not have permission to access this file.") + + if not mimetype and guessmime: + header['Content-Type'] = mimetypes.guess_type(filename)[0] + else: + header['Content-Type'] = mimetype if mimetype else 'text/plain' + + if download == True: + download = os.path.basename(filename) + if download: + header['Content-Disposition'] = 'attachment; filename="%s"' % download + + stats = os.stat(filename) + lm = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(stats.st_mtime)) + header['Last-Modified'] = lm + ims = request.environ.get('HTTP_IF_MODIFIED_SINCE') + if ims: + ims = ims.split(";")[0].strip() # IE sends "; length=146" + ims = parse_date(ims) + if ims is not None and ims >= int(stats.st_mtime): + header['Date'] = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime()) + return HTTPResponse(status=304, header=header) + header['Content-Length'] = stats.st_size + if request.method == 'HEAD': + return HTTPResponse('', header=header) + else: + return HTTPResponse(open(filename, 'rb'), header=header) + + + + + + +############################################################################### +# HTTP Utilities and MISC (TODO) ############################################### +############################################################################### + +def debug(mode=True): + """ Change the debug level. + There is only one debug level supported at the moment.""" + global DEBUG + DEBUG = bool(mode) + + +def parse_date(ims): + """ Parse rfc1123, rfc850 and asctime timestamps and return UTC epoch. """ + try: + ts = email.utils.parsedate_tz(ims) + return time.mktime(ts[:8] + (0,)) - (ts[9] or 0) - time.timezone + except (TypeError, ValueError, IndexError, OverflowError): + return None + + +def parse_auth(header): + """ Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None""" + try: + method, data = header.split(None, 1) + if method.lower() == 'basic': + name, pwd = base64.b64decode(data).split(':', 1) + return name, pwd + except (KeyError, ValueError, TypeError): + return None + + +def _lscmp(a, b): + ''' Compares two strings in a cryptographically save way: + Runtime is not affected by a common prefix. ''' + return not sum(0 if x==y else 1 for x, y in zip(a, b)) and len(a) == len(b) + + +def cookie_encode(data, key): + ''' Encode and sign a pickle-able object. Return a (byte) string ''' + msg = base64.b64encode(pickle.dumps(data, -1)) + sig = base64.b64encode(hmac.new(key, msg).digest()) + return tob('!') + sig + tob('?') + msg + + +def cookie_decode(data, key): + ''' Verify and decode an encoded string. Return an object or None.''' + data = tob(data) + if cookie_is_encoded(data): + sig, msg = data.split(tob('?'), 1) + if _lscmp(sig[1:], base64.b64encode(hmac.new(key, msg).digest())): + return pickle.loads(base64.b64decode(msg)) + return None + + +def cookie_is_encoded(data): + ''' Return True if the argument looks like a encoded cookie.''' + return bool(data.startswith(tob('!')) and tob('?') in data) + + +def yieldroutes(func): + """ Return a generator for routes that match the signature (name, args) + of the func parameter. This may yield more than one route if the function + takes optional keyword arguments. The output is best described by example:: + + a() -> '/a' + b(x, y) -> '/b/:x/:y' + c(x, y=5) -> '/c/:x' and '/c/:x/:y' + d(x=5, y=6) -> '/d' and '/d/:x' and '/d/:x/:y' + """ + import inspect # Expensive module. Only import if necessary. + path = func.__name__.replace('__','/').lstrip('/') + spec = inspect.getargspec(func) + argc = len(spec[0]) - len(spec[3] or []) + path += ('/:%s' * argc) % tuple(spec[0][:argc]) + yield path + for arg in spec[0][argc:]: + path += '/:%s' % arg + yield path + +def path_shift(script_name, path_info, shift=1): + ''' Shift path fragments from PATH_INFO to SCRIPT_NAME and vice versa. + + :return: The modified paths. + :param script_name: The SCRIPT_NAME path. + :param script_name: The PATH_INFO path. + :param shift: The number of path fragments to shift. May be negative to + change the shift direction. (default: 1) + ''' + if shift == 0: return script_name, path_info + pathlist = path_info.strip('/').split('/') + scriptlist = script_name.strip('/').split('/') + if pathlist and pathlist[0] == '': pathlist = [] + if scriptlist and scriptlist[0] == '': scriptlist = [] + if shift > 0 and shift <= len(pathlist): + moved = pathlist[:shift] + scriptlist = scriptlist + moved + pathlist = pathlist[shift:] + elif shift < 0 and shift >= -len(scriptlist): + moved = scriptlist[shift:] + pathlist = moved + pathlist + scriptlist = scriptlist[:shift] + else: + empty = 'SCRIPT_NAME' if shift < 0 else 'PATH_INFO' + raise AssertionError("Cannot shift. Nothing left from %s" % empty) + new_script_name = '/' + '/'.join(scriptlist) + new_path_info = '/' + '/'.join(pathlist) + if path_info.endswith('/') and pathlist: new_path_info += '/' + return new_script_name, new_path_info + + + +# Decorators +#TODO: Replace default_app() with app() + +def validate(**vkargs): + """ + Validates and manipulates keyword arguments by user defined callables. + Handles ValueError and missing arguments by raising HTTPError(403). + """ + def decorator(func): + def wrapper(**kargs): + for key, value in vkargs.iteritems(): + if key not in kargs: + abort(403, 'Missing parameter: %s' % key) + try: + kargs[key] = value(kargs[key]) + except ValueError: + abort(403, 'Wrong parameter format for: %s' % key) + return func(**kargs) + return wrapper + return decorator + +def auth_basic(check, realm="private", text="Access denied"): + ''' Callback decorator to require HTTP auth (basic). + TODO: Add route(check_auth=...) parameter. ''' + def decorator(func): + def wrapper(*a, **ka): + user, password = request.auth or (None, None) + if user is None or not check(user, password): + response.headers['WWW-Authenticate'] = 'Basic realm="%s"' % realm + return HTTPError(401, text) + return func(*a, **ka) + return wrapper + return decorator + + +def make_default_app_wrapper(name): + ''' Return a callable that relays calls to the current default app. ''' + @functools.wraps(getattr(Bottle, name)) + def wrapper(*a, **ka): + return getattr(app(), name)(*a, **ka) + return wrapper + +for name in 'route get post put delete error mount hook'.split(): + globals()[name] = make_default_app_wrapper(name) +url = make_default_app_wrapper('get_url') +del name + +def default(): + depr("The default() decorator is deprecated. Use @error(404) instead.") + return error(404) + + + + + + +############################################################################### +# Server Adapter ############################################################### +############################################################################### + +class ServerAdapter(object): + quiet = False + def __init__(self, host='127.0.0.1', port=8080, **config): + self.options = config + self.host = host + self.port = int(port) + + def run(self, handler): # pragma: no cover + pass + + def __repr__(self): + args = ', '.join(['%s=%s'%(k,repr(v)) for k, v in self.options.items()]) + return "%s(%s)" % (self.__class__.__name__, args) + + +class CGIServer(ServerAdapter): + quiet = True + def run(self, handler): # pragma: no cover + from wsgiref.handlers import CGIHandler + CGIHandler().run(handler) # Just ignore host and port here + + +class FlupFCGIServer(ServerAdapter): + def run(self, handler): # pragma: no cover + import flup.server.fcgi + kwargs = {'bindAddress':(self.host, self.port)} + kwargs.update(self.options) # allow to override bindAddress and others + flup.server.fcgi.WSGIServer(handler, **kwargs).run() + + +class WSGIRefServer(ServerAdapter): + def run(self, handler): # pragma: no cover + from wsgiref.simple_server import make_server, WSGIRequestHandler + if self.quiet: + class QuietHandler(WSGIRequestHandler): + def log_request(*args, **kw): pass + self.options['handler_class'] = QuietHandler + srv = make_server(self.host, self.port, handler, **self.options) + srv.serve_forever() + + +class CherryPyServer(ServerAdapter): + def run(self, handler): # pragma: no cover + from cherrypy import wsgiserver + server = wsgiserver.CherryPyWSGIServer((self.host, self.port), handler) + server.start() + + +class PasteServer(ServerAdapter): + def run(self, handler): # pragma: no cover + from paste import httpserver + if not self.quiet: + from paste.translogger import TransLogger + handler = TransLogger(handler) + httpserver.serve(handler, host=self.host, port=str(self.port), + **self.options) + +class MeinheldServer(ServerAdapter): + def run(self, handler): + from meinheld import server + server.listen((self.host, self.port)) + server.run(handler) + +class FapwsServer(ServerAdapter): + """ Extremely fast webserver using libev. See http://www.fapws.org/ """ + def run(self, handler): # pragma: no cover + import fapws._evwsgi as evwsgi + from fapws import base, config + port = self.port + if float(config.SERVER_IDENT[-2:]) > 0.4: + # fapws3 silently changed its API in 0.5 + port = str(port) + evwsgi.start(self.host, port) + # fapws3 never releases the GIL. Complain upstream. I tried. No luck. + if 'BOTTLE_CHILD' in os.environ and not self.quiet: + print "WARNING: Auto-reloading does not work with Fapws3." + print " (Fapws3 breaks python thread support)" + evwsgi.set_base_module(base) + def app(environ, start_response): + environ['wsgi.multiprocess'] = False + return handler(environ, start_response) + evwsgi.wsgi_cb(('', app)) + evwsgi.run() + + +class TornadoServer(ServerAdapter): + """ The super hyped asynchronous server by facebook. Untested. """ + def run(self, handler): # pragma: no cover + import tornado.wsgi + import tornado.httpserver + import tornado.ioloop + container = tornado.wsgi.WSGIContainer(handler) + server = tornado.httpserver.HTTPServer(container) + server.listen(port=self.port) + tornado.ioloop.IOLoop.instance().start() + + +class AppEngineServer(ServerAdapter): + """ Adapter for Google App Engine. """ + quiet = True + def run(self, handler): + from google.appengine.ext.webapp import util + util.run_wsgi_app(handler) + + +class TwistedServer(ServerAdapter): + """ Untested. """ + def run(self, handler): + from twisted.web import server, wsgi + from twisted.python.threadpool import ThreadPool + from twisted.internet import reactor + thread_pool = ThreadPool() + thread_pool.start() + reactor.addSystemEventTrigger('after', 'shutdown', thread_pool.stop) + factory = server.Site(wsgi.WSGIResource(reactor, thread_pool, handler)) + reactor.listenTCP(self.port, factory, interface=self.host) + reactor.run() + + +class DieselServer(ServerAdapter): + """ Untested. """ + def run(self, handler): + from diesel.protocols.wsgi import WSGIApplication + app = WSGIApplication(handler, port=self.port) + app.run() + + +class GeventServer(ServerAdapter): + """ Untested. """ + def run(self, handler): + from gevent import wsgi + #from gevent.hub import getcurrent + #self.set_context_ident(getcurrent, weakref=True) # see contextlocal + wsgi.WSGIServer((self.host, self.port), handler).serve_forever() + + +class GunicornServer(ServerAdapter): + """ Untested. """ + def run(self, handler): + from gunicorn.arbiter import Arbiter + from gunicorn.config import Config + handler.cfg = Config({'bind': "%s:%d" % (self.host, self.port), 'workers': 4}) + arbiter = Arbiter(handler) + arbiter.run() + + +class EventletServer(ServerAdapter): + """ Untested """ + def run(self, handler): + from eventlet import wsgi, listen + wsgi.server(listen((self.host, self.port)), handler) + + +class RocketServer(ServerAdapter): + """ Untested. As requested in issue 63 + https://github.com/defnull/bottle/issues/#issue/63 """ + def run(self, handler): + from rocket import Rocket + server = Rocket((self.host, self.port), 'wsgi', { 'wsgi_app' : handler }) + server.start() + +class BjoernServer(ServerAdapter): + """ Screamingly fast server written in C: https://github.com/jonashaag/bjoern """ + def run(self, handler): + from bjoern import run + run(handler, self.host, self.port) + + +class AutoServer(ServerAdapter): + """ Untested. """ + adapters = [PasteServer, CherryPyServer, TwistedServer, WSGIRefServer] + def run(self, handler): + for sa in self.adapters: + try: + return sa(self.host, self.port, **self.options).run(handler) + except ImportError: + pass + + +server_names = { + 'cgi': CGIServer, + 'flup': FlupFCGIServer, + 'wsgiref': WSGIRefServer, + 'cherrypy': CherryPyServer, + 'paste': PasteServer, + 'fapws3': FapwsServer, + 'tornado': TornadoServer, + 'gae': AppEngineServer, + 'twisted': TwistedServer, + 'diesel': DieselServer, + 'meinheld': MeinheldServer, + 'gunicorn': GunicornServer, + 'eventlet': EventletServer, + 'gevent': GeventServer, + 'rocket': RocketServer, + 'bjoern' : BjoernServer, + 'auto': AutoServer, +} + + + + + + +############################################################################### +# Application Control ########################################################## +############################################################################### + + +def _load(target, **kwargs): + """ Fetch something from a module. The exact behaviour depends on the the + target string: + + If the target is a valid python import path (e.g. `package.module`), + the rightmost part is returned as a module object. + If the target contains a colon (e.g. `package.module:var`) the module + variable specified after the colon is returned. + If the part after the colon contains any non-alphanumeric characters + (e.g. `package.module:function(argument)`) the result of the expression + is returned. The exec namespace is updated with the keyword arguments + provided to this function. + + Example:: + >>> _load('bottle') + + >>> _load('bottle:Bottle') + + >>> _load('bottle:cookie_encode(v, secret)', v='foo', secret='bar') + '!F+hN4dQxaDJ4QxxaZ+Z3jw==?gAJVA2Zvb3EBLg==' + + """ + module, target = target.split(":", 1) if ':' in target else (target, None) + if module not in sys.modules: + __import__(module) + if not target: + return sys.modules[module] + if target.isalnum(): + return getattr(sys.modules[module], target) + package_name = module.split('.')[0] + kwargs[package_name] = sys.modules[package_name] + return eval('%s.%s' % (module, target), kwargs) + +def load_app(target): + """ Load a bottle application based on a target string and return the + application object. + + If the target is an import path (e.g. package.module), the application + stack is used to isolate the routes defined in that module. + If the target contains a colon (e.g. package.module:myapp) the + module variable specified after the colon is returned instead. + """ + tmp = app.push() # Create a new "default application" + rv = _load(target) # Import the target module + app.remove(tmp) # Remove the temporary added default application + return rv if isinstance(rv, Bottle) else tmp + + +def run(app=None, server='wsgiref', host='127.0.0.1', port=8080, + interval=1, reloader=False, quiet=False, **kargs): + """ Start a server instance. This method blocks until the server terminates. + + :param app: WSGI application or target string supported by + :func:`load_app`. (default: :func:`default_app`) + :param server: Server adapter to use. See :data:`server_names` keys + for valid names or pass a :class:`ServerAdapter` subclass. + (default: `wsgiref`) + :param host: Server address to bind to. Pass ``0.0.0.0`` to listens on + all interfaces including the external one. (default: 127.0.0.1) + :param port: Server port to bind to. Values below 1024 require root + privileges. (default: 8080) + :param reloader: Start auto-reloading server? (default: False) + :param interval: Auto-reloader interval in seconds (default: 1) + :param quiet: Suppress output to stdout and stderr? (default: False) + :param options: Options passed to the server adapter. + """ + app = app or default_app() + if isinstance(app, basestring): + app = load_app(app) + if isinstance(server, basestring): + server = server_names.get(server) + if isinstance(server, type): + server = server(host=host, port=port, **kargs) + if not isinstance(server, ServerAdapter): + raise RuntimeError("Server must be a subclass of ServerAdapter") + server.quiet = server.quiet or quiet + if not server.quiet and not os.environ.get('BOTTLE_CHILD'): + print "Bottle server starting up (using %s)..." % repr(server) + print "Listening on http://%s:%d/" % (server.host, server.port) + print "Use Ctrl-C to quit." + print + try: + if reloader: + interval = min(interval, 1) + if os.environ.get('BOTTLE_CHILD'): + _reloader_child(server, app, interval) + else: + _reloader_observer(server, app, interval) + else: + server.run(app) + except KeyboardInterrupt: + pass + if not server.quiet and not os.environ.get('BOTTLE_CHILD'): + print "Shutting down..." + + +class FileCheckerThread(threading.Thread): + ''' Thread that periodically checks for changed module files. ''' + + def __init__(self, lockfile, interval): + threading.Thread.__init__(self) + self.lockfile, self.interval = lockfile, interval + #1: lockfile to old; 2: lockfile missing + #3: module file changed; 5: external exit + self.status = 0 + + def run(self): + exists = os.path.exists + mtime = lambda path: os.stat(path).st_mtime + files = dict() + for module in sys.modules.values(): + path = getattr(module, '__file__', '') + if path[-4:] in ('.pyo', '.pyc'): path = path[:-1] + if path and exists(path): files[path] = mtime(path) + while not self.status: + for path, lmtime in files.iteritems(): + if not exists(path) or mtime(path) > lmtime: + self.status = 3 + if not exists(self.lockfile): + self.status = 2 + elif mtime(self.lockfile) < time.time() - self.interval - 5: + self.status = 1 + if not self.status: + time.sleep(self.interval) + if self.status != 5: + thread.interrupt_main() + + +def _reloader_child(server, app, interval): + ''' Start the server and check for modified files in a background thread. + As soon as an update is detected, KeyboardInterrupt is thrown in + the main thread to exit the server loop. The process exists with status + code 3 to request a reload by the observer process. If the lockfile + is not modified in 2*interval second or missing, we assume that the + observer process died and exit with status code 1 or 2. + ''' + lockfile = os.environ.get('BOTTLE_LOCKFILE') + bgcheck = FileCheckerThread(lockfile, interval) + try: + bgcheck.start() + server.run(app) + except KeyboardInterrupt: + pass + bgcheck.status, status = 5, bgcheck.status + bgcheck.join() # bgcheck.status == 5 --> silent exit + if status: sys.exit(status) + + +def _reloader_observer(server, app, interval): + ''' Start a child process with identical commandline arguments and restart + it as long as it exists with status code 3. Also create a lockfile and + touch it (update mtime) every interval seconds. + ''' + fd, lockfile = tempfile.mkstemp(prefix='bottle-reloader.', suffix='.lock') + os.close(fd) # We only need this file to exist. We never write to it + try: + while os.path.exists(lockfile): + args = [sys.executable] + sys.argv + environ = os.environ.copy() + environ['BOTTLE_CHILD'] = 'true' + environ['BOTTLE_LOCKFILE'] = lockfile + p = subprocess.Popen(args, env=environ) + while p.poll() is None: # Busy wait... + os.utime(lockfile, None) # I am alive! + time.sleep(interval) + if p.poll() != 3: + if os.path.exists(lockfile): os.unlink(lockfile) + sys.exit(p.poll()) + elif not server.quiet: + print "Reloading server..." + except KeyboardInterrupt: + pass + if os.path.exists(lockfile): os.unlink(lockfile) + + + + + + +############################################################################### +# Template Adapters ############################################################ +############################################################################### + +class TemplateError(HTTPError): + def __init__(self, message): + HTTPError.__init__(self, 500, message) + + +class BaseTemplate(object): + """ Base class and minimal API for template adapters """ + extentions = ['tpl','html','thtml','stpl'] + settings = {} #used in prepare() + defaults = {} #used in render() + + def __init__(self, source=None, name=None, lookup=[], encoding='utf8', **settings): + """ Create a new template. + If the source parameter (str or buffer) is missing, the name argument + is used to guess a template filename. Subclasses can assume that + self.source and/or self.filename are set. Both are strings. + The lookup, encoding and settings parameters are stored as instance + variables. + The lookup parameter stores a list containing directory paths. + The encoding parameter should be used to decode byte strings or files. + The settings parameter contains a dict for engine-specific settings. + """ + self.name = name + self.source = source.read() if hasattr(source, 'read') else source + self.filename = source.filename if hasattr(source, 'filename') else None + self.lookup = map(os.path.abspath, lookup) + self.encoding = encoding + self.settings = self.settings.copy() # Copy from class variable + self.settings.update(settings) # Apply + if not self.source and self.name: + self.filename = self.search(self.name, self.lookup) + if not self.filename: + raise TemplateError('Template %s not found.' % repr(name)) + if not self.source and not self.filename: + raise TemplateError('No template specified.') + self.prepare(**self.settings) + + @classmethod + def search(cls, name, lookup=[]): + """ Search name in all directories specified in lookup. + First without, then with common extensions. Return first hit. """ + if os.path.isfile(name): return name + for spath in lookup: + fname = os.path.join(spath, name) + if os.path.isfile(fname): + return fname + for ext in cls.extentions: + if os.path.isfile('%s.%s' % (fname, ext)): + return '%s.%s' % (fname, ext) + + @classmethod + def global_config(cls, key, *args): + ''' This reads or sets the global settings stored in class.settings. ''' + if args: + cls.settings[key] = args[0] + else: + return cls.settings[key] + + def prepare(self, **options): + """ Run preparations (parsing, caching, ...). + It should be possible to call this again to refresh a template or to + update settings. + """ + raise NotImplementedError + + def render(self, *args, **kwargs): + """ Render the template with the specified local variables and return + a single byte or unicode string. If it is a byte string, the encoding + must match self.encoding. This method must be thread-safe! + Local variables may be provided in dictionaries (*args) + or directly, as keywords (**kwargs). + """ + raise NotImplementedError + + +class MakoTemplate(BaseTemplate): + def prepare(self, **options): + from mako.template import Template + from mako.lookup import TemplateLookup + options.update({'input_encoding':self.encoding}) + #TODO: This is a hack... https://github.com/defnull/bottle/issues#issue/8 + mylookup = TemplateLookup(directories=['.']+self.lookup, **options) + if self.source: + self.tpl = Template(self.source, lookup=mylookup) + else: #mako cannot guess extentions. We can, but only at top level... + name = self.name + if not os.path.splitext(name)[1]: + name += os.path.splitext(self.filename)[1] + self.tpl = mylookup.get_template(name) + + def render(self, *args, **kwargs): + for dictarg in args: kwargs.update(dictarg) + _defaults = self.defaults.copy() + _defaults.update(kwargs) + return self.tpl.render(**_defaults) + + +class CheetahTemplate(BaseTemplate): + def prepare(self, **options): + from Cheetah.Template import Template + self.context = threading.local() + self.context.vars = {} + options['searchList'] = [self.context.vars] + if self.source: + self.tpl = Template(source=self.source, **options) + else: + self.tpl = Template(file=self.filename, **options) + + def render(self, *args, **kwargs): + for dictarg in args: kwargs.update(dictarg) + self.context.vars.update(self.defaults) + self.context.vars.update(kwargs) + out = str(self.tpl) + self.context.vars.clear() + return [out] + + +class Jinja2Template(BaseTemplate): + def prepare(self, filters=None, tests=None, **kwargs): + from jinja2 import Environment, FunctionLoader + if 'prefix' in kwargs: # TODO: to be removed after a while + raise RuntimeError('The keyword argument `prefix` has been removed. ' + 'Use the full jinja2 environment name line_statement_prefix instead.') + self.env = Environment(loader=FunctionLoader(self.loader), **kwargs) + if filters: self.env.filters.update(filters) + if tests: self.env.tests.update(tests) + if self.source: + self.tpl = self.env.from_string(self.source) + else: + self.tpl = self.env.get_template(self.filename) + + def render(self, *args, **kwargs): + for dictarg in args: kwargs.update(dictarg) + _defaults = self.defaults.copy() + _defaults.update(kwargs) + return self.tpl.render(**_defaults).encode("utf-8") + + def loader(self, name): + fname = self.search(name, self.lookup) + if fname: + with open(fname, "rb") as f: + return f.read().decode(self.encoding) + +class SimpleTALTemplate(BaseTemplate): + ''' Untested! ''' + def prepare(self, **options): + from simpletal import simpleTAL + # TODO: add option to load METAL files during render + if self.source: + self.tpl = simpleTAL.compileHTMLTemplate(self.source) + else: + with open(self.filename, 'rb') as fp: + self.tpl = simpleTAL.compileHTMLTemplate(tonat(fp.read())) + + def render(self, *args, **kwargs): + from simpletal import simpleTALES + from StringIO import StringIO + for dictarg in args: kwargs.update(dictarg) + # TODO: maybe reuse a context instead of always creating one + context = simpleTALES.Context() + for k,v in self.defaults.items(): + context.addGlobal(k, v) + for k,v in kwargs.items(): + context.addGlobal(k, v) + output = StringIO() + self.tpl.expand(context, output) + return output.getvalue() + + + +class SimpleTemplate(BaseTemplate): + blocks = ('if','elif','else','try','except','finally','for','while','with','def','class') + dedent_blocks = ('elif', 'else', 'except', 'finally') + re_pytokens = None + + def prepare(self, escape_func=cgi.escape, noescape=False): + self.cache = {} + enc = self.encoding + self._str = lambda x: touni(x, enc) + self._escape = lambda x: escape_func(touni(x, enc)) + if noescape: + self._str, self._escape = self._escape, self._str + + @classmethod + def split_comment(cls, code): + """ Removes comments (#...) from python code. """ + if '#' not in code: return code + if not cls.re_pytokens: + #: This matches comments and all kinds of quoted strings but does + #: NOT match comments (#...) within quoted strings. (trust me) + cls.re_pytokens = re.compile(r''' + (''(?!')|""(?!")|'{6}|"{6} # Empty strings (all 4 types) + |'(?:[^\\']|\\.)+?' # Single quotes (') + |"(?:[^\\"]|\\.)+?" # Double quotes (") + |'{3}(?:[^\\]|\\.|\n)+?'{3} # Triple-quoted strings (') + |"{3}(?:[^\\]|\\.|\n)+?"{3} # Triple-quoted strings (") + |\#.* # Comments + )''', re.VERBOSE) + #: Remove comments only (leave quoted strings as they are) + subf = lambda m: '' if m.group(0)[0]=='#' else m.group(0) + return re.sub(cls.re_pytokens, subf, code) + + @cached_property + def co(self): + return compile(self.code, self.filename or '', 'exec') + + @cached_property + def code(self): + stack = [] # Current Code indentation + lineno = 0 # Current line of code + ptrbuffer = [] # Buffer for printable strings and token tuple instances + codebuffer = [] # Buffer for generated python code + multiline = dedent = oneline = False + template = self.source if self.source else open(self.filename).read() + + def yield_tokens(line): + for i, part in enumerate(re.split(r'\{\{(.*?)\}\}', line)): + if i % 2: + if part.startswith('!'): yield 'RAW', part[1:] + else: yield 'CMD', part + else: yield 'TXT', part + + def flush(): # Flush the ptrbuffer + if not ptrbuffer: return + cline = '' + for line in ptrbuffer: + for token, value in line: + if token == 'TXT': cline += repr(value) + elif token == 'RAW': cline += '_str(%s)' % value + elif token == 'CMD': cline += '_escape(%s)' % value + cline += ', ' + cline = cline[:-2] + '\\\n' + cline = cline[:-2] + if cline[:-1].endswith('\\\\\\\\\\n'): + cline = cline[:-7] + cline[-1] # 'nobr\\\\\n' --> 'nobr' + cline = '_printlist([' + cline + '])' + del ptrbuffer[:] # Do this before calling code() again + code(cline) + + def code(stmt): + for line in stmt.splitlines(): + codebuffer.append(' ' * len(stack) + line.strip()) + + for line in template.splitlines(True): + lineno += 1 + line = line if isinstance(line, unicode)\ + else unicode(line, encoding=self.encoding) + if lineno <= 2: + m = re.search(r"%.*coding[:=]\s*([-\w\.]+)", line) + if m: self.encoding = m.group(1) + if m: line = line.replace('coding','coding (removed)') + if line.strip()[:2].count('%') == 1: + line = line.split('%',1)[1].lstrip() # Full line following the % + cline = self.split_comment(line).strip() + cmd = re.split(r'[^a-zA-Z0-9_]', cline)[0] + flush() ##encodig (TODO: why?) + if cmd in self.blocks or multiline: + cmd = multiline or cmd + dedent = cmd in self.dedent_blocks # "else:" + if dedent and not oneline and not multiline: + cmd = stack.pop() + code(line) + oneline = not cline.endswith(':') # "if 1: pass" + multiline = cmd if cline.endswith('\\') else False + if not oneline and not multiline: + stack.append(cmd) + elif cmd == 'end' and stack: + code('#end(%s) %s' % (stack.pop(), line.strip()[3:])) + elif cmd == 'include': + p = cline.split(None, 2)[1:] + if len(p) == 2: + code("_=_include(%s, _stdout, %s)" % (repr(p[0]), p[1])) + elif p: + code("_=_include(%s, _stdout)" % repr(p[0])) + else: # Empty %include -> reverse of %rebase + code("_printlist(_base)") + elif cmd == 'rebase': + p = cline.split(None, 2)[1:] + if len(p) == 2: + code("globals()['_rebase']=(%s, dict(%s))" % (repr(p[0]), p[1])) + elif p: + code("globals()['_rebase']=(%s, {})" % repr(p[0])) + else: + code(line) + else: # Line starting with text (not '%') or '%%' (escaped) + if line.strip().startswith('%%'): + line = line.replace('%%', '%', 1) + ptrbuffer.append(yield_tokens(line)) + flush() + return '\n'.join(codebuffer) + '\n' + + def subtemplate(self, _name, _stdout, *args, **kwargs): + for dictarg in args: kwargs.update(dictarg) + if _name not in self.cache: + self.cache[_name] = self.__class__(name=_name, lookup=self.lookup) + return self.cache[_name].execute(_stdout, kwargs) + + def execute(self, _stdout, *args, **kwargs): + for dictarg in args: kwargs.update(dictarg) + env = self.defaults.copy() + env.update({'_stdout': _stdout, '_printlist': _stdout.extend, + '_include': self.subtemplate, '_str': self._str, + '_escape': self._escape}) + env.update(kwargs) + eval(self.co, env) + if '_rebase' in env: + subtpl, rargs = env['_rebase'] + subtpl = self.__class__(name=subtpl, lookup=self.lookup) + rargs['_base'] = _stdout[:] #copy stdout + del _stdout[:] # clear stdout + return subtpl.execute(_stdout, rargs) + return env + + def render(self, *args, **kwargs): + """ Render the template using keyword arguments as local variables. """ + for dictarg in args: kwargs.update(dictarg) + stdout = [] + self.execute(stdout, kwargs) + return ''.join(stdout) + + +def template(*args, **kwargs): + ''' + Get a rendered template as a string iterator. + You can use a name, a filename or a template string as first parameter. + Template rendering arguments can be passed as dictionaries + or directly (as keyword arguments). + ''' + tpl = args[0] if args else None + template_adapter = kwargs.pop('template_adapter', SimpleTemplate) + if tpl not in TEMPLATES or DEBUG: + settings = kwargs.pop('template_settings', {}) + lookup = kwargs.pop('template_lookup', TEMPLATE_PATH) + if isinstance(tpl, template_adapter): + TEMPLATES[tpl] = tpl + if settings: TEMPLATES[tpl].prepare(**settings) + elif "\n" in tpl or "{" in tpl or "%" in tpl or '$' in tpl: + TEMPLATES[tpl] = template_adapter(source=tpl, lookup=lookup, **settings) + else: + TEMPLATES[tpl] = template_adapter(name=tpl, lookup=lookup, **settings) + if not TEMPLATES[tpl]: + abort(500, 'Template (%s) not found' % tpl) + for dictarg in args[1:]: kwargs.update(dictarg) + return TEMPLATES[tpl].render(kwargs) + +mako_template = functools.partial(template, template_adapter=MakoTemplate) +cheetah_template = functools.partial(template, template_adapter=CheetahTemplate) +jinja2_template = functools.partial(template, template_adapter=Jinja2Template) +simpletal_template = functools.partial(template, template_adapter=SimpleTALTemplate) + +def view(tpl_name, **defaults): + ''' Decorator: renders a template for a handler. + The handler can control its behavior like that: + + - return a dict of template vars to fill out the template + - return something other than a dict and the view decorator will not + process the template, but return the handler result as is. + This includes returning a HTTPResponse(dict) to get, + for instance, JSON with autojson or other castfilters. + ''' + def decorator(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + result = func(*args, **kwargs) + if isinstance(result, (dict, DictMixin)): + tplvars = defaults.copy() + tplvars.update(result) + return template(tpl_name, **tplvars) + return result + return wrapper + return decorator + +mako_view = functools.partial(view, template_adapter=MakoTemplate) +cheetah_view = functools.partial(view, template_adapter=CheetahTemplate) +jinja2_view = functools.partial(view, template_adapter=Jinja2Template) +simpletal_view = functools.partial(view, template_adapter=SimpleTALTemplate) + + + + + +############################################################################### +# Constants and Globals ######################################################## +############################################################################### + +TEMPLATE_PATH = ['./', './views/'] +TEMPLATES = {} +DEBUG = False +MEMFILE_MAX = 1024*100 + +#: A dict to map HTTP status codes (e.g. 404) to phrases (e.g. 'Not Found') +HTTP_CODES = httplib.responses +HTTP_CODES[418] = "I'm a teapot" # RFC 2324 + +#: The default template used for error pages. Override with @error() +ERROR_PAGE_TEMPLATE = """ +%try: + %from bottle import DEBUG, HTTP_CODES, request + %status_name = HTTP_CODES.get(e.status, 'Unknown').title() + + + + Error {{e.status}}: {{status_name}} + + + +

Error {{e.status}}: {{status_name}}

+

Sorry, the requested URL {{request.url}} caused an error:

+
{{str(e.output)}}
+ %if DEBUG and e.exception: +

Exception:

+
{{repr(e.exception)}}
+ %end + %if DEBUG and e.traceback: +

Traceback:

+
{{e.traceback}}
+ %end + + +%except ImportError: + ImportError: Could not generate the error page. Please add bottle to sys.path +%end +""" + +#: A thread-save instance of :class:`Request` representing the `current` request. +request = Request() + +#: A thread-save instance of :class:`Response` used to build the HTTP response. +response = Response() + +#: A thread-save namepsace. Not used by Bottle. +local = threading.local() + +# Initialize app stack (create first empty Bottle app) +# BC: 0.6.4 and needed for run() +app = default_app = AppStack() +app.push() diff --git a/gae_index.py b/gae_index.py new file mode 100644 index 0000000..99ae517 --- /dev/null +++ b/gae_index.py @@ -0,0 +1,24 @@ +from google.appengine.ext import webapp +from google.appengine.ext.webapp.util import run_wsgi_app + +from qrmaker import QRMaker +from qrmaker import QRPageHandler + +class MainPage(webapp.RequestHandler): + def get(self): + self.response.headers['Content-Type'] = 'text/plain' + self.response.out.write('Hello, webapp World!') + +application = webapp.WSGIApplication( + [ + ('/', MainPage), + ('/qrmaker', QRPageHandler.QRPageHandler) + ], + debug=True) + +def main(): + run_wsgi_app(application) + + +if __name__ == "__main__": + main() diff --git a/html/index.html b/html/index.html new file mode 100644 index 0000000..77cf39a --- /dev/null +++ b/html/index.html @@ -0,0 +1,166 @@ + + + + + + + QR vCard Generator + + + + + + + + + + + + + + +
+

QR Code vCard Generator

+

Author: Fergal Moran Blog article

+
+ +
+
+ +
+
+ +
+
+

vCard Details

+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +

Please end lines with a ,

+
+
+ + +

Please end lines with a ,

+
+
+
+
+ + diff --git a/html/qrcode.html b/html/qrcode.html new file mode 100644 index 0000000..aa6c3b8 --- /dev/null +++ b/html/qrcode.html @@ -0,0 +1,124 @@ + + + + + + + QR vCard Generator + + + + + + + + + + + + + + +
+

QR Code vCard Generator

+

Author: Fergal Moran Blog article

+
+ +
+ QRCode should be here +
+ + + diff --git a/html/qrcode.png b/html/qrcode.png new file mode 100644 index 0000000000000000000000000000000000000000..eafd2420b94670c51c468810f1755a206de784d4 GIT binary patch literal 4287 zcmYjV3pmsJAC{9-OzxMNOGor~*W`#c3TY#exr}maa*$AB8z`gfDe$F=s*-;amk6*p4;TC+md#{3)vJ5^xu}~`uGsm#p6~e^L`JO`p2Ken= zPo>si=_(K5n2fV0*)QR>LEe(FDsD~D+dJFetSyf3d>%R=_SMt$jKsdze_8PTt}4!X z-u}1MA1|~k9Sp^mf9in_%x=e!* zKjvQPaMdMEtDD?A7?Y^VZ)ZhKa(5vEC1J4;%_4mtH8@V7UowxmJb9Vag$bsG5X5O7 z%y8I-(z`DrGx9sUr(GJ<^_JZ?(YT0zyR4p1P>0A}Z8qm$$s1E&r#K{L1|6n>;p2H* z>eoJ59^nJsJJ=>a7$oa0zZ?s8y_CW@iossNEHC%HodptIm9n~1f1g^KD?Lv8?bc5? z3XZOrGaCR;QoQWKq;KbZTrn-l!U>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`LWZC;9G5Ya9d{#0Zn?*RI^m2-*ATX9;3_{h(p0Um*^e( zeVhRJ!wmMwQR*DY87Itt4Sl!Ocai3yh$-{OHGL(H#hKm!rBkSwl+H07%K zys3gB-*N(~=a#$9OD6Tjiqb`bz6i#I9oxk2>cYS$a89_0Zh`-9GG|up91GwWE`0Id z)lp|KT|H0jPeCT7uG=3JJ$!#A)rT-dcJ@-ch+C$%T{hY_F64z++163p`P~Ct!R^JM jJ#Xeva&KZ^zmA!>x$9S!E6Mpsg3s!#twojj<+%R>2)5f) literal 0 HcmV?d00001 diff --git a/html/style.css b/html/style.css new file mode 100644 index 0000000..e94e654 --- /dev/null +++ b/html/style.css @@ -0,0 +1,27 @@ + diff --git a/index.py b/index.py new file mode 100644 index 0000000..66186b6 --- /dev/null +++ b/index.py @@ -0,0 +1,82 @@ +import logging +import sys +import os +sys.path.insert(0, os.path.dirname(__file__)) + +def initLogging(): + logging.basicConfig(level=logging.DEBUG + ,format='%(asctime)s [[%(levelname)s]] %(message)s' + ,datefmt='%d %b %y %H:%M' + ,filename='/tmp/qrmaker.log' + ,filemode='a') +import bottle +from bottle import route, request, redirect, run, template, static_file +from qrmaker import QRMaker +from auth import rpxtokenurl +from model import user + +initLogging() +logging.debug("Path: " + os.path.dirname(__file__) + '/views/') +bottle.TEMPLATE_PATH.insert(0, os.path.dirname(__file__) + '/views/') + +@route('/favicon.ico') +def favicon(): + return static_file('favicon.ico', root=os.path.dirname(__file__) + '/static/images') + +@route('/static/:directory/:filename') +def server_static(directory, filename): + return static_file(filename, root=os.path.dirname(__file__) + '/static/%s' % directory) + +@route('/css/:filename') +def server_static(filename): + return static_file(filename, root=os.path.dirname(__file__) + '/views/css') + +@route('/js/:filename') +def server_static(filename): + return static_file(filename, root=os.path.dirname(__file__) + '/views/js') + +@route('auth_proxy', method='POST') +def auth_proxy(): + ret = rpxtokenurl.rpx_response(request.forms.get('token')) + if type(ret).__name__ == 'dict': + newUser = user.UserController(ret) + newUser.generatePermalink() + return template('qrcode') + else: + return ret + +@route('/permalink/:id') +def permalink(id=''): + if id == '': + return template('qrcode', id='', linkurl='Invalid qrcode id') + else: + qr = QRMaker.QRMaker() + linkUrl = 'Here is your permalink for this vcard
Link' % (request['HTTP_HOST'], qr.generatePermalink(id)) + return template( + 'qrcode', + id=id, + linkurl=linkUrl + ) + +@route('/qrcode') +def index(): + if id == '': + return 'Invalid qrcode id specified' + else: + return template('qrcode', id='', linkurl='') + +@route('/:name') +def index(name='World'): + return template('qrform') + +@route('/') +def index(): + return template('qrform') + +@route('/genqr', method='POST') +def gen_qrvcard(): + qr = QRMaker.QRMaker() + uid = qr.createVCard(request.forms) + return template('qrcode', id=uid, linkurl='') + +application = bottle.default_app() diff --git a/model/__init__.py b/model/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/model/controller.py b/model/controller.py new file mode 100644 index 0000000..1631697 --- /dev/null +++ b/model/controller.py @@ -0,0 +1,9 @@ +from pymongo import Connection +import logging + +class Controller: + def __init__(self): + self._cn = Connection() + self.DB = self._cn.qrmaker + logging.debug("Created database connection") + diff --git a/model/user.py b/model/user.py new file mode 100644 index 0000000..dda3a11 --- /dev/null +++ b/model/user.py @@ -0,0 +1,27 @@ +import logging +import pymongo +import gridfs +import pdb +import controller +class UserController(): + def __init__(self, items): + logging.debug("Created a user") + self._controller = controller.Controller() + + self._profile = items['profile'] + self._id = self._profile['identifier'] + + + def generatePermalink(self): + fs = gridfs.GridFS(self._controller.DB) + + logging.debug("Generating permalink") + self._write() + + def _write(self): + pdb.set_trace() + blob = { + "_id" : self._id, + "profile" : self._profile + } + self._controller.DB.users.insert(blob) diff --git a/qrmaker/QRMaker.py b/qrmaker/QRMaker.py new file mode 100644 index 0000000..e6f899f --- /dev/null +++ b/qrmaker/QRMaker.py @@ -0,0 +1,46 @@ +from pygooglechart import QRChart +import logging +import re +import uuid +import shutil + +HEIGHT = 220 +WIDTH = 220 + +vCardTemplate = """BEGIN:VCARD +N:{SURNAME};{FIRSTNAME} +TEL;CELL:{TELMOBILE} +TEL;HOME:{TELHOME} +EMAIL:{EMAIL} +URL:{URL} +END:VCARD""" + +class QRMaker: + def __init__(self): + self._templateData = vCardTemplate + + def createVCard(self, data): + logging.debug("In createVCard") + chart = QRChart(HEIGHT, WIDTH) + templateData = "" + + for k, v in data.items(): + templateData = self._templateData.replace("{%s}" % k, v) + self._templateData = templateData + + match = re.sub(r'{\w*\w}', '', templateData) + + chart.add_data(match) + + chart.set_ec('H', 0) + uid = uuid.uuid1() + + chart.download('static/cache/%s.png' % uid) + return uid + + def generatePermalink(self, id): + shutil.copyfile( + 'static/cache/%s.png' % id, + 'static/images/permalinked/%s.png' % id + ) + return 'static/images/permalinked/%s.png' % id diff --git a/qrmaker/QRPageHandler.py b/qrmaker/QRPageHandler.py new file mode 100644 index 0000000..ca3432c --- /dev/null +++ b/qrmaker/QRPageHandler.py @@ -0,0 +1,7 @@ +from google.appengine.ext import webapp +from google.appengine.ext.webapp.util import run_wsgi_app + +class QRPageHandler(webapp.RequestHandler): + def get(self): + self.response.headers['Content-Type'] = 'text/plain' + self.response.out.write('Hello, qrmaker') diff --git a/qrmaker/__init__.py b/qrmaker/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/qrmaker/pygooglechart.py b/qrmaker/pygooglechart.py new file mode 100644 index 0000000..8a76825 --- /dev/null +++ b/qrmaker/pygooglechart.py @@ -0,0 +1,1161 @@ +""" +pygooglechart - A complete Python wrapper for the Google Chart API + +http://pygooglechart.slowchop.com/ + +Copyright 2007-2009 Gerald Kaszuba + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . + +""" +from __future__ import division + +import os +import urllib +import urllib2 +import math +import random +import re +import warnings +import copy + +# Helper variables and functions +# ----------------------------------------------------------------------------- + +__version__ = '0.3.0' +__author__ = 'Gerald Kaszuba' + +reo_colour = re.compile('^([A-Fa-f0-9]{2,2}){3,4}$') + +def _check_colour(colour): + if not reo_colour.match(colour): + raise InvalidParametersException('Colours need to be in ' \ + 'RRGGBB or RRGGBBAA format. One of your colours has %s' % \ + colour) + + +def _reset_warnings(): + """Helper function to reset all warnings. Used by the unit tests.""" + globals()['__warningregistry__'] = None + + +# Exception Classes +# ----------------------------------------------------------------------------- + + +class PyGoogleChartException(Exception): + pass + + +class DataOutOfRangeException(PyGoogleChartException): + pass + + +class UnknownDataTypeException(PyGoogleChartException): + pass + + +class NoDataGivenException(PyGoogleChartException): + pass + + +class InvalidParametersException(PyGoogleChartException): + pass + + +class BadContentTypeException(PyGoogleChartException): + pass + + +class AbstractClassException(PyGoogleChartException): + pass + + +class UnknownChartType(PyGoogleChartException): + pass + +class UnknownCountryCodeException(PyGoogleChartException): + pass + +# Data Classes +# ----------------------------------------------------------------------------- + + +class Data(object): + + def __init__(self, data): + if type(self) == Data: + raise AbstractClassException('This is an abstract class') + self.data = data + + @classmethod + def float_scale_value(cls, value, range): + lower, upper = range + assert(upper > lower) + scaled = (value - lower) * (cls.max_value / (upper - lower)) + return scaled + + @classmethod + def clip_value(cls, value): + return max(0, min(value, cls.max_value)) + + @classmethod + def int_scale_value(cls, value, range): + return int(round(cls.float_scale_value(value, range))) + + @classmethod + def scale_value(cls, value, range): + scaled = cls.int_scale_value(value, range) + clipped = cls.clip_value(scaled) + Data.check_clip(scaled, clipped) + return clipped + + @staticmethod + def check_clip(scaled, clipped): + if clipped != scaled: + warnings.warn('One or more of of your data points has been ' + 'clipped because it is out of range.') + + +class SimpleData(Data): + + max_value = 61 + enc_map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' + + def __repr__(self): + encoded_data = [] + for data in self.data: + sub_data = [] + for value in data: + if value is None: + sub_data.append('_') + elif value >= 0 and value <= self.max_value: + sub_data.append(SimpleData.enc_map[value]) + else: + raise DataOutOfRangeException('cannot encode value: %d' + % value) + encoded_data.append(''.join(sub_data)) + return 'chd=s:' + ','.join(encoded_data) + + +class TextData(Data): + + max_value = 100 + + def __repr__(self): + encoded_data = [] + for data in self.data: + sub_data = [] + for value in data: + if value is None: + sub_data.append(-1) + elif value >= 0 and value <= self.max_value: + sub_data.append("%.1f" % float(value)) + else: + raise DataOutOfRangeException() + encoded_data.append(','.join(sub_data)) + return 'chd=t:' + '%7c'.join(encoded_data) + + @classmethod + def scale_value(cls, value, range): + # use float values instead of integers because we don't need an encode + # map index + scaled = cls.float_scale_value(value, range) + clipped = cls.clip_value(scaled) + Data.check_clip(scaled, clipped) + return clipped + + +class ExtendedData(Data): + + max_value = 4095 + enc_map = \ + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.' + + def __repr__(self): + encoded_data = [] + enc_size = len(ExtendedData.enc_map) + for data in self.data: + sub_data = [] + for value in data: + if value is None: + sub_data.append('__') + elif value >= 0 and value <= self.max_value: + first, second = divmod(int(value), enc_size) + sub_data.append('%s%s' % ( + ExtendedData.enc_map[first], + ExtendedData.enc_map[second])) + else: + raise DataOutOfRangeException( \ + 'Item #%i "%s" is out of range' % (data.index(value), \ + value)) + encoded_data.append(''.join(sub_data)) + return 'chd=e:' + ','.join(encoded_data) + + +# Axis Classes +# ----------------------------------------------------------------------------- + + +class Axis(object): + + BOTTOM = 'x' + TOP = 't' + LEFT = 'y' + RIGHT = 'r' + TYPES = (BOTTOM, TOP, LEFT, RIGHT) + + def __init__(self, axis_index, axis_type, **kw): + assert(axis_type in Axis.TYPES) + self.has_style = False + self.axis_index = axis_index + self.axis_type = axis_type + self.positions = None + + def set_index(self, axis_index): + self.axis_index = axis_index + + def set_positions(self, positions): + self.positions = positions + + def set_style(self, colour, font_size=None, alignment=None): + _check_colour(colour) + self.colour = colour + self.font_size = font_size + self.alignment = alignment + self.has_style = True + + def style_to_url(self): + bits = [] + bits.append(str(self.axis_index)) + bits.append(self.colour) + if self.font_size is not None: + bits.append(str(self.font_size)) + if self.alignment is not None: + bits.append(str(self.alignment)) + return ','.join(bits) + + def positions_to_url(self): + bits = [] + bits.append(str(self.axis_index)) + bits += [str(a) for a in self.positions] + return ','.join(bits) + + +class LabelAxis(Axis): + + def __init__(self, axis_index, axis_type, values, **kwargs): + Axis.__init__(self, axis_index, axis_type, **kwargs) + self.values = [str(a) for a in values] + + def __repr__(self): + return '%i:%%7c%s' % (self.axis_index, '%7c'.join(self.values)) + + +class RangeAxis(Axis): + + def __init__(self, axis_index, axis_type, low, high, **kwargs): + Axis.__init__(self, axis_index, axis_type, **kwargs) + self.low = low + self.high = high + + def __repr__(self): + return '%i,%s,%s' % (self.axis_index, self.low, self.high) + +# Chart Classes +# ----------------------------------------------------------------------------- + + +class Chart(object): + """Abstract class for all chart types. + + width are height specify the dimensions of the image. title sets the title + of the chart. legend requires a list that corresponds to datasets. + """ + + BASE_URL = 'http://chart.apis.google.com/chart' + BACKGROUND = 'bg' + CHART = 'c' + ALPHA = 'a' + VALID_SOLID_FILL_TYPES = (BACKGROUND, CHART, ALPHA) + SOLID = 's' + LINEAR_GRADIENT = 'lg' + LINEAR_STRIPES = 'ls' + + def __init__(self, width, height, title=None, legend=None, colours=None, + auto_scale=True, x_range=None, y_range=None, + colours_within_series=None): + if type(self) == Chart: + raise AbstractClassException('This is an abstract class') + assert(isinstance(width, int)) + assert(isinstance(height, int)) + self.width = width + self.height = height + self.data = [] + self.set_title(title) + self.set_title_style(None, None) + self.set_legend(legend) + self.set_legend_position(None) + self.set_colours(colours) + self.set_colours_within_series(colours_within_series) + + # Data for scaling. + self.auto_scale = auto_scale # Whether to automatically scale data + self.x_range = x_range # (min, max) x-axis range for scaling + self.y_range = y_range # (min, max) y-axis range for scaling + self.scaled_data_class = None + self.scaled_x_range = None + self.scaled_y_range = None + + self.fill_types = { + Chart.BACKGROUND: None, + Chart.CHART: None, + Chart.ALPHA: None, + } + self.fill_area = { + Chart.BACKGROUND: None, + Chart.CHART: None, + Chart.ALPHA: None, + } + self.axis = [] + self.markers = [] + self.line_styles = {} + self.grid = None + self.title_colour = None + self.title_font_size = None + + # URL generation + # ------------------------------------------------------------------------- + + def get_url(self, data_class=None): + return self.BASE_URL + '?' + self.get_url_extension(data_class) + + def get_url_extension(self, data_class=None): + url_bits = self.get_url_bits(data_class=data_class) + return '&'.join(url_bits) + + def get_url_bits(self, data_class=None): + url_bits = [] + # required arguments + url_bits.append(self.type_to_url()) + url_bits.append('chs=%ix%i' % (self.width, self.height)) + url_bits.append(self.data_to_url(data_class=data_class)) + # optional arguments + if self.title: + url_bits.append('chtt=%s' % self.title) + if self.title_colour and self.title_font_size: + url_bits.append('chts=%s,%s' % (self.title_colour, \ + self.title_font_size)) + if self.legend: + url_bits.append('chdl=%s' % '%7c'.join(self.legend)) + if self.legend_position: + url_bits.append('chdlp=%s' % (self.legend_position)) + if self.colours: + url_bits.append('chco=%s' % ','.join(self.colours)) + if self.colours_within_series: + url_bits.append('chco=%s' % '%7c'.join(self.colours_within_series)) + ret = self.fill_to_url() + if ret: + url_bits.append(ret) + ret = self.axis_to_url() + if ret: + url_bits.append(ret) + if self.markers: + url_bits.append(self.markers_to_url()) + if self.line_styles: + style = [] + for index in xrange(max(self.line_styles) + 1): + if index in self.line_styles: + values = self.line_styles[index] + else: + values = ('1', ) + style.append(','.join(values)) + url_bits.append('chls=%s' % '%7c'.join(style)) + if self.grid: + url_bits.append('chg=%s' % self.grid) + return url_bits + + # Downloading + # ------------------------------------------------------------------------- + + def download(self, file_name, use_post=True): + if use_post: + opener = urllib2.urlopen(self.BASE_URL, self.get_url_extension()) + else: + opener = urllib2.urlopen(self.get_url()) + + if opener.headers['content-type'] != 'image/png': + raise BadContentTypeException('Server responded with a ' \ + 'content-type of %s' % opener.headers['content-type']) + + open(file_name, 'wb').write(opener.read()) + + # Simple settings + # ------------------------------------------------------------------------- + + def set_title(self, title): + if title: + self.title = urllib.quote(title) + else: + self.title = None + + def set_title_style(self, colour=None, font_size=None): + if not colour is None: + _check_colour(colour) + if not colour and not font_size: + return + self.title_colour = colour or '333333' + self.title_font_size = font_size or 13.5 + + def set_legend(self, legend): + """legend needs to be a list, tuple or None""" + assert(isinstance(legend, list) or isinstance(legend, tuple) or + legend is None) + if legend: + self.legend = [urllib.quote(a) for a in legend] + else: + self.legend = None + + def set_legend_position(self, legend_position): + if legend_position: + self.legend_position = urllib.quote(legend_position) + else: + self.legend_position = None + + # Chart colours + # ------------------------------------------------------------------------- + + def set_colours(self, colours): + # colours needs to be a list, tuple or None + assert(isinstance(colours, list) or isinstance(colours, tuple) or + colours is None) + # make sure the colours are in the right format + if colours: + for col in colours: + _check_colour(col) + self.colours = colours + + def set_colours_within_series(self, colours): + # colours needs to be a list, tuple or None + assert(isinstance(colours, list) or isinstance(colours, tuple) or + colours is None) + # make sure the colours are in the right format + if colours: + for col in colours: + _check_colour(col) + self.colours_within_series = colours + + # Background/Chart colours + # ------------------------------------------------------------------------- + + def fill_solid(self, area, colour): + assert(area in Chart.VALID_SOLID_FILL_TYPES) + _check_colour(colour) + self.fill_area[area] = colour + self.fill_types[area] = Chart.SOLID + + def _check_fill_linear(self, angle, *args): + assert(isinstance(args, list) or isinstance(args, tuple)) + assert(angle >= 0 and angle <= 90) + assert(len(args) % 2 == 0) + args = list(args) # args is probably a tuple and we need to mutate + for a in xrange(int(len(args) / 2)): + col = args[a * 2] + offset = args[a * 2 + 1] + _check_colour(col) + assert(offset >= 0 and offset <= 1) + args[a * 2 + 1] = str(args[a * 2 + 1]) + return args + + def fill_linear_gradient(self, area, angle, *args): + assert(area in Chart.VALID_SOLID_FILL_TYPES) + args = self._check_fill_linear(angle, *args) + self.fill_types[area] = Chart.LINEAR_GRADIENT + self.fill_area[area] = ','.join([str(angle)] + args) + + def fill_linear_stripes(self, area, angle, *args): + assert(area in Chart.VALID_SOLID_FILL_TYPES) + args = self._check_fill_linear(angle, *args) + self.fill_types[area] = Chart.LINEAR_STRIPES + self.fill_area[area] = ','.join([str(angle)] + args) + + def fill_to_url(self): + areas = [] + for area in (Chart.BACKGROUND, Chart.CHART, Chart.ALPHA): + if self.fill_types[area]: + areas.append('%s,%s,%s' % (area, self.fill_types[area], \ + self.fill_area[area])) + if areas: + return 'chf=' + '%7c'.join(areas) + + # Data + # ------------------------------------------------------------------------- + + def data_class_detection(self, data): + """Determines the appropriate data encoding type to give satisfactory + resolution (http://code.google.com/apis/chart/#chart_data). + """ + assert(isinstance(data, list) or isinstance(data, tuple)) + if not isinstance(self, (LineChart, BarChart, ScatterChart)): + # From the link above: + # Simple encoding is suitable for all other types of chart + # regardless of size. + return SimpleData + elif self.height < 100: + # The link above indicates that line and bar charts less + # than 300px in size can be suitably represented with the + # simple encoding. I've found that this isn't sufficient, + # e.g. examples/line-xy-circle.png. Let's try 100px. + return SimpleData + else: + return ExtendedData + + def _filter_none(self, data): + return [r for r in data if r is not None] + + def data_x_range(self): + """Return a 2-tuple giving the minimum and maximum x-axis + data range. + """ + try: + lower = min([min(self._filter_none(s)) + for type, s in self.annotated_data() + if type == 'x']) + upper = max([max(self._filter_none(s)) + for type, s in self.annotated_data() + if type == 'x']) + return (lower, upper) + except ValueError: + return None # no x-axis datasets + + def data_y_range(self): + """Return a 2-tuple giving the minimum and maximum y-axis + data range. + """ + try: + lower = min([min(self._filter_none(s)) + for type, s in self.annotated_data() + if type == 'y']) + upper = max([max(self._filter_none(s)) + 1 + for type, s in self.annotated_data() + if type == 'y']) + return (lower, upper) + except ValueError: + return None # no y-axis datasets + + def scaled_data(self, data_class, x_range=None, y_range=None): + """Scale `self.data` as appropriate for the given data encoding + (data_class) and return it. + + An optional `y_range` -- a 2-tuple (lower, upper) -- can be + given to specify the y-axis bounds. If not given, the range is + inferred from the data: (0, ) presuming no negative + values, or (, ) if there are negative + values. `self.scaled_y_range` is set to the actual lower and + upper scaling range. + + Ditto for `x_range`. Note that some chart types don't have x-axis + data. + """ + self.scaled_data_class = data_class + + # Determine the x-axis range for scaling. + if x_range is None: + x_range = self.data_x_range() + if x_range and x_range[0] > 0: + x_range = (x_range[0], x_range[1]) + self.scaled_x_range = x_range + + # Determine the y-axis range for scaling. + if y_range is None: + y_range = self.data_y_range() + if y_range and y_range[0] > 0: + y_range = (y_range[0], y_range[1]) + self.scaled_y_range = y_range + + scaled_data = [] + for type, dataset in self.annotated_data(): + if type == 'x': + scale_range = x_range + elif type == 'y': + scale_range = y_range + elif type == 'marker-size': + scale_range = (0, max(dataset)) + scaled_dataset = [] + for v in dataset: + if v is None: + scaled_dataset.append(None) + else: + scaled_dataset.append( + data_class.scale_value(v, scale_range)) + scaled_data.append(scaled_dataset) + return scaled_data + + def add_data(self, data): + self.data.append(data) + return len(self.data) - 1 # return the "index" of the data set + + def data_to_url(self, data_class=None): + if not data_class: + data_class = self.data_class_detection(self.data) + if not issubclass(data_class, Data): + raise UnknownDataTypeException() + if self.auto_scale: + data = self.scaled_data(data_class, self.x_range, self.y_range) + else: + data = self.data + return repr(data_class(data)) + + def annotated_data(self): + for dataset in self.data: + yield ('x', dataset) + + # Axis Labels + # ------------------------------------------------------------------------- + + def set_axis_labels(self, axis_type, values): + assert(axis_type in Axis.TYPES) + values = [urllib.quote(str(a)) for a in values] + axis_index = len(self.axis) + axis = LabelAxis(axis_index, axis_type, values) + self.axis.append(axis) + return axis_index + + def set_axis_range(self, axis_type, low, high): + assert(axis_type in Axis.TYPES) + axis_index = len(self.axis) + axis = RangeAxis(axis_index, axis_type, low, high) + self.axis.append(axis) + return axis_index + + def set_axis_positions(self, axis_index, positions): + try: + self.axis[axis_index].set_positions(positions) + except IndexError: + raise InvalidParametersException('Axis index %i has not been ' \ + 'created' % axis) + + def set_axis_style(self, axis_index, colour, font_size=None, \ + alignment=None): + try: + self.axis[axis_index].set_style(colour, font_size, alignment) + except IndexError: + raise InvalidParametersException('Axis index %i has not been ' \ + 'created' % axis) + + def axis_to_url(self): + available_axis = [] + label_axis = [] + range_axis = [] + positions = [] + styles = [] + index = -1 + for axis in self.axis: + available_axis.append(axis.axis_type) + if isinstance(axis, RangeAxis): + range_axis.append(repr(axis)) + if isinstance(axis, LabelAxis): + label_axis.append(repr(axis)) + if axis.positions: + positions.append(axis.positions_to_url()) + if axis.has_style: + styles.append(axis.style_to_url()) + if not available_axis: + return + url_bits = [] + url_bits.append('chxt=%s' % ','.join(available_axis)) + if label_axis: + url_bits.append('chxl=%s' % '%7c'.join(label_axis)) + if range_axis: + url_bits.append('chxr=%s' % '%7c'.join(range_axis)) + if positions: + url_bits.append('chxp=%s' % '%7c'.join(positions)) + if styles: + url_bits.append('chxs=%s' % '%7c'.join(styles)) + return '&'.join(url_bits) + + # Markers, Ranges and Fill area (chm) + # ------------------------------------------------------------------------- + + def markers_to_url(self): + return 'chm=%s' % '%7c'.join([','.join(a) for a in self.markers]) + + def add_marker(self, index, point, marker_type, colour, size, priority=0): + self.markers.append((marker_type, colour, str(index), str(point), \ + str(size), str(priority))) + + def add_horizontal_range(self, colour, start, stop): + self.markers.append(('r', colour, '0', str(start), str(stop))) + + def add_data_line(self, colour, data_set, size, priority=0): + self.markers.append(('D', colour, str(data_set), '0', str(size), \ + str(priority))) + + def add_marker_text(self, string, colour, data_set, data_point, size, \ + priority=0): + self.markers.append((str(string), colour, str(data_set), \ + str(data_point), str(size), str(priority))) + + def add_vertical_range(self, colour, start, stop): + self.markers.append(('R', colour, '0', str(start), str(stop))) + + def add_fill_range(self, colour, index_start, index_end): + self.markers.append(('b', colour, str(index_start), str(index_end), \ + '1')) + + def add_fill_simple(self, colour): + self.markers.append(('B', colour, '1', '1', '1')) + + # Line styles + # ------------------------------------------------------------------------- + + def set_line_style(self, index, thickness=1, line_segment=None, \ + blank_segment=None): + value = [] + value.append(str(thickness)) + if line_segment: + value.append(str(line_segment)) + value.append(str(blank_segment)) + self.line_styles[index] = value + + # Grid + # ------------------------------------------------------------------------- + + def set_grid(self, x_step, y_step, line_segment=1, \ + blank_segment=0): + self.grid = '%s,%s,%s,%s' % (x_step, y_step, line_segment, \ + blank_segment) + + +class ScatterChart(Chart): + + def type_to_url(self): + return 'cht=s' + + def annotated_data(self): + yield ('x', self.data[0]) + yield ('y', self.data[1]) + if len(self.data) > 2: + # The optional third dataset is relative sizing for point + # markers. + yield ('marker-size', self.data[2]) + + +class LineChart(Chart): + + def __init__(self, *args, **kwargs): + if type(self) == LineChart: + raise AbstractClassException('This is an abstract class') + Chart.__init__(self, *args, **kwargs) + + +class SimpleLineChart(LineChart): + + def type_to_url(self): + return 'cht=lc' + + def annotated_data(self): + # All datasets are y-axis data. + for dataset in self.data: + yield ('y', dataset) + + +class SparkLineChart(SimpleLineChart): + + def type_to_url(self): + return 'cht=ls' + + +class XYLineChart(LineChart): + + def type_to_url(self): + return 'cht=lxy' + + def annotated_data(self): + # Datasets alternate between x-axis, y-axis. + for i, dataset in enumerate(self.data): + if i % 2 == 0: + yield ('x', dataset) + else: + yield ('y', dataset) + + +class BarChart(Chart): + + def __init__(self, *args, **kwargs): + if type(self) == BarChart: + raise AbstractClassException('This is an abstract class') + Chart.__init__(self, *args, **kwargs) + self.bar_width = None + self.zero_lines = {} + + def set_bar_width(self, bar_width): + self.bar_width = bar_width + + def set_zero_line(self, index, zero_line): + self.zero_lines[index] = zero_line + + def get_url_bits(self, data_class=None, skip_chbh=False): + url_bits = Chart.get_url_bits(self, data_class=data_class) + if not skip_chbh and self.bar_width is not None: + url_bits.append('chbh=%i' % self.bar_width) + zero_line = [] + if self.zero_lines: + for index in xrange(max(self.zero_lines) + 1): + if index in self.zero_lines: + zero_line.append(str(self.zero_lines[index])) + else: + zero_line.append('0') + url_bits.append('chp=%s' % ','.join(zero_line)) + return url_bits + + +class StackedHorizontalBarChart(BarChart): + + def type_to_url(self): + return 'cht=bhs' + + +class StackedVerticalBarChart(BarChart): + + def type_to_url(self): + return 'cht=bvs' + + def annotated_data(self): + for dataset in self.data: + yield ('y', dataset) + + +class GroupedBarChart(BarChart): + + def __init__(self, *args, **kwargs): + if type(self) == GroupedBarChart: + raise AbstractClassException('This is an abstract class') + BarChart.__init__(self, *args, **kwargs) + self.bar_spacing = None + self.group_spacing = None + + def set_bar_spacing(self, spacing): + """Set spacing between bars in a group.""" + self.bar_spacing = spacing + + def set_group_spacing(self, spacing): + """Set spacing between groups of bars.""" + self.group_spacing = spacing + + def get_url_bits(self, data_class=None): + # Skip 'BarChart.get_url_bits' and call Chart directly so the parent + # doesn't add "chbh" before we do. + url_bits = BarChart.get_url_bits(self, data_class=data_class, + skip_chbh=True) + if self.group_spacing is not None: + if self.bar_spacing is None: + raise InvalidParametersException('Bar spacing is required ' \ + 'to be set when setting group spacing') + if self.bar_width is None: + raise InvalidParametersException('Bar width is required to ' \ + 'be set when setting bar spacing') + url_bits.append('chbh=%i,%i,%i' + % (self.bar_width, self.bar_spacing, self.group_spacing)) + elif self.bar_spacing is not None: + if self.bar_width is None: + raise InvalidParametersException('Bar width is required to ' \ + 'be set when setting bar spacing') + url_bits.append('chbh=%i,%i' % (self.bar_width, self.bar_spacing)) + elif self.bar_width: + url_bits.append('chbh=%i' % self.bar_width) + return url_bits + + +class GroupedHorizontalBarChart(GroupedBarChart): + + def type_to_url(self): + return 'cht=bhg' + + +class GroupedVerticalBarChart(GroupedBarChart): + + def type_to_url(self): + return 'cht=bvg' + + def annotated_data(self): + for dataset in self.data: + yield ('y', dataset) + + +class PieChart(Chart): + + def __init__(self, *args, **kwargs): + if type(self) == PieChart: + raise AbstractClassException('This is an abstract class') + Chart.__init__(self, *args, **kwargs) + self.pie_labels = [] + if self.y_range: + warnings.warn('y_range is not used with %s.' % \ + (self.__class__.__name__)) + + def set_pie_labels(self, labels): + self.pie_labels = [urllib.quote(a) for a in labels] + + def get_url_bits(self, data_class=None): + url_bits = Chart.get_url_bits(self, data_class=data_class) + if self.pie_labels: + url_bits.append('chl=%s' % '%7c'.join(self.pie_labels)) + return url_bits + + def annotated_data(self): + # Datasets are all y-axis data. However, there should only be + # one dataset for pie charts. + for dataset in self.data: + yield ('x', dataset) + + def scaled_data(self, data_class, x_range=None, y_range=None): + if not x_range: + x_range = [0, sum(self.data[0])] + return Chart.scaled_data(self, data_class, x_range, self.y_range) + + +class PieChart2D(PieChart): + + def type_to_url(self): + return 'cht=p' + + +class PieChart3D(PieChart): + + def type_to_url(self): + return 'cht=p3' + + +class VennChart(Chart): + + def type_to_url(self): + return 'cht=v' + + def annotated_data(self): + for dataset in self.data: + yield ('y', dataset) + + +class RadarChart(Chart): + + def type_to_url(self): + return 'cht=r' + + +class SplineRadarChart(RadarChart): + + def type_to_url(self): + return 'cht=rs' + + +class MapChart(Chart): + + def __init__(self, *args, **kwargs): + Chart.__init__(self, *args, **kwargs) + self.geo_area = 'world' + self.codes = [] + self.__areas = ('africa', 'asia', 'europe', 'middle_east', + 'south_america', 'usa', 'world') + self.__ccodes = ( + 'AD', 'AE', 'AF', 'AG', 'AI', 'AL', 'AM', 'AN', 'AO', 'AQ', 'AR', + 'AS', 'AT', 'AU', 'AW', 'AX', 'AZ', 'BA', 'BB', 'BD', 'BE', 'BF', + 'BG', 'BH', 'BI', 'BJ', 'BL', 'BM', 'BN', 'BO', 'BR', 'BS', 'BT', + 'BV', 'BW', 'BY', 'BZ', 'CA', 'CC', 'CD', 'CF', 'CG', 'CH', 'CI', + 'CK', 'CL', 'CM', 'CN', 'CO', 'CR', 'CU', 'CV', 'CX', 'CY', 'CZ', + 'DE', 'DJ', 'DK', 'DM', 'DO', 'DZ', 'EC', 'EE', 'EG', 'EH', 'ER', + 'ES', 'ET', 'FI', 'FJ', 'FK', 'FM', 'FO', 'FR', 'GA', 'GB', 'GD', + 'GE', 'GF', 'GG', 'GH', 'GI', 'GL', 'GM', 'GN', 'GP', 'GQ', 'GR', + 'GS', 'GT', 'GU', 'GW', 'GY', 'HK', 'HM', 'HN', 'HR', 'HT', 'HU', + 'ID', 'IE', 'IL', 'IM', 'IN', 'IO', 'IQ', 'IR', 'IS', 'IT', 'JE', + 'JM', 'JO', 'JP', 'KE', 'KG', 'KH', 'KI', 'KM', 'KN', 'KP', 'KR', + 'KW', 'KY', 'KZ', 'LA', 'LB', 'LC', 'LI', 'LK', 'LR', 'LS', 'LT', + 'LU', 'LV', 'LY', 'MA', 'MC', 'MD', 'ME', 'MF', 'MG', 'MH', 'MK', + 'ML', 'MM', 'MN', 'MO', 'MP', 'MQ', 'MR', 'MS', 'MT', 'MU', 'MV', + 'MW', 'MX', 'MY', 'MZ', 'NA', 'NC', 'NE', 'NF', 'NG', 'NI', 'NL', + 'NO', 'NP', 'NR', 'NU', 'NZ', 'OM', 'PA', 'PE', 'PF', 'PG', 'PH', + 'PK', 'PL', 'PM', 'PN', 'PR', 'PS', 'PT', 'PW', 'PY', 'QA', 'RE', + 'RO', 'RS', 'RU', 'RW', 'SA', 'SB', 'SC', 'SD', 'SE', 'SG', 'SH', + 'SI', 'SJ', 'SK', 'SL', 'SM', 'SN', 'SO', 'SR', 'ST', 'SV', 'SY', + 'SZ', 'TC', 'TD', 'TF', 'TG', 'TH', 'TJ', 'TK', 'TL', 'TM', 'TN', + 'TO', 'TR', 'TT', 'TV', 'TW', 'TZ', 'UA', 'UG', 'UM', 'US', 'UY', + 'UZ', 'VA', 'VC', 'VE', 'VG', 'VI', 'VN', 'VU', 'WF', 'WS', 'YE', + 'YT', 'ZA', 'ZM', 'ZW') + + def type_to_url(self): + return 'cht=t' + + def set_codes(self, codes): + '''Set the country code map for the data. + Codes given in a list. + + i.e. DE - Germany + AT - Austria + US - United States + ''' + + codemap = '' + + for cc in codes: + cc = cc.upper() + if cc in self.__ccodes: + codemap += cc + else: + raise UnknownCountryCodeException(cc) + + self.codes = codemap + + def set_geo_area(self, area): + '''Sets the geo area for the map. + + * africa + * asia + * europe + * middle_east + * south_america + * usa + * world + ''' + + if area in self.__areas: + self.geo_area = area + else: + raise UnknownChartType('Unknown chart type for maps: %s' %area) + + def get_url_bits(self, data_class=None): + url_bits = Chart.get_url_bits(self, data_class=data_class) + url_bits.append('chtm=%s' % self.geo_area) + if self.codes: + url_bits.append('chld=%s' % ''.join(self.codes)) + return url_bits + + def add_data_dict(self, datadict): + '''Sets the data and country codes via a dictionary. + + i.e. {'DE': 50, 'GB': 30, 'AT': 70} + ''' + + self.set_codes(datadict.keys()) + self.add_data(datadict.values()) + + +class GoogleOMeterChart(PieChart): + """Inheriting from PieChart because of similar labeling""" + + def __init__(self, *args, **kwargs): + PieChart.__init__(self, *args, **kwargs) + if self.auto_scale and not self.x_range: + warnings.warn('Please specify an x_range with GoogleOMeterChart, ' + 'otherwise one arrow will always be at the max.') + + def type_to_url(self): + return 'cht=gom' + + +class QRChart(Chart): + + def __init__(self, *args, **kwargs): + Chart.__init__(self, *args, **kwargs) + self.encoding = None + self.ec_level = None + self.margin = None + + def type_to_url(self): + return 'cht=qr' + + def data_to_url(self, data_class=None): + if not self.data: + raise NoDataGivenException() + return 'chl=%s' % urllib.quote(self.data[0]) + + def get_url_bits(self, data_class=None): + url_bits = Chart.get_url_bits(self, data_class=data_class) + if self.encoding: + url_bits.append('choe=%s' % self.encoding) + if self.ec_level: + url_bits.append('chld=%s%%7c%s' % (self.ec_level, self.margin)) + return url_bits + + def set_encoding(self, encoding): + self.encoding = encoding + + def set_ec(self, level, margin): + self.ec_level = level + self.margin = margin + + +class ChartGrammar(object): + + def __init__(self): + self.grammar = None + self.chart = None + + def parse(self, grammar): + self.grammar = grammar + self.chart = self.create_chart_instance() + + for attr in self.grammar: + if attr in ('w', 'h', 'type', 'auto_scale', 'x_range', 'y_range'): + continue # These are already parsed in create_chart_instance + attr_func = 'parse_' + attr + if not hasattr(self, attr_func): + warnings.warn('No parser for grammar attribute "%s"' % (attr)) + continue + getattr(self, attr_func)(grammar[attr]) + + return self.chart + + def parse_data(self, data): + self.chart.data = data + + @staticmethod + def get_possible_chart_types(): + possible_charts = [] + for cls_name in globals().keys(): + if not cls_name.endswith('Chart'): + continue + cls = globals()[cls_name] + # Check if it is an abstract class + try: + a = cls(1, 1, auto_scale=False) + del a + except AbstractClassException: + continue + # Strip off "Class" + possible_charts.append(cls_name[:-5]) + return possible_charts + + def create_chart_instance(self, grammar=None): + if not grammar: + grammar = self.grammar + assert(isinstance(grammar, dict)) # grammar must be a dict + assert('w' in grammar) # width is required + assert('h' in grammar) # height is required + assert('type' in grammar) # type is required + chart_type = grammar['type'] + w = grammar['w'] + h = grammar['h'] + auto_scale = grammar.get('auto_scale', None) + x_range = grammar.get('x_range', None) + y_range = grammar.get('y_range', None) + types = ChartGrammar.get_possible_chart_types() + if chart_type not in types: + raise UnknownChartType('%s is an unknown chart type. Possible ' + 'chart types are %s' % (chart_type, ','.join(types))) + return globals()[chart_type + 'Chart'](w, h, auto_scale=auto_scale, + x_range=x_range, y_range=y_range) + + def download(self): + pass + diff --git a/static/cache/07968d7c-1a57-11e0-b3ab-001ec9ff1126.png b/static/cache/07968d7c-1a57-11e0-b3ab-001ec9ff1126.png new file mode 100644 index 0000000000000000000000000000000000000000..96c7ed9048229871bd64f43e24cd317c92ab41e4 GIT binary patch literal 2318 zcmb`Ji$Bx*AIF_jZYfU6spHNW&LKhadwhE^RxQ zt#z=P#!*JaPcE@otRW*Ll;yH5yR_eTe&;{<{T|=P_xpK#AK&li{dvDWpXdAac;}xC z^x3gZf18Sm$_`(MR|qgZQr;Th0#63L=qxa(#r@*rrJ_(?f3m2>Dk>VCzFx;prQiKT z=r3G4{GIB7V_y|_th7?MuDcZ^u1uTWi~K>CN8Y}A&x9dclS-v`dPrZSxa9{yCfyBIvVfH8mwK90ORjU^CtQf4^|d7WcPx`v>}%a zIuM_Yx-+vvxandrPxb(r0u8g?7j+U0VnD%R%Q-C4%8gTQc)ERqiukZ}VyVxycS1RD z_C#`B2VAtG%6H&=Fdew|=A%s=*@CV{70hRs0qbt?{#KFpS%IaltB)co+>^aeVD9uz zt!Pz5C9dfKS>NqTyO3kb_7NVbnl+OwZs)cUC%LG?(m{Mg-NR;^fKYN z=SE^b-gCT$NOS7^k*4KvTluXcYC7n&uwAtmBx=1D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EluyN|>&6ErcTJ;pcVmB;u>9Y5`j zvyCVpJ(AwQ6cNzBpHCSF&}Vo=n&DW({Cr<;r-IUb{)d(PQ?(>dsxm{`i;E-f>j>O1BIejS@dIiuH@XmjzE z@~l%7{JvdhVn7c6UjLGdoK#^?T57>Ag_JUz&H2++eJeLSmOjf|8|E5e`b1l5XaoW@ zP&^;h@>d=J8MM!#AYk&?6~&W3AgKq2!i&tQ6YitR6;vuxC4O%(`)0Vrx z-+7XO39uysS@9I0a#<=+1OJb{;h)Asrd3_DbH~G%Qca-2QStQ-^lCi*YxaKtjcm9+ literal 0 HcmV?d00001 diff --git a/static/cache/0891e970-19cf-11e0-a16e-001ec9ff1126.png b/static/cache/0891e970-19cf-11e0-a16e-001ec9ff1126.png new file mode 100644 index 0000000000000000000000000000000000000000..2dc5a68a4da2d189c48d3374a3ffc9506f9a8cfe GIT binary patch literal 1381 zcmYLJeN>WH9A+JB*0Hwfw$jKm%jiVehtB+%A1!r27WhG)Q*5pLBEyd+kpX_}c$|$w zS9xeD9~Nq+_R`4&js$tOm`bIuiGd;Lsis7Uw2_d!l2hViu6QGJYsHPTvIgHAP~#_aPi*~&+^QM zKl1gvyb_+^FU`%3tI{rf|Fg$T=FX|Zl8|<8RB!9{Ge+VY|_N&$9>FtfZb6LSA@w zf+VJFG|q11eNYTjJ$=^%JP08AQF&;v_2J!Jcd9dkzcls#-q^F-&{+eFJyHo4iukU% zZo8V1I8G;kSjPSQ=w?$Xii+ldgo!Bc$p|+fM(*REbdIvJtm1(UJqPZOY)Dj8MK2;X z@5VUzy*cfB%5}I~YQ1bu1=T4nf5Ev2uWq`trlSye7=8_^&i>a((wZf4gI#Nx3*a)t zD`E<`#`;^vaK&-(b*jBeGdSE^NkYB+K4Jq|E^IZR6@ z+StU=--sg8%#K<;xk%6r-$>ao7&f$`iEQqxI~GPce_C69K$HkS$?vJh2*a`~r!1Wk zYt~$yY*B>VCna-T8lQ z)y)&xcoQv%^zswg$Hs`S(_I`eqcK^A7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1Q|L4J-&=)0n;Dgbr&R9W4<&12(p5Ui%grnhhM0lDXtP zKovCU-p?bC+mGn$$8|YpSe1?6L0)?#ZO?QI?m9)~Tg#ur{~Bt`mvm0}fOQG?- zKON@dD>wtY!x{t0(1F+%z-0L$3O43%3qO^bgjmUzW1dFyjxuILL>E*K;jCI6vSZLn zY`WC>-#GB=Jxvyw|$3&2Y57C5lm0)Fxs2kTdR z9y?ZWU@RD?wZK9&%yUzz^HQ~XYqo<^E|}Y!F(x`ez_mzVA{sC3M^Zw};*k?kuYR2I z60i#7J^Rk;%B*`Ft$1JPQ?jL?7spMVG!~kEMs83s3u!PB;%W`8F^V)~p+n4=y(9J*#VSA4_(1quGbr46HESRNGGxWLIw& Jfzz2w{{sMlvoHVv literal 0 HcmV?d00001 diff --git a/static/cache/3526ee82-19ce-11e0-ab4b-001ec9ff1126.png b/static/cache/3526ee82-19ce-11e0-ab4b-001ec9ff1126.png new file mode 100644 index 0000000000000000000000000000000000000000..2dc5a68a4da2d189c48d3374a3ffc9506f9a8cfe GIT binary patch literal 1381 zcmYLJeN>WH9A+JB*0Hwfw$jKm%jiVehtB+%A1!r27WhG)Q*5pLBEyd+kpX_}c$|$w zS9xeD9~Nq+_R`4&js$tOm`bIuiGd;Lsis7Uw2_d!l2hViu6QGJYsHPTvIgHAP~#_aPi*~&+^QM zKl1gvyb_+^FU`%3tI{rf|Fg$T=FX|Zl8|<8RB!9{Ge+VY|_N&$9>FtfZb6LSA@w zf+VJFG|q11eNYTjJ$=^%JP08AQF&;v_2J!Jcd9dkzcls#-q^F-&{+eFJyHo4iukU% zZo8V1I8G;kSjPSQ=w?$Xii+ldgo!Bc$p|+fM(*REbdIvJtm1(UJqPZOY)Dj8MK2;X z@5VUzy*cfB%5}I~YQ1bu1=T4nf5Ev2uWq`trlSye7=8_^&i>a((wZf4gI#Nx3*a)t zD`E<`#`;^vaK&-(b*jBeGdSE^NkYB+K4Jq|E^IZR6@ z+StU=--sg8%#K<;xk%6r-$>ao7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D>S4qG%BE{cn)%m$iq)6%J8-1DEd?Xh#~ za7*{UY*W&|!_+acm?BoGYN>31?!y2*WKl{|2v9BaG6~Bc1z679dT0OCulpS8b9_NW z((o(hbUXRV3z|^g@NlSpp(v*4u)-zO>XxN;sqJacs(1Z%S(AlBYMW!!_6#Feu*}!m zqgKzjwefVOiXuGi zJtys?1^NQ}Lb_gOU`xWSh_CYI*%&cIWzUR}TCcuvO1?dLcnT)73N8@1+!MTCUl;jX z!Y!Se-SbWEAi)7fA0}mKK9z}xU_)1ufn|(U^w;p-rNi)ObBjwW#YPcGrP7I#8!!P2So5wUla8u; z6Qz4c>k9qo`W_}MlPsQhP|A}))t4mD<^Vk@TEIzcLLWN2UWWc3p&5n9m1%nBAWJHp zOqe<)M(gqL-LGbG_ueSIg|c(^`|yL8kZK1OhRcMXt)@qMV}ZxVh3LbqU{&~o;2h%6 z2J|>=1kuie?k5zr7)eNBkurV9t3z-(6bh(?veIno_0ImFLMlG{^KkA~wen>wPFngqR{LY;X5;H&tnJ4K<>n&Dr0gif$k%98@OT>&Md!~!FLAq znIukJykVvaO7N=fH3hVEtxlK9k12YjP&#f)-dy9M1uGdiF8USY1Mnjm@?T%9c5U$+|vJmb8~E&P0%MHlFUjKwn> mx=`vT`i*dJSO?phyv6E9+SAxV?SGa5iiiq}#W#fhaOr=;j<8_> literal 0 HcmV?d00001 diff --git a/static/cache/a69fb7ae-1a52-11e0-8a59-001ec9ff1126.png b/static/cache/a69fb7ae-1a52-11e0-8a59-001ec9ff1126.png new file mode 100644 index 0000000000000000000000000000000000000000..84ec1e868eddba1d286acd54af3228b607a1a6ab GIT binary patch literal 1405 zcmYjRX;4#F7>%|fIt_Iujv{92z$8Ufupj}Wl9V;1Y-+I)!eS+14~Rh)fzT0^q7spS z7*;JH1+uUPK_C@v=tFi56e2vU45@{PLh>*`pdsct&YgSjk9+U;oqNvtzO3WkB;;0; ztq24HNp^QRsok5_r{PBJ+913|*KP)9JxDHywe@kgql$w-Y_cJ{IQk|PD<(YHuidwO zIaKWkuJuT%R+3)~lMYvIn6;Gp=GG)&P-=}@qtTF-4z975HYhv3%FOv^n+@9Os`Fpx z40jpbBPzcp5{YvAB4zclIge4FQbvjpNaTnC5ix7kD0WqRnyI~J`q=a`gIz^iq0h71 zBf~sGjheBZfbpPKs1oW9FuTMDtOO+wQ#?e1m}aSQa<$I(-{#Q%v{U6kr6PFc(e*dN;|AgJUE6ProFgVA7htnaK8EK6@kwZ z#Uz~>wN8ch!nx?m4v^kpFjbRYS-+W*68(Gqj#0bJ5gp<#7Tdmi(|AgX`M|r-qS=}~ zbgI!Oj?yN77%up37b#rH@a*B{aofdW^@_<^ecI!6pE_EH)t@4|(BaYof9|pwWD$@E78e|`0M+Pg#_ObP=jWG%7Y8<^l|tz2wW>c*vJ@;V;Wfy# zW9hAQEL3sm%$uNijkGmRp{{!ZE77RIi{@TVIV^>WyQVsUM484-kbmlm&ZjdhHq`FA zFB3EOoQy|NG*}8VKs4|@9NC1Q|L4J-&=)0n;Dgbr&R9W4<&12(p5Ui%grnhhM0lDXtP zKovCU-p?bC+mGn$$8|YpSe1?6L0)?#ZO?QI?m9)~Tg#ur{~Bt`mvm0}fOQG?- zKON@dD>wtY!x{t0(1F+%z-0L$3O43%3qO^bgjmUzW1dFyjxuILL>E*K;jCI6vSZLn zY`WC>-#GB=Jxvyw|$3&2Y57C5lm0)Fxs2kTdR z9y?ZWU@RD?wZK9&%yUzz^HQ~XYqo<^E|}Y!F(x`ez_mzVA{sC3M^Zw};*k?kuYR2I z60i#7J^Rk;%B*`Ft$1JPQ?jL?7spMVG!~kEMs83s3u!PB;%W`8F^V)~p+n4=y(9J*#VSA4_(1quGbr46HESRNGGxWLIw& Jfzz2w{{sMlvoHVv literal 0 HcmV?d00001 diff --git a/static/cache/ca163ebc-19ce-11e0-a16e-001ec9ff1126.png b/static/cache/ca163ebc-19ce-11e0-a16e-001ec9ff1126.png new file mode 100644 index 0000000000000000000000000000000000000000..2dc5a68a4da2d189c48d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mV?d00001 diff --git a/static/images/permalinked/0891e970-19cf-11e0-a16e-001ec9ff1126.png b/static/images/permalinked/0891e970-19cf-11e0-a16e-001ec9ff1126.png new file mode 100644 index 0000000000000000000000000000000000000000..2dc5a68a4da2d189c48d3374a3ffc9506f9a8cfe GIT binary patch literal 1381 zcmYLJeN>WH9A+JB*0Hwfw$jKm%jiVehtB+%A1!r27WhG)Q*5pLBEyd+kpX_}c$|$w zS9xeD9~Nq+_R`4&js$tOm`bIuiGd;Lsis7Uw2_d!l2hViu6QGJYsHPTvIgHAP~#_aPi*~&+^QM zKl1gvyb_+^FU`%3tI{rf|Fg$T=FX|Zl8|<8RB!9{Ge+VY|_N&$9>FtfZb6LSA@w zf+VJFG|q11eNYTjJ$=^%JP08AQF&;v_2J!Jcd9dkzcls#-q^F-&{+eFJyHo4iukU% zZo8V1I8G;kSjPSQ=w?$Xii+ldgo!Bc$p|+fM(*REbdIvJtm1(UJqPZOY)Dj8MK2;X z@5VUzy*cfB%5}I~YQ1bu1=T4nf5Ev2uWq`trlSye7=8_^&i>a((wZf4gI#Nx3*a)t zD`E<`#`;^vaK&-(b*jBeGdSE^NkYB+K4Jq|E^IZR6@ z+StU=--sg8%#K<;xk%6r-$>ao7&f$`iEQqxI~GPce_C69K$HkS$?vJh2*a`~r!1Wk zYt~$yY*B>VCna-T8lQ z)y)&xcoQv%^zswg$Hs`S(_I`eqcK^A7k&26Stat!LO{u^2cox6!R$8CtCfe*gsPS3 zv4h%J1-cz3R=uVM3f|P%d}y&!8~=v(C{JSR zg#FQR=1NIXG=_n^c+(l$DSanTcwvPD#dctTjAuEwlBnxQlvHnOplN3Pe8nm^KW`!= zww^Q*R7tj`S}3SkvN58=O{v&{Wa-wCn1{F7aVX19Y`O((EHOq5WxME^WrxY%rmSWG z(OtseH}*5^V<+HaNX`){hc_pWmFsGYi`vq1 z?4vS>Q7jeiaVsRFI#ni^XhboZ_$mi$it!Y1wwWSxm9QfgjGjJud3ck0TH<#@AQgJL z;{4Z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Eju>v$U|gGCPj17+gTT(bT-oT zLVjT!j}I*R>vIRTt7ko&etmv;j(MhrY5YN}j84N@(imu%sMH=!*3O|gc@5bZaHCA! zo}X&&Bvkph;2%V%1a}KCCjF~7I-CXg(3k?L6Wi53;nz%hYJ}RQf_f)1Bimb@Wrewk zUA#t}zGRcrpF1#>m^sL`*Ek}g z1fwU&0&NL3n@|OO=IM!{36xw`5o?cRE+l770(v*NTmw55Rv2p+Cov&(7vIRi{&c`F z*u1lI`aO36Y!14LJ#b|xbUd#;l=rv^OjN>@ilu-Nr-P; z?X-_|elID&-^y9*(iAZcE-oWQ(mW~$^%0=eb;t+CJJV)I(ahYZ9hFCgfxRa8^hCtR LBokY=>^}Y 0) && (field.val().length < min_length)) { + return i18n('minlength', caption, min_length); + } else { + return true; + } + }, + + /** + * Validate is if value is lesser than min + * + * @param jQuery field + * @param sting caption + */ + validateMin : function(field, caption) { + var min_val = this.get_val('validateMin', field.attr('class'), 0); + + if((parseInt(field.val(),10) < min_val)) { + return i18n('min', caption, min_val); + } else { + return true; + } + }, + + /** + * Validate if field value is longer than allowed + * + * @param jQuery field + * @param string caption + */ + validateMaxLength : function(field, caption) { + var max_length = this.get_val('validateMaxLength', field.attr('class'), 0); + + if((max_length > 0) && (field.val().length > max_length)) { + return i18n('maxlength', caption, max_length); + } else { + return true; + } + }, + + /** + * Validate is if value is lesser than min + * + * @param jQuery field + * @param sting caption + */ + validateMax : function(field, caption) { + var max_val = this.get_val('validateMax', field.attr('class'), 0); + + if((parseInt(field.val(),10) > max_val)) { + return i18n('max', caption, max_val); + } else { + return true; + } + }, + + + /** + * Make sure that field has same value as the value of target field + * + * @param jQuery field + * @param string caption + */ + validateSameAs : function(field, caption) { + var classes = field.attr('class').split(' '); + var target_field_name = ''; + + for(var i = 0; i < classes.length; i++) { + if(classes[i] == 'validateSameAs') { + if(classes[i + 1] != 'undefined') { + target_field_name = classes[i + 1]; + break; + } + } + } + + if(target_field_name) { + var target_field = jQuery('#' + target_field_name); + if(target_field.length > 0) { + //var target_field_caption = field_caption(field); + var target_field_caption = field_caption(target_field); + + if(target_field.val() != field.val()) { + return i18n('same_as', caption, target_field_caption); + } + } + } + + return true; + }, + + /** + * Validate if provided value is valid email address + * + * @param jQuery field + * @param string caption + */ + validateEmail : function(field, caption) { + if(field.val().match(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/)) { + return true; + } else { + return i18n('email', caption) + } + }, + + /** + * Validate if provided value is valid URL + * + * @param jQuery field + * @param string caption + */ + validateUrl : function(field, caption) { + if(field.val().match(/^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i)) { + return true; + } else { + return i18n('url', caption); + } + }, + + /** + * Number is only valid value (integers and floats) + * + * @param jQuery field + * @param string caption + */ + validateNumber : function(field, caption) { + if(field.val().match(/(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/) || field.val() == '') { + return true; + } else { + return i18n('number', caption); + } + }, + + /** + * Whole numbers are allowed + * + * @param jQuery field + * @param string caption + */ + validateInteger : function(field, caption) { + if(field.val().match(/(^-?\d\d*$)/) || field.val() == '') { + return true; + } else { + return i18n('integer', caption); + } + }, + + /** + * Letters only + * + * @param jQuery field + * @param string caption + */ + validateAlpha : function(field, caption) { + if(field.val().match(/^[a-zA-Z]+$/)) { + return true; + } else { + return i18n('alpha', caption); + } + }, + + /** + * Letters and numbers + * + * @param jQuery field + * @param string caption + */ + validateAlphaNum : function(field, caption) { + if(field.val().match(/\W/)) { + return i18n('alphanum', caption); + } else { + return true; + } + }, + + /** + * Simple phrases + * + * @param jQuery field + * @param string caption + */ + validatePhrase : function(field, caption) { + if((field.val() == '') || field.val().match(/^[\w\d\.\-_\(\)\*'# :,]+$/i)) { + return true; + } else { + return i18n('phrase', caption); + } + }, + + /** + * Phone number + * + * @param jQuery field + * @param string caption + */ + validatePhone : function(field, caption) { + if(field.val().match('/^1?-?(\d{3})?-?(\d{2})?\d-?(\d{4})$/')) { + return true; + } else { + return i18n('phone', caption); + } + }, + + /** + * Phone number + * + * @param jQuery field + * @param string caption + */ + validateDate : function(field, caption) { + if(field.val().match('(1[0-9]|[1-9])/([1-3][0-9]|[1-9])/((19|20)[0-9][0-9]|[0-9][0-9])')) { + return true; + } else { + return i18n('date', caption); + } + }, + + /** + * Callback validator + * + * Lets you define your own validators. Usage: + * + * + * + * This will result in UniForm searching for window.my_callback funciton and + * executing it with field and caption arguments. Sample implementation: + * + * window.my_callback = function(field, caption) { + * if(field.val() == '34') { + * return true; + * } else { + * return caption + ' value should be "34"'; + * } + * } + * + * @param jQuery field + * @param caption + */ + validateCallback : function(field, caption) { + var classes = field.attr('class').split(' '); + var callback_function = ''; + + for(var i = 0; i < classes.length; i++) { + if(classes[i] == 'validateCallback') { + if(classes[i + 1] != 'undefined') { + callback_function = classes[i + 1]; + break; + } + } + } + + if(window[callback_function] != 'undefined' && (typeof window[callback_function] == 'function')) { + return window[callback_function](field, caption); + } + + return i18n('callback', caption, callback_function); + } + + }; + + /** + * Simple replacement for i18n + sprintf + * + * @param string language for for the local i18n object + * @param mixed substitution vars + * + * @return internationalized string + */ + var i18n = function(lang_key) { + var lang_string = i18n_en[lang_key]; + var bits = lang_string.split('%'); + var out = bits[0]; + var re = /^([ds])(.*)$/; + for (var i=1; i + + + + + + QR vCard Generator + + + + + + + + + + + + + + + +
+

QR Code vCard Generator

+

Author: Fergal Moran Blog article

+
+ +
+

+ Here is your qrcode vCard. Right click the image below and select "Save as" to download it.
+ Alternatively, you may click "Permalink" below to generate a permanent URL for this image (please note, this requires signing in and may not always be available). +

+ + QRCode should be here + + + +
+ + diff --git a/views/qrform.tpl b/views/qrform.tpl new file mode 100644 index 0000000..a03e066 --- /dev/null +++ b/views/qrform.tpl @@ -0,0 +1,167 @@ + + + + + + + QR vCard Generator + + + + + + + + + + + + + + +
+

QR Code vCard Generator

+

Author: Fergal Moran Blog article

+
+ +
+
+ +
+
+ +
+
+

vCard Details

+
+ + +
+
+ + +
+
+ + +
+ +
+ + +
+
+ + +
+
+ + +
+
+ + +

Please seperate lines with a comma

+
+
+
+
+ +