# -*- coding: utf-8 -*- import os import json import clastic from clastic import Application from clastic.render import JSONRender from clastic.middleware import GetParamMiddleware from clastic import Response from clastic.sinter import getargspec from boltons.tableutils import Table _DATA = json.load(open('meta_stats.json')) _CUR_PATH = os.path.dirname(os.path.abspath(clastic.__file__)) _CA_PATH = _CUR_PATH + '/_clastic_assets' _CSS_PATH = _CA_PATH + '/common.css' _STYLE = open(_CSS_PATH).read() try: basestring # Python 2 unicode except NameError: # Python 3 basestring = (str, ) unicode = str def fetch_json(url): import urllib2 response = urllib2.urlopen(url) content = response.read() data = json.loads(content) return data class AutoTableRenderer(object): _html_doctype = '' _html_wrapper, _html_wrapper_close = '', '' _html_table_tag = '' _html_style_content = _STYLE def __init__(self, max_depth=4, orientation='auto'): self.max_depth = max_depth self.orientation = orientation def _html_format_ep(self, route): # TODO: callable object endpoints? module_name = route.endpoint.__module__ try: func_name = route.endpoint.func_name except: func_name = repr(route.endpoint) args, _, _, _ = getargspec(route.endpoint) argstr = ', '.join(args) title = ('

%s
%s(%s)

' % (module_name, func_name, argstr)) return title def __call__(self, context, _route): content_parts = [self._html_wrapper] if self._html_style_content: content_parts.extend(['']) content_parts.append('') title = self._html_format_ep(_route) content_parts.append(title) table = Table.from_data(context, max_depth=self.max_depth) table._html_table_tag = self._html_table_tag content = table.to_html(max_depth=self.max_depth, orientation=self.orientation) content_parts.append(content) content_parts.append('') content_parts.append(self._html_wrapper_close) return Response('\n'.join(content_parts), mimetype='text/html') class BasicRender(object): _default_mime = 'application/json' _format_mime_map = {'html': 'text/html', 'json': 'application/json'} def __init__(self, dev_mode=True, qp_name='format'): self.qp_name = qp_name self.json_render = JSONRender(dev_mode=dev_mode) self.autotable_render = AutoTableRenderer() def render_response(self, request, context, _route): from collections import Sized if isinstance(context, basestring): # already serialized if self._guess_json(context): return Response(context, mimetype="application/json") elif '