Example #1
0
def generate_api_test(routes):
    '''generate the html to test the API'''
    wrapper = div(class_='wrapper')
    for method in routes:
        for route in routes[method]:
            name = tubes.underscores_to_camelcase(route.handler.__name__)
            output_id = name + '-output'
            args = []
            start_arg = 1

            if route.accepts == tubes.JSON:
                start_arg = 2

            tbl = table(class_='api-form', id=name)
            output = div(class_='output', id=output_id,
                    onclick="$(this).html('');")
            wrapper.add(div(h2(name), tbl, output, class_='api'))

            for arg in inspect.getargspec(route.handler)[0][start_arg:]:
                argname = name + '-' + arg
                args.append(argname)
                tbl.add(tr(
                    td(arg, class_='left'),
                    td(input(type='text', id=argname, class_='value'),
                        class_='right')))

            if route.has_payload or route.accepts == tubes.JSON:
                tbl.add(tr(
                    td("payload (eval)", class_='left'),
                    td(input(type='text', id=name + '--payload', class_='value'),
                        class_='right')))

            ids = ', '.join("'%s'" % (arg, ) for arg in args)
            tbl.add(tr(td(), td(button('send',
                onclick='sendForm(\'' + name + '\', [' + ids + '], \'' + \
                        output_id + '\')'))))

    return str(wrapper)
Example #2
0
def generate_requests(handler, namespace='requests'):
    '''return javascript code to interact with this handler'''
    def get_rest_call(method, route):
        '''return a string representing a asynchornous REST call'''
        pattern = route.pattern
        if pattern.startswith('^'):
            pattern = pattern[1:]

        if pattern.endswith('?'):
            pattern = pattern[:-1]

        start_arg = 1

        if route.accepts == tubes.JSON:
            start_arg = 2

        parts = re.split('(\(.*?\))', pattern)
        result = ['"']
        args = inspect.getargspec(route.handler)[0][start_arg:]

        for part in parts:
            if part.startswith('('):
                result.append('" + ' + args.pop(0) + ' + "')
            else:
                result.append(part.replace('^', '').replace('$',
                    '').replace('?', ''))

        result.append('"')
        code  = "    var url = %s;\n" % (''.join(result), )
        code += "    $.ajax({'contentType': '%s',\n" % (route.produces, )

        if route.accepts == tubes.JSON:
            code += "        'data': JSON.stringify(data),\n"
        elif route.accepts is not None:
            code += "        'data': data,\n"

        code += "        'dataType': '%s',\n" % \
                (tubes.JQUERY_TYPES.get(route.produces, 'text'),)
        code += "        'error': onError,\n"
        code += "        'success': onSuccess,\n"
        code += "        'type': '%s',\n" % (method, )
        code += "        'url': url});\n"

        return code

    code  = 'var %s = {};\n\n' % (namespace,)
    code += '%s.cb = function(response) {console.log(response);};\n\n' % \
            (namespace, )

    for method, routes in handler.routes.iteritems():
        for route in routes:
            start_arg = 1

            if route.accepts == tubes.JSON:
                start_arg = 2

            args = inspect.getargspec(route.handler)[0][start_arg:]

            if route.has_payload or route.accepts == tubes.JSON:
                args += ['data']

            args += ['onSuccess', 'onError']
            method_name = tubes.underscores_to_camelcase(route.handler.__name__)

            code += '// handle %s on %s\n' % (method, route.pattern)
            code += '%s.%s = function(%s) {\n%s};\n\n' % (namespace,
                    method_name, ', '.join(args), get_rest_call(method, route))

    return code