Skip to content

Commit

Permalink
Row values endpoint using libmagic
Browse files Browse the repository at this point in the history
Not yet complete. Refs #3
  • Loading branch information
Simon Willison committed Oct 25, 2017
1 parent f1b0521 commit 97bcd41
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
5 changes: 5 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
FROM python:3

RUN apt-get update && apt-get install -y --no-install-recommends \
libmagic-dev \
&& rm -rf /var/lib/apt/lists/*

COPY . /app
WORKDIR /app
RUN pip install -r requirements.txt
Expand Down
31 changes: 31 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import hashlib
import sys
import time
import magic

app_root = Path(__file__).parent

Expand Down Expand Up @@ -249,9 +250,37 @@ def data(self, request, name, hash, table, pk_path):
}


class CellView(BaseView):
async def get(self, request, db_name, table, pk_path, column, as_json=False):
name, hash, should_redirect = resolve_db_name(db_name, **{
'table': table,
'pk_path': pk_path,
'column': column,
'as_json': as_json,
})
if should_redirect:
return self.redirect(request, should_redirect)
conn = get_conn(name)
pk_values = compound_pks_from_path(pk_path)
pks = pks_for_table(conn, table)
wheres = [
'"{}"=?'.format(pk)
for pk in pks
]
sql = 'select "{}" from "{}" where {}'.format(
column, table, ' AND '.join(wheres)
)
row = conn.execute(sql, pk_values).fetchone()
content = row[0].decode('latin1')
# Sniff content type
content_type = magic.from_buffer(content[:1024], mime=True)
return response.text(content, content_type=content_type)


app.add_route(DatabaseView.as_view(), '/<db_name:[^/]+?><as_json:(.jsono?)?$>')
app.add_route(TableView.as_view(), '/<db_name:[^/]+>/<table:[^/]+?><as_json:(.jsono?)?$>')
app.add_route(RowView.as_view(), '/<db_name:[^/]+>/<table:[^/]+?>/<pk_path:[^/]+?><as_json:(.jsono?)?$>')
app.add_route(CellView.as_view(), '/<db_name:[^/]+>/<table:[^/]+?>/<pk_path:[^/]+?>/<column:[^/]+?><as_json:(.jsono?)?$>')


def resolve_db_name(db_name, **kwargs):
Expand Down Expand Up @@ -280,6 +309,8 @@ def resolve_db_name(db_name, **kwargs):
)
if 'table' in kwargs:
should_redirect += '/' + kwargs['table']
if 'column' in kwargs:
should_redirect += '/' + kwargs['column']
if 'as_json' in kwargs:
should_redirect += kwargs['as_json']
return name, expected, should_redirect
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
sanic==0.6.0
sanic-jinja2==0.5.5
python-magic==0.4.13

0 comments on commit 97bcd41

Please sign in to comment.