Skip to content

Instantly share code, notes, and snippets.

@simonw
Created August 8, 2024 14:56
Show Gist options
  • Save simonw/b2cfff8281d5681c30e54083a9882141 to your computer and use it in GitHub Desktop.
Save simonw/b2cfff8281d5681c30e54083a9882141 to your computer and use it in GitHub Desktop.
import re
import filetype
from datasette import hookimpl
from markupsafe import escape, Markup
sequence_re = re.compile(r"((?:\\x[0-9a-f]{2})+)")
octet_re = re.compile(r"(\\x[0-9a-f]{2})")
@hookimpl(trylast=True)
def render_cell(value):
if not isinstance(value, bytes):
return None
# Attempt to guess filetype
suggestion = None
match = filetype.guess(value[:1000])
if match:
suggestion = "{} ({})".format(match.extension, match.mime)
encoded = repr(value)
# Ditch the b' and trailing '
if encoded.startswith("b'") and encoded.endswith("'"):
encoded = encoded[2:-1]
# Split it into sequences of octets and characters
chunks = sequence_re.split(encoded)
html = []
if suggestion:
html.append(
'<p style="margin-top: 0; font-family: monospace; font-size: 0.8em;">Suggestion: {}</p>'.format(
escape(suggestion)
)
)
for chunk in chunks:
if sequence_re.match(chunk):
octets = octet_re.findall(chunk)
octets = [o[2:] for o in octets]
html.append(
'<code style="color: #999; font-family: monospace">{}</code>'.format(
" ".join(octets).upper()
)
)
else:
html.append(escape(chunk.replace("\\\\", "\\")))
return Markup(" ".join(html).strip())
With that code as inspiration, modify the following Django Admin code to use that to display decoded base64 data:
@admin.register(RequestLog)
class RequestLogAdmin(admin.ModelAdmin):
list_display = ("endpoint", "method", "timestamp", "body_preview", "is_base64")
list_filter = ("endpoint", "method", "is_base64")
readonly_fields = (
"endpoint",
"method",
"headers",
"body_display",
"is_base64",
"timestamp",
)
search_fields = ("endpoint__path",)
def has_add_permission(self, request):
return False
def has_change_permission(self, request, obj=None):
return False
def body_preview(self, obj):
body = obj.get_body()
if isinstance(body, bytes):
return f"Binary data ({len(body)} bytes)"
return body[:50] + ("..." if len(body) > 50 else "")
def body_display(self, obj):
body = obj.get_body()
if isinstance(body, bytes):
return format_html("<pre>Binary data ({} bytes)</pre>", len(body))
return format_html("<pre>{}</pre>", body)
body_display.short_description = "Body"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment