How to use the datasette.utils.path_from_row_pks function in datasette

To help you get started, we’ve selected a few datasette examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github simonw / datasette / tests / test_utils.py View on Github external
def test_path_from_row_pks(row, pks, expected_path):
    actual_path = utils.path_from_row_pks(row, pks, False)
    assert expected_path == actual_path
github simonw / datasette / datasette / views / table.py View on Github external
{"name": r[0], "sortable": r[0] in sortable_columns} for r in description
        ]
        pks = await db.primary_keys(table)
        column_to_foreign_key_table = {
            fk["column"]: fk["other_table"]
            for fk in await db.foreign_keys_for_table(table)
        }

        cell_rows = []
        for row in rows:
            cells = []
            # Unless we are a view, the first column is a link - either to the rowid
            # or to the simple or compound primary key
            if link_column:
                is_special_link_column = len(pks) != 1
                pk_path = path_from_row_pks(row, pks, not pks, False)
                cells.append(
                    {
                        "column": pks[0] if len(pks) == 1 else "Link",
                        "is_special_link_column": is_special_link_column,
                        "raw": pk_path,
                        "value": jinja2.Markup(
                            '<a href="/{database}/{table}/{flat_pks_quoted}">{flat_pks}</a>'.format(
                                database=database,
                                table=urllib.parse.quote_plus(table),
                                flat_pks=str(jinja2.escape(pk_path)),
                                flat_pks_quoted=path_from_row_pks(row, pks, not pks),
                            )
                        ),
                    }
                )
github simonw / datasette / datasette / renderer.py View on Github external
if rows and columns:
            data["rows"] = [dict(zip(columns, row)) for row in rows]
        if shape == "object":
            error = None
            if "primary_keys" not in data:
                error = "_shape=object is only available on tables"
            else:
                pks = data["primary_keys"]
                if not pks:
                    error = (
                        "_shape=object not available for tables with no primary keys"
                    )
                else:
                    object_rows = {}
                    for row in data["rows"]:
                        pk_string = path_from_row_pks(row, pks, not pks)
                        object_rows[pk_string] = row
                    data = object_rows
            if error:
                data = {"ok": False, "error": error}
        elif shape == "array":
            data = data["rows"]
    elif shape == "arrays":
        pass
    else:
        status_code = 400
        data = {
            "ok": False,
            "error": "Invalid _shape: {}".format(shape),
            "status": 400,
            "title": None,
        }
github simonw / datasette / datasette / app.py View on Github external
columns = [r[0] for r in description]
        rows = list(rows)

        filter_columns = columns[:]
        if use_rowid and filter_columns[0] == 'rowid':
            filter_columns = filter_columns[1:]

        # Pagination next link
        next_value = None
        next_url = None
        if len(rows) > self.page_size:
            if is_view:
                next_value = int(_next or 0) + self.page_size
            else:
                next_value = path_from_row_pks(rows[-2], pks, use_rowid)
            # If there's a sort or sort_desc, add that value as a prefix
            if (sort or sort_desc) and not is_view:
                prefix = str(rows[-2][sort or sort_desc])
                next_value = '{},{}'.format(
                    urllib.parse.quote_plus(prefix), next_value
                )
                added_args = {
                    '_next': next_value,
                }
                if sort:
                    added_args['_sort'] = sort
                else:
                    added_args['_sort_desc'] = sort_desc
            else:
                added_args = {
                    '_next': next_value,
github simonw / datasette / datasette / views / table.py View on Github external
"value": value,
                                "label": expanded_labels[(column, value)],
                            }
                        else:
                            new_row[column] = value
                    new_rows.append(new_row)
                rows = new_rows

        # Pagination next link
        next_value = None
        next_url = None
        if len(rows) > page_size and page_size > 0:
            if is_view:
                next_value = int(_next or 0) + page_size
            else:
                next_value = path_from_row_pks(rows[-2], pks, use_rowid)
            # If there's a sort or sort_desc, add that value as a prefix
            if (sort or sort_desc) and not is_view:
                prefix = rows[-2][sort or sort_desc]
                if isinstance(prefix, dict) and "value" in prefix:
                    prefix = prefix["value"]
                if prefix is None:
                    prefix = "$null"
                else:
                    prefix = urllib.parse.quote_plus(str(prefix))
                next_value = "{},{}".format(prefix, next_value)
                added_args = {"_next": next_value}
                if sort:
                    added_args["_sort"] = sort
                else:
                    added_args["_sort_desc"] = sort_desc
            else:
github simonw / datasette / datasette / app.py View on Github external
labeled_fks[(fk['column'], id)] = (fk['other_table'], value)

        cell_rows = []
        for row in rows:
            cells = []
            # Unless we are a view, the first column is a link - either to the rowid
            # or to the simple or compound primary key
            if link_column:
                cells.append({
                    'column': 'Link',
                    'value': jinja2.Markup(
                        '<a href="/{database}/{table}/{flat_pks_quoted}">{flat_pks}</a>'.format(
                            database=database,
                            table=urllib.parse.quote_plus(table),
                            flat_pks=str(jinja2.escape(path_from_row_pks(row, pks, not pks, False))),
                            flat_pks_quoted=path_from_row_pks(row, pks, not pks)
                        )
                    ),
                })

            for value, column_dict in zip(row, columns):
                column = column_dict['name']
                if link_column and len(pks) == 1 and column == pks[0]:
                    # If there's a simple primary key, don't repeat the value as it's
                    # already shown in the link column.
                    continue
                if (column, value) in labeled_fks:
                    other_table, label = labeled_fks[(column, value)]
                    display_value = jinja2.Markup(
                        '<a href="/{database}/{table}/{link_id}">{label}</a>&nbsp;<em>{id}</em>'.format(
                            database=database,
                            table=urllib.parse.quote_plus(other_table),
github simonw / datasette / datasette / app.py View on Github external
for id, value in results:
                        labeled_fks[(fk['column'], id)] = (fk['other_table'], value)

        cell_rows = []
        for row in rows:
            cells = []
            # Unless we are a view, the first column is a link - either to the rowid
            # or to the simple or compound primary key
            if link_column:
                cells.append({
                    'column': 'Link',
                    'value': jinja2.Markup(
                        '<a href="/{database}/{table}/{flat_pks_quoted}">{flat_pks}</a>'.format(
                            database=database,
                            table=urllib.parse.quote_plus(table),
                            flat_pks=str(jinja2.escape(path_from_row_pks(row, pks, not pks, False))),
                            flat_pks_quoted=path_from_row_pks(row, pks, not pks)
                        )
                    ),
                })

            for value, column_dict in zip(row, columns):
                column = column_dict['name']
                if link_column and len(pks) == 1 and column == pks[0]:
                    # If there's a simple primary key, don't repeat the value as it's
                    # already shown in the link column.
                    continue
                if (column, value) in labeled_fks:
                    other_table, label = labeled_fks[(column, value)]
                    display_value = jinja2.Markup(
                        '<a href="/{database}/{table}/{link_id}">{label}</a>&nbsp;<em>{id}</em>'.format(
                            database=database,
github simonw / datasette / datasette / views / table.py View on Github external
# Unless we are a view, the first column is a link - either to the rowid
            # or to the simple or compound primary key
            if link_column:
                is_special_link_column = len(pks) != 1
                pk_path = path_from_row_pks(row, pks, not pks, False)
                cells.append(
                    {
                        "column": pks[0] if len(pks) == 1 else "Link",
                        "is_special_link_column": is_special_link_column,
                        "raw": pk_path,
                        "value": jinja2.Markup(
                            '<a href="/{database}/{table}/{flat_pks_quoted}">{flat_pks}</a>'.format(
                                database=database,
                                table=urllib.parse.quote_plus(table),
                                flat_pks=str(jinja2.escape(pk_path)),
                                flat_pks_quoted=path_from_row_pks(row, pks, not pks),
                            )
                        ),
                    }
                )

            for value, column_dict in zip(row, columns):
                column = column_dict["name"]
                if link_column and len(pks) == 1 and column == pks[0]:
                    # If there's a simple primary key, don't repeat the value as it's
                    # already shown in the link column.
                    continue

                # First let the plugins have a go
                # pylint: disable=no-member
                plugin_display_value = pm.hook.render_cell(
                    value=value,
github simonw / datasette / datasette / app.py View on Github external
data['rows'] = [
                        dict(zip(columns, row))
                        for row in rows
                    ]
                if shape == 'object':
                    error = None
                    if 'primary_keys' not in data:
                        error = '_shape=object is only available on tables'
                    else:
                        pks = data['primary_keys']
                        if not pks:
                            error = '_shape=object not available for tables with no primary keys'
                        else:
                            object_rows = {}
                            for row in data['rows']:
                                pk_string = path_from_row_pks(row, pks, not pks)
                                object_rows[pk_string] = row
                            data['rows'] = object_rows
                    if error:
                        data = {
                            'ok': False,
                            'error': error,
                            'database': name,
                            'database_hash': hash,
                        }

            headers = {}
            if self.ds.cors:
                headers['Access-Control-Allow-Origin'] = '*'
            r = response.HTTPResponse(
                json.dumps(
                    data, cls=CustomJSONEncoder