Exemplo n.º 1
0
def existing_node_input():
    """
    Get an existing node id by name or id.

    Return -1 if invalid
    """
    input_from_user = raw_input("Existing node name or id: ")
    node_id = INVALID_NODE

    if not input_from_user:
        return node_id

    # int or str?
    try:
        parsed_input = int(input_from_user)
    except ValueError:
        parsed_input = input_from_user

    if isinstance(parsed_input, int):
        result = db.execute(text(fetch_query_string('select_node_from_id.sql')),
                node_id=parsed_input).fetchall()
        if result:
            node_id = int(result[0]['node_id'])
    else:
        result = db.execute(text(fetch_query_string('select_node_from_name.sql')),
                node_name=parsed_input).fetchall()
        if result:
            if len(result) == 1:
                print 'Node id: {node_id}\nNode name: {name}'.format(**result[0])
                print '-------------'
                node_id = result[0]['node_id']
            else:
                print 'Multiple nodes found with the name: {0}'.format(parsed_input)
                for item in result:
                    print '{node_id}: {name} = {value}'.format(**item)
                node_selection = raw_input('Enter a node id from this list or enter "?" to render all or "?<node>" for a specific one.')
                if node_selection:
                    node_selection_match = re.match(r"\?(\d)*", node_selection)
                    if node_selection_match:
                        if node_selection_match.groups()[0]:
                            value = render_node(int(node_selection_match.groups()[0]), noderequest={'_no_template':True}, **result[0])
                            print safe_dump(value, default_flow_style=False)
                        else:
                            for item in result:
                                value = render_node(item['node_id'], noderequest={'_no_template':True}, **item)
                                print 'Node id: {0}'.format(item['node_id'])
                                print safe_dump(value, default_flow_style=False)
                                print '---'
                        node_id = node_input()
                    else:
                        try:
                            node_id = int(node_selection)
                        except ValueError:
                            node_id = INVALID_NODE
                            print 'invalid node id: %s' % node

    return node_id
Exemplo n.º 2
0
    def get(self, uri=''):
        "For sql queries that start with 'SELECT ...'"
        (node, rule_kw) = node_from_uri(uri)

        if node == None:
            abort(404)
        rule_kw.update( node )
        values = rule_kw
        xhr_data = request.get_json()
        if xhr_data:
            values.update( xhr_data )
        values.update( request.form.to_dict(flat=True) )
        values.update( request.args.to_dict(flat=True) )
        values.update( request.cookies )
        values['method'] = request.method
        noderequest = values.copy()
        noderequest.pop('node_id')
        noderequest.pop('name')
        noderequest.pop('value')

        #current_app.logger.debug("get kw: %s", values)
        rendered = render_node(node['id'], noderequest=noderequest, **values)
        #current_app.logger.debug("rendered: %s", rendered)
        if rendered:
            if not isinstance(rendered, (str, unicode, int, float)):
                # return a json string
                return encoder.encode(rendered)
            return rendered

        # Nothing to show, so nothing found
        abort(404)
Exemplo n.º 3
0
    def get(self, uri=''):
        "For sql queries that start with 'SELECT ...'"
        (node, rule_kw) = node_from_uri(uri)

        if node == None:
            abort(404)
        rule_kw.update(node)
        values = rule_kw
        xhr_data = request.get_json()
        if xhr_data:
            values.update(xhr_data)
        values.update(request.form.to_dict(flat=True))
        values.update(request.args.to_dict(flat=True))
        values.update(request.cookies)
        values['method'] = request.method
        noderequest = values.copy()
        noderequest.pop('node_id')
        noderequest.pop('name')
        noderequest.pop('value')

        #current_app.logger.debug("get kw: %s", values)
        rendered = render_node(node['id'], noderequest=noderequest, **values)
        current_app.logger.debug("rendered: %s", rendered)
        if rendered:
            if not isinstance(rendered, (str, unicode, int, float)):
                # return a json string
                return encoder.encode(rendered)
            return rendered

        # Nothing to show, so nothing found
        abort(404)
Exemplo n.º 4
0
def render_value_for_node(node_id):
    """
    Wrap render_node for usage in operate scripts.  Returns without template
    rendered.
    """
    value = None
    result = []
    try:
        result = db.execute(text(fetch_query_string('select_node_from_id.sql')), node_id=node_id).fetchall()
    except DatabaseError as err:
        current_app.logger.error("DatabaseError: %s", err)

    if result:
        kw = dict(zip(result[0].keys(), result[0].values()))
        value = render_node(node_id, noderequest={'_no_template':True}, **kw)

    return value
Exemplo n.º 5
0
def route_handler(context, content, pargs, kwargs):
    """
    Route shortcode works a lot like rendering a page based on the url or
    route.  This allows inserting in rendered HTML within another page.

    Activate it with the 'shortcodes' template filter. Within the content use
    the chill route shortcode: "[chill route /path/to/something/]" where the
    '[chill' and ']' are the shortcode starting and ending tags. And 'route' is
    this route handler that takes one argument which is the url.
    """
    (node, rule_kw) = node_from_uri(pargs[0])

    if node == None:
        return "<!-- 404 '{0}' -->".format(pargs[0])

    rule_kw.update( node )
    values = rule_kw
    values.update( request.form.to_dict(flat=True) )
    values.update( request.args.to_dict(flat=True) )
    values['method'] = request.method
    noderequest = values.copy()
    noderequest.pop('node_id')
    noderequest.pop('name')
    noderequest.pop('value')

    rendered = render_node(node['id'], noderequest=noderequest, **values)

    if rendered:
        if not isinstance(rendered, (str, unicode, int, float)):
            # return a json string
            return encoder.encode(rendered)

        return rendered

    # Nothing to show, so nothing found
    return "<!-- 404 '{0}' -->".format(pargs[0])
Exemplo n.º 6
0
def route_handler(context, content, pargs, kwargs):
    """
    Route shortcode works a lot like rendering a page based on the url or
    route.  This allows inserting in rendered HTML within another page.

    Activate it with the 'shortcodes' template filter. Within the content use
    the chill route shortcode: "[chill route /path/to/something/]" where the
    '[chill' and ']' are the shortcode starting and ending tags. And 'route' is
    this route handler that takes one argument which is the url.
    """
    (node, rule_kw) = node_from_uri(pargs[0])

    if node == None:
        return u"<!-- 404 '{0}' -->".format(pargs[0])

    rule_kw.update(node)
    values = rule_kw
    values.update(request.form.to_dict(flat=True))
    values.update(request.args.to_dict(flat=True))
    values['method'] = request.method
    noderequest = values.copy()
    noderequest.pop('node_id')
    noderequest.pop('name')
    noderequest.pop('value')

    rendered = render_node(node['id'], noderequest=noderequest, **values)

    if rendered:
        if not isinstance(rendered, (str, unicode, int, float)):
            # return a json string
            return encoder.encode(rendered)

        return rendered

    # Nothing to show, so nothing found
    return "<!-- 404 '{0}' -->".format(pargs[0])
Exemplo n.º 7
0
def operate_menu():
    "Select between these operations on the database"

    selection = True
    while selection:

        print globals()['operate_menu'].__doc__
        selection = select([
            'chill.database functions',
            'execute sql file',
            'render_node',
            'New collection',
            'Manage collection',
            'Add document for node',
            'help',
            ])
        if selection == 'chill.database functions':
            mode_database_functions()
        elif selection == 'execute sql file':
            print "View the sql file and show a fill in the blanks interface with raw_input"
            sqlfile = choose_query_file()
            if not sqlfile:
                # return to the menu choices if not file picked
                selection = True
            else:
                sql_named_placeholders_re = re.compile(r":(\w+)")
                sql = fetch_query_string(sqlfile)
                placeholders = set(sql_named_placeholders_re.findall(sql))
                print sql
                data = {}
                for placeholder in placeholders:
                    value = raw_input(placeholder + ': ')
                    data[placeholder] = value

                result = []
                try:
                    result = db.execute(text(sql), data)
                except DatabaseError as err:
                    current_app.logger.error("DatabaseError: %s", err)

                if result and result.returns_rows:
                    result = result.fetchall()
                    print result
                    if not result:
                        print 'No results.'
                    else:
                        kw = result[0]

                        if 'node_id' in kw:
                            print 'render node %s' % kw['node_id']
                            value = render_node(kw['node_id'], **kw)
                            print safe_dump(value, default_flow_style=False)
                        else:
                            #print safe_dump(rowify(result, [(x, None) for x in result[0].keys()]), default_flow_style=False)
                            print safe_dump([dict(zip(x.keys(), x.values())) for x in result], default_flow_style=False)

        elif selection == 'render_node':
            print globals()['render_node'].__doc__
            node_id = existing_node_input()

            value = render_value_for_node(node_id)
            print safe_dump(value, default_flow_style=False)

        elif selection == 'New collection':
            mode_new_collection()
        elif selection == 'Manage collection':
            mode_collection()
        elif selection == 'Add document for node':
            folder = current_app.config.get('DOCUMENT_FOLDER')
            if not folder:
                print "No DOCUMENT_FOLDER configured for the application."
            else:
                choices = map(os.path.basename,
                            glob(os.path.join(folder, '*'))
                            )
                choices.sort()
                if len(choices) == 0:
                    print "No files found in DOCUMENT_FOLDER."
                else:
                    filename = select(choices)
                    if filename:
                        defaultname = os.path.splitext(filename)[0]
                        nodename = raw_input("Enter name for node [{0}]: ".format(defaultname)) or defaultname
                        node = insert_node(name=nodename, value=filename)
                        print "Added document '%s' to node '%s' with id: %s" % (filename, nodename, node)
        elif selection == 'help':
            print "------"
            print __doc__
            print "------"
        else:
            print 'Done'