Reading CloudFlare headers in a Django middleware2021-01-22
For my new Django project, DB Buddy, I’m using CloudFlare as my CDN. It has a bunch of useful features that would otherwise take extra work, such as DDoS protection, HTML minification, and analytics.
Since CDN’s proxy your site, all requests are seen to be coming from their servers’ IP’s, rather than actual users’ IP’s.
But sometimes you need to inspect real user IP’s, for example to implement rate limiting.
To help with this, CloudFlare adds several useful headers, including
CF-Connecting-IP with the client’s real IP.
In order to provide an interface to get the client’s IP, whether my project is running in development or production, I added a middleware to attach the client IP as
Although the middleware is short, I still made sure to write some tests.
I based these on my subclass of Django’s
SimpleTestCase, since no DB queries should be made.
To generate example requests, I used Django’s
The end result was this test case with one test for each branch in the middleware:
With the middleware now built, I installed it in the
MIDDLEWARE setting and then implemented login rate limiting with django-ratelimit using
May this help you make your own middleware,
Want better tests? Check out my book Speed Up Your Django Tests which teaches you to write faster, more accurate tests.
One summary email a week, no spam, I pinky promise.
- Simple In-Memory Caching of Django Model Data With cachetools
- Efficient Reloading in Django’s Runserver With Watchman
- Introducing django-version-checks
© 2021 All rights reserved.