simonw / djp

A plugin system for Django
https://djp.readthedocs.io
Apache License 2.0
25 stars 0 forks source link

Example plugins to exercise each hook #2

Closed simonw closed 1 day ago

simonw commented 2 days ago
simonw commented 2 days 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()
simonw commented 2 days ago

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,
    )
simonw commented 2 days ago

https://github.com/simonw/django-plugin-django-header serves a random composition by Django Reinhardt in a Django-Composition: HTTP header.

simonw commented 2 days ago

That example plugin has tests, using the pattern from https://til.simonwillison.net/django/pytest-django

https://github.com/simonw/django-plugin-django-header/blob/main/tests/test_django_plugin_django_header.py

simonw commented 2 days ago

Built https://github.com/simonw/django-plugin-blog

simonw commented 1 day ago

https://github.com/simonw/django-plugin-database-url