It's a story of using django-request in DRF.
--Save API request history --Items that can be saved --Status code --Method --Path --Request date and time --Whether SSL --Whether it is ajax communication --IP address (** problem, see below **) --Referer --User agent --Language
--History of the contents of the request body such as POST parameters ――Since there is also a security point of view, saving POST parameters is risky, isn't it?
1 Install with pip etc.
pip install django-request
2 Add request
to ʻINSTALLED_APPS`
3 Add request.middleware.RequestMiddleware
to MIDDLEWARE
4 Migration execution
manage.py migrate
The API request is now stored in the request_request
table.
Even the request of django-admin will be saved, so I think it is better to exclude it I made it like this (health is a pass for health check)
REQUEST_IGNORE_PATHS = (
r'^admin/', r'^docs/', r'^health$', r'\.ico$', r'^static/'
)
Since the IP address uses REMOTE_ADDR
, it cannot be obtained correctly if there is a load balancer.
I made it like this with a bittersweet measure (Please tell me if there is a better way)
from request.middleware import RequestMiddleware
class XRequestMiddleware(RequestMiddleware):
def process_response(self, request, response):
# django-REMOTE in request_I have saved ADDR as IP, so I'm forced to HTTP_X_FORWARDED_Change to FOR
http_x_forwarded_for_ip = request.META.get('HTTP_X_FORWARDED_FOR')
remote_addr_ip = request.META.get('REMOTE_ADDR')
if http_x_forwarded_for_ip:
request.META['REMOTE_ADDR'] = http_x_forwarded_for_ip
response = super().process_response(request, response)
if http_x_forwarded_for_ip:
request.META['REMOTE_ADDR'] = remote_addr_ip
return response
By the way, in HTTP_X_FORWARDED_FOR
, IP addresses may be entered separated by commas, so if you use REQUEST_IGNORE_IP
, you should do as follows.
http_x_forwarded_for_ip = request.META.get('HTTP_X_FORWARDED_FOR').split(',')[0]
It's easy to incorporate, and it's essential for data-driven. Another issue is backup when data is accumulated. However, I want you to update the IP address ...
Recommended Posts