Update middleware.py

Avoids race condition a la Python issue #7980. Might be not necessary if using new imports from Python 3.