gpt4 book ai didi

python - Django RequestFactory 添加 HTTP_X_FORWARDED_FOR

转载 作者:行者123 更新时间:2023-12-04 00:04:38 25 4
gpt4 key购买 nike

我有这个代码块,我正在尝试为其编写测试:

def get_client_ip(req):
"""
This is used to get the user's IP from the request object.

"""
x_forwarded_for = req.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = req.META.get('REMOTE_ADDR', "unknown")
return ip

到目前为止,我已经能够测试 if 语句的 else 部分。
这是我的测试目前的样子:
def test_get_client_ip(self):
"""
Test the get Client IP fuction with a request.

"""
# Create an instance of a GET request.
request = self.factory.get('/home')
ip = get_client_ip(request)
self.assertEqual(ip, '127.0.0.1')

我将如何将“HTTP_X_FORWARDED_FOR”添加到请求对象的 META 中?

最佳答案

事实证明,您可以使用 get 方法中的 extra 关键字为 get 请求提供额外的 header :
https://docs.djangoproject.com/en/2.0/topics/testing/tools/#django.test.Client.get

工作代码如下:

    def test_get_client_ip(self):
"""
Test the get Client IP fuction with a request.

"""
# Create an instance of a GET request.
request = self.factory.get('/home')
ip = get_client_ip(request)
self.assertEqual(ip, '127.0.0.1')
request = self.factory.get('/home', HTTP_X_FORWARDED_FOR="8.8.8.8")
ip = get_client_ip(request)
self.assertEqual(ip, '8.8.8.8')

关于python - Django RequestFactory 添加 HTTP_X_FORWARDED_FOR,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50498944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com