Minor refactoring for middleware.py