From 97bcd41f3392b8a6c4c5a0eb373c9c2a29e31954 Mon Sep 17 00:00:00 2001 From: Simon Willison Date: Wed, 25 Oct 2017 08:05:17 -0700 Subject: [PATCH] Row values endpoint using libmagic Not yet complete. Refs #3 --- Dockerfile | 5 +++++ app.py | 31 +++++++++++++++++++++++++++++++ requirements.txt | 1 + 3 files changed, 37 insertions(+) diff --git a/Dockerfile b/Dockerfile index fc10c98d..38d7bd5c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -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 diff --git a/app.py b/app.py index 5431dfd5..6a8264e9 100644 --- a/app.py +++ b/app.py @@ -13,6 +13,7 @@ import base64 import hashlib import sys import time +import magic app_root = Path(__file__).parent @@ -249,9 +250,37 @@ class RowView(BaseView): } +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(), '/') app.add_route(TableView.as_view(), '//') app.add_route(RowView.as_view(), '///') +app.add_route(CellView.as_view(), '////') def resolve_db_name(db_name, **kwargs): @@ -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 diff --git a/requirements.txt b/requirements.txt index 26410e3e..1ecfd635 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,3 @@ sanic==0.6.0 sanic-jinja2==0.5.5 +python-magic==0.4.13