如何用Django测试客户端指定IP地址?

时间:2022-09-16 13:25:44

I am testing an API with Django test client. The API uses geo blocking so in my test I need to specify an IP address to make sure it works properly. How can I do that?

我正在使用Django测试客户端测试API。 API使用地理阻止,所以在我的测试中我需要指定一个IP地址以确保它正常工作。我怎样才能做到这一点?

I am making a request in my test like this:

我在我的测试中提出这样的请求:

from django.test.client import Client as HttpClient
.
.
.
client = HttpClient()
response = client.get(uri + query_string)

4 个解决方案

#1


11  

The Client.get() method has an extra keyword arguments parameter, which can be used to specify headers.

Client.get()方法有一个额外的关键字参数参数,可用于指定标题。

c.get(/my-url/, REMOTE_ADDR="127.0.0.1") 

#2


5  

Pass REMOTE_ADDR in constructor.

在构造函数中传递REMOTE_ADDR。

client = HttpClient(REMOTE_ADDR='127.0.0.1')

or

要么

client.get('/path/', {'param':'foo'}, **{'HTTP_USER_AGENT':'firefox-22', 'REMOTE_ADDR':'127.0.0.1'})

#3


-1  

As simple like this:

像这样简单:

client_address = request.META.get('HTTP_X_FORWARDED_FOR') or request.META.get('REMOTE_ADDR')

#4


-1  

You can also set it for all future requests:

您还可以为将来的所有请求设置它:

client.defaults['REMOTE_ADDR'] = '1.2.3.4'

Also with subclassing:

还有子类化:

class DecoratedApiClient(Client):
    def set_ip_addr(self, ip_addr):
        self.defaults['REMOTE_ADDR'] = ip_addr

client = DecoratedApiClient()
client.set_ip_addr('1.2.3.4')

#1


11  

The Client.get() method has an extra keyword arguments parameter, which can be used to specify headers.

Client.get()方法有一个额外的关键字参数参数,可用于指定标题。

c.get(/my-url/, REMOTE_ADDR="127.0.0.1") 

#2


5  

Pass REMOTE_ADDR in constructor.

在构造函数中传递REMOTE_ADDR。

client = HttpClient(REMOTE_ADDR='127.0.0.1')

or

要么

client.get('/path/', {'param':'foo'}, **{'HTTP_USER_AGENT':'firefox-22', 'REMOTE_ADDR':'127.0.0.1'})

#3


-1  

As simple like this:

像这样简单:

client_address = request.META.get('HTTP_X_FORWARDED_FOR') or request.META.get('REMOTE_ADDR')

#4


-1  

You can also set it for all future requests:

您还可以为将来的所有请求设置它:

client.defaults['REMOTE_ADDR'] = '1.2.3.4'

Also with subclassing:

还有子类化:

class DecoratedApiClient(Client):
    def set_ip_addr(self, ip_addr):
        self.defaults['REMOTE_ADDR'] = ip_addr

client = DecoratedApiClient()
client.set_ip_addr('1.2.3.4')