(MacOS) Django can't find the MySQL driver ... but, why?

Here's the traceback:

Exception in thread django-main-thread:
Traceback (most recent call last):
  File "/Users/mike/.virtualenvs/djangoprod/lib/python3.10/site-packages/MySQLdb/__init__.py", line 18, in <module>
    from . import _mysql
ImportError: dlopen(/Users/mike/.virtualenvs/djangoprod/lib/python3.10/site-packages/MySQLdb/_mysql.cpython-310-darwin.so, 0x0002): Library not loaded: '@rpath/libmysqlclient.21.dylib'
  Referenced from: '/Users/mike/.virtualenvs/djangoprod/lib/python3.10/site-packages/MySQLdb/_mysql.cpython-310-darwin.so'
  Reason: tried: '/usr/lib/libmysqlclient.21.dylib' (no such file)

And here's the problem:

$ locate libmysqlclient
[...]
/usr/local/mysql-8.0.31-macos12-x86_64/lib/libmysqlclient.21.dylib

So, the library is there, but Django isn't finding it. So, before I "bang my head uselessly against this thing," especially given that it used to work, will someone out there kindly give me a nudge in the right direction? What am I missing here?

I particularly notice that the package is trying the path, /usr/lib... when that is not in fact the proper location here.

In particular: I see in the text a reference to @rpath which I am sure is the root cause of the problem – obviously, the value is wrong. (I notice that it does have the library-name right.) I'm frankly not familiar with this @rpath thing, nor exactly what sets it.

Thank you kindly in advance ...

Sorry to have asked this question so many times ...

It appears that System Integrity Protection (SIP) was the root cause of the problem. Turning it off caused the library to be found, once it had been added with export DYLD_LIBRARY_PATH ...etc...

Instructions and explanation can be found here: https://developer.apple.com/documentation/security/disabling_and_enabling_system_integrity_protection

According to the Apple Developer website, this causes the value of DYLD_LIBRARY_PATH to be denied to child processes. And apparently, the Python interface for MySQL must use one somewhere. (How doing such an odd thing would benefit "system integrity" is quite beyond me, but Apple must have its reasons. ...)

FYI: I also found out from Apple's man dyld page what @RPATH means and where its value comes from.

Back to Top