Skip to content

Commit

Permalink
Auto-link column values that look like URLs
Browse files Browse the repository at this point in the history
Refs #153
  • Loading branch information
simonw committed Nov 29, 2017
1 parent 0120c24 commit b67890d
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
5 changes: 5 additions & 0 deletions datasette/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
escape_sqlite_table_name,
filters_should_redirect,
get_all_foreign_keys,
is_url,
InvalidSql,
path_from_row_pks,
path_with_added_args,
Expand Down Expand Up @@ -443,6 +444,10 @@ async def make_display_rows(self, database, database_hash, table, rows, display_
)
elif value is None:
display_value = jinja2.Markup(' ')
elif is_url(str(value).strip()):
display_value = jinja2.Markup(
'<a href="{url}">{url}</a>'.format(url=value.strip())
)
else:
display_value = str(value)
cells.append({
Expand Down
15 changes: 15 additions & 0 deletions datasette/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -441,3 +441,18 @@ def filters_should_redirect(special_args):
('_filter_value_{}'.format(number), None),
])
return redirect_params


whitespace_re = re.compile(r'\s')


def is_url(value):
"Must start with http:// or https:// and contain JUST a URL"
if not isinstance(value, str):
return False
if not value.startswith('http://') and not value.startswith('https://'):
return False
# Any whitespace at all is invalid
if whitespace_re.search(value):
return False
return True
10 changes: 10 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,3 +151,13 @@ def test_detect_fts():
assert None is utils.detect_fts(conn, 'Dumb_Table')
assert None is utils.detect_fts(conn, 'Test_View')
assert 'Street_Tree_List_fts' == utils.detect_fts(conn, 'Street_Tree_List')


@pytest.mark.parametrize('url,expected', [
('http://www.google.com/', True),
('https://example.com/', True),
('www.google.com', False),
('http://www.google.com/ is a search engine', False),
])
def test_is_url(url, expected):
assert expected == utils.is_url(url)

1 comment on commit b67890d

@simonw
Copy link
Owner Author

@simonw simonw commented on b67890d Nov 30, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

metobjects__metobjects__457_509_rows

Please sign in to comment.