【问题标题】:Read IP address from api call in Tastypie?从 Tastypie 的 api 调用中读取 IP 地址?
【发布时间】:2014-10-06 19:25:28
【问题描述】:
在我的代码中,我想知道进行 api 调用的客户端的 IP 地址。有什么办法吗?
例如:假设某个人发起了这个 api 调用,例如"http://server_url/api/v1/range/setup/"
我可以在服务器的 api.py 中读取他机器的 ip 地址吗?
【问题讨论】:
-
我假设您使用的是 django.. 如果是这样,请参阅 this。还请添加您到目前为止所获得的内容..
标签:
python
python-3.x
tastypie
【解决方案1】:
我曾经使用过这种方法,它应该从您的请求元数据中返回 IP 地址:
def getClientIPaddress(request):
http_x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if http_x_forwarded_for:
ip_address = http_x_forwarded_for.split(',')[0]
else:
ip_address = request.META.get('REMOTE_ADDR')
return ip_address
然后,您可以从处理 API 调用的任何位置调用 getClientIPaddress 方法,例如:
class YourResource(ModelResource):
class Meta:
#meta code here
def obj_create(self, bundle, **kwargs):
ip = getClientIPaddress(bundle.request)
#your code here
def obj_get_list(self, bundle, **kwargs):
ip = getClientIPaddress(bundle.request)
#your code here