Skip to content
This repository was archived by the owner on Jul 15, 2025. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions api_reflector/admin.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,36 @@
"""
Declares the flask-admin instance and sets up the model views.
"""
import json
from json import JSONDecodeError

from flask import redirect, url_for
from flask_admin import Admin, AdminIndexView
from flask_admin.contrib.sqla import ModelView
from flask_admin.menu import MenuLink
from jinja2.runtime import Context
from slugify import slugify
from wtforms import validators

from api_reflector import auth, db, models


def is_valid_json(data: str) -> None:
"""
Validator function for checking whether form field content is a valid JSON.
"""

try:
json.loads(data)
except JSONDecodeError as exc:
raise validators.ValidationError("Response content data must be a valid JSON object or empty.") from exc


form_validators = {
"application/json": is_valid_json,
}


def admin_view(model: db.Model):
"""
Registers a model with the admin.
Expand Down Expand Up @@ -97,6 +117,11 @@ class ResponseView(RestrictedView):
form_widget_args = {"content": {"rows": 8, "style": "font-family: monospace;"}}
column_searchable_list = ("name",)

def on_model_change(self, form, model, is_created):
if validator := form_validators.get(form.content_type.data):
validator(form.content.data)
super().on_model_change(form, model, is_created)

def content_formatter(self, _ctx: Context, model: models.Model, _name: str):
"""
Limits the content field to a maximum length in the list view.
Expand Down
2 changes: 1 addition & 1 deletion api_reflector/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ class Response(Model):

status_code = Column(Integer, nullable=False, default=200)
content_type = Column(String, nullable=False, default="application/json")
content = Column(Text, nullable=False, default="")
content = Column(Text, nullable=False, default="{}")

is_active = Column(Boolean, nullable=False, default=True)

Expand Down