Closed simonw closed 1 day ago
For middleware:
import djp
@djp.hookimpl
def middleware():
return ["django_zen_of_python_header.middleware.ZenOfPythonMiddleware"]
And that middleware.py
file:
import importlib
import random
import sys
class ZenOfPythonMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
response["Zen-Of-Python"] = random.choice(zen_lines)
return response
def get_zen_of_python():
captured_output = []
original_print = print
try:
sys.modules["builtins"].print = captured_output.append
importlib.import_module("this")
finally:
sys.modules["builtins"].print = original_print
# Return all non-blank lines except the first
lines = captured_output[0].splitlines()[1:]
return [line for line in lines if line.strip()]
# This can only be run once or the import trick breaks
zen_lines = get_zen_of_python()
For settings, one that configures dj-database-url
for you automatically:
import djp
import dj_database_url
@djp.hookimpl
def settings(current_settings):
current_settings["DATABASES"]["default"] = dj_database_url.config(
conn_max_age=600,
conn_health_checks=True,
)
https://github.com/simonw/django-plugin-django-header serves a random composition by
Django Reinhardt in a Django-Composition:
HTTP header.
That example plugin has tests, using the pattern from https://til.simonwillison.net/django/pytest-django
installed_apps()
https://github.com/simonw/django-plugin-blogmiddleware()
https://github.com/simonw/django-plugin-django-headerurlpatterns()
https://github.com/simonw/django-plugin-blogsettings(current_settings)
https://github.com/simonw/django-plugin-database-url