Skip to content

Commit

Permalink
Settings module + Browsable API toggle
Browse files Browse the repository at this point in the history
  • Loading branch information
stevelacey committed Dec 14, 2021
1 parent 0e262c5 commit c3fe7ab
Show file tree
Hide file tree
Showing 7 changed files with 34 additions and 22 deletions.
6 changes: 6 additions & 0 deletions worf/conf.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from importlib import import_module

from django.utils.functional import SimpleLazyObject


settings = SimpleLazyObject(lambda: import_module("worf.settings"))
2 changes: 1 addition & 1 deletion worf/serializers.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import marshmallow

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.db.models.fields.files import FieldFile

from worf import fields # noqa: F401
from worf.casing import snake_to_camel
from worf.conf import settings


class SerializerOptions(marshmallow.SchemaOpts):
Expand Down
9 changes: 9 additions & 0 deletions worf/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from django.conf import settings


WORF_API_NAME = getattr(settings, "WORF_API_NAME", "Worf API")
WORF_API_ROOT = getattr(settings, "WORF_API_ROOT", "/api/")

WORF_BROWSABLE_API = getattr(settings, "WORF_BROWSABLE_API", True)

WORF_DEBUG = getattr(settings, "WORF_DEBUG", settings.DEBUG)
6 changes: 3 additions & 3 deletions worf/templates/worf/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<meta name="robots" content="none,noarchive"/>
{% endblock %}

<title>{{ api_name }}: {{ request.get_full_path }}</title>
<title>{{ settings.WORF_API_NAME }}: {{ request.get_full_path }}</title>

{% block style %}
<link href="https://unpkg.com/[email protected]/dist/tailwind.min.css" crossorigin="anonymous" referrerpolicy="no-referrer" rel="stylesheet">
Expand Down Expand Up @@ -35,8 +35,8 @@
<nav class="p-4">
<div class="max-w-5xl mx-auto">
{% block branding %}
<a href="{{ api_root }}" class="font-medium text-lg text-white" rel="nofollow">
{{ api_name }}
<a href="{{ settings.WORF_API_ROOT }}" class="font-medium text-lg text-white" rel="nofollow">
{{ settings.WORF_API_NAME }}
</a>
{% endblock %}
</div>
Expand Down
6 changes: 3 additions & 3 deletions worf/validators.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
from datetime import datetime
from uuid import UUID

from django.conf import settings
from django.db import models
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from django.utils.dateparse import parse_datetime

from worf.conf import settings
from worf.exceptions import NotImplementedInWorfYet


Expand Down Expand Up @@ -167,7 +167,7 @@ def validate_bundle(self, key):

if self.request.method in write_methods and key not in serializer.write():
message = f"{self.keymap[key]} is not editable"
if settings.DEBUG:
if settings.WORF_DEBUG:
message += f":: {serializer}"
raise ValidationError(message)

Expand Down Expand Up @@ -240,7 +240,7 @@ def validate_bundle(self, key):

else:
message = f"{field.get_internal_type()} has no validation method for {key}"
if settings.DEBUG:
if settings.WORF_DEBUG:
message += f":: Received {self.bundle[key]}"
raise NotImplementedInWorfYet(message)
# TODO
Expand Down
19 changes: 8 additions & 11 deletions worf/views/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from io import BytesIO
from urllib.parse import parse_qs

from django.conf import settings
from django.core.exceptions import (
ImproperlyConfigured,
ObjectDoesNotExist,
Expand All @@ -18,14 +17,12 @@
from django.views.decorators.cache import never_cache
from django.utils.decorators import method_decorator

from worf.conf import settings
from worf.casing import camel_to_snake, snake_to_camel
from worf.exceptions import HTTP_EXCEPTIONS, HTTP404, HTTP422, PermissionsException
from worf.serializers import LegacySerializer
from worf.validators import ValidationMixin

api_name = getattr(settings, "WORF_API_NAME", "Worf API")
api_root = getattr(settings, "WORF_API_ROOT", "/api/")


@method_decorator(never_cache, name="dispatch")
class APIResponse(View):
Expand All @@ -45,23 +42,23 @@ def render_to_response(self, data=None, status_code=200):
msg += "render_to_response, nor did its serializer method"
raise ImproperlyConfigured(msg)

is_html_request = (
"text/html" in self.request.headers.get("Accept", "")
is_browsable = (
settings.WORF_BROWSABLE_API
and "text/html" in self.request.headers.get("Accept", "")
and self.request.GET.get("format") != "json"
)

json_kwargs = dict(json_dumps_params=dict(indent=2)) if is_html_request else {}
json_kwargs = dict(json_dumps_params=dict(indent=2)) if is_browsable else {}

response = JsonResponse(data, **json_kwargs) if data != "" else HttpResponse()
response.status_code = status_code

if is_html_request:
if is_browsable:
template = "worf/api.html"
context = dict(
api_name=api_name,
api_root=api_root,
content=response.content.decode("utf-8"),
response=response,
settings=settings,
)
response = TemplateResponse(self.request, template, context=context)
response.status_code = status_code
Expand Down Expand Up @@ -118,7 +115,7 @@ def _check_permissions(self):
if response == 200:
continue

if settings.DEBUG:
if settings.WORF_DEBUG:
raise PermissionsException(
"Permissions function {}.{} returned {}. You'd normally see a 404 here but DEBUG=True.".format(
method.__module__, method.__name__, response
Expand Down
8 changes: 4 additions & 4 deletions worf/views/list.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@
from functools import reduce
import warnings

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.paginator import Paginator, EmptyPage
from django.db.models import Q

from worf.casing import camel_to_snake
from worf.conf import settings
from worf.exceptions import HTTP420
from worf.filters import apply_filterset, generate_filterset
from worf.views.base import AbstractBaseAPI
Expand Down Expand Up @@ -165,7 +165,7 @@ def get_processed_queryset(self):
if order_by:
queryset = queryset.order_by(*order_by)
except TypeError as e:
if settings.DEBUG:
if settings.WORF_DEBUG:
raise HTTP420(f"Error, {self.lookup_kwargs}, {e.__cause__}")
raise e

Expand All @@ -181,7 +181,7 @@ def paginated_results(self):
queryset = self.get_processed_queryset()
request = self.request

if settings.DEBUG:
if settings.WORF_DEBUG:
self.query = str(queryset.query)

default_per_page = getattr(self, "results_per_page", self.per_page)
Expand Down Expand Up @@ -235,7 +235,7 @@ def serialize(self):
}
)

if not settings.DEBUG:
if not settings.WORF_DEBUG:
return payload

if not hasattr(self, "lookup_kwargs"):
Expand Down

0 comments on commit c3fe7ab

Please sign in to comment.