1
0
mirror of https://github.com/netbox-community/netbox.git synced 2024-05-10 07:54:54 +00:00

Move NetBoxFakeRequest and copy_safe_request() from utilities.utils to utilities.request

This commit is contained in:
Jeremy Stretch
2024-03-21 12:48:08 -04:00
parent 3547ea376c
commit ef774319f4
5 changed files with 47 additions and 39 deletions

View File

@@ -2,11 +2,54 @@ from django.utils.translation import gettext_lazy as _
from netaddr import AddrFormatError, IPAddress
from urllib.parse import urlparse
from .constants import HTTP_REQUEST_META_SAFE_COPY
__all__ = (
'NetBoxFakeRequest',
'copy_safe_request',
'get_client_ip',
)
#
# Fake request object
#
class NetBoxFakeRequest:
"""
A fake request object which is explicitly defined at the module level so it is able to be pickled. It simply
takes what is passed to it as kwargs on init and sets them as instance variables.
"""
def __init__(self, _dict):
self.__dict__ = _dict
#
# Utility functions
#
def copy_safe_request(request):
"""
Copy selected attributes from a request object into a new fake request object. This is needed in places where
thread safe pickling of the useful request data is needed.
"""
meta = {
k: request.META[k]
for k in HTTP_REQUEST_META_SAFE_COPY
if k in request.META and isinstance(request.META[k], str)
}
return NetBoxFakeRequest({
'META': meta,
'COOKIES': request.COOKIES,
'POST': request.POST,
'GET': request.GET,
'FILES': request.FILES,
'user': request.user,
'path': request.path,
'id': getattr(request, 'id', None), # UUID assigned by middleware
})
def get_client_ip(request, additional_headers=()):
"""
Return the client (source) IP address of the given request.