takahe/activities/views/debug.py

49 lines
1.5 KiB
Python
Raw Normal View History

2022-12-18 10:00:21 -08:00
import pprint
import httpx
from asgiref.sync import async_to_sync
from django import forms
from django.utils.decorators import method_decorator
from django.views.generic import FormView
from core.ld import canonicalise
from users.decorators import admin_required
from users.models import SystemActor
@method_decorator(admin_required, name="dispatch")
class JsonViewer(FormView):
template_name = "activities/debug_json.html"
class form_class(forms.Form):
uri = forms.CharField(
help_text="The URI to fetch and show",
widget=forms.TextInput(attrs={"type": "search", "autofocus": "autofocus"}),
)
def form_valid(self, form):
2022-12-20 00:19:00 -08:00
raw_result = ""
2022-12-20 05:21:36 -08:00
uri = form.cleaned_data["uri"]
if "://" not in uri:
uri = "https://" + uri
2022-12-18 10:00:21 -08:00
try:
response = async_to_sync(SystemActor().signed_request)(
method="get",
2022-12-20 05:21:36 -08:00
uri=uri,
2022-12-18 10:00:21 -08:00
)
except httpx.RequestError:
result = "Request Error"
else:
2022-12-20 00:19:00 -08:00
raw_result = response.text
2022-12-18 10:00:21 -08:00
if response.status_code >= 400:
result = f"Error response: {response.status_code}\n{response.content}"
else:
document = canonicalise(response.json(), include_security=True)
result = pprint.pformat(document)
# Render results
context = self.get_context_data(form=form)
context["result"] = result
2022-12-20 00:19:00 -08:00
context["raw_result"] = raw_result
2022-12-18 10:00:21 -08:00
return self.render_to_response(context)