[Fixed]-Monkey patching Django app in another app

1đź‘Ť

I am really not for monkey patching (except during test cases, even then I believe mock is better).

Why don’t you try the simpler option? Create a proxy of the app within your project (it will be called first, due to Python’s lookup system) and then simply patch the methods you want, and bypass the ones you don’t to the original app.

So if the component is called “FooProject” you would create another app called “FooProject” in your project, in this app’s __init__.py:

from originalproject import FooProject as OriginalFoo

class FooProject(OriginalFoo):
    def override_method_here(self, foo):
       return my_own_magic(foo)
👤Burhan Khalid

1đź‘Ť

I ended up doing this in the wsgi portion of initialization

In wsgi.py

# Monkey Patch a few things
from huey_monitor.apps import HueyMonitorConfig
HueyMonitorConfig.verbose_name = 'Task Monitor'
👤Kevin Parker

0đź‘Ť

Monkey-patching is a hack, hard to maintain and should be avoided.

The principle is to patch your code before it gets imported, before Django itself is loaded. Depending on what is your entry point you will find the right place to patch your code.

Using Django 1.9 I can think about two entry points:

  1. wsgi.py – while your code is run on a WSGI container
  2. manage.py – while any management command (shell, runserver, migrate) is run
👤domtes

0đź‘Ť

I just had a similar need to monkey patch the django-allauth/django-invitation adapter and stumbled upon the same limitations (apps_ready == False).

So I used partially what @domtes mentioned, editing manage.py and inserting there a method to rewrite partially the adapter I had to modify and thus appending the required behaviour. By the time django loaded django-invitations, the method was already rewritten.

It was a simple, dirty and possibly not recommended search & replace method in which I rewrote the targeted .py file belonging to the library structure.

It suppose to be compatible to future versions, but I admit it is a source of bugs and problems.

Cheers

👤dfcoelho

Leave a comment