Skip to content

Commit 4ff0947

Browse files
committed
fix get client ip
1 parent b528a8a commit 4ff0947

File tree

2 files changed

+15
-3
lines changed

2 files changed

+15
-3
lines changed

web-framework/python/django/publish.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ Type: Project
33
Name: start-django-dipper
44
Provider:
55
- 阿里云
6-
Version: 0.0.1
6+
Version: 0.0.2
77
Description: 本案例是将 Python Web 框架中,非常受欢迎的 Django 框架,快速创建并部署到阿里云函数计算 FC。
88
HomePage: https://github.com/devsapp/start-web-framework/tree/dipper/web-framework/python/django
99
Organization: 阿里云函数计算(FC)

web-framework/python/django/src/code/index/views.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,18 @@
22
import json
33
import arrow
44

5+
6+
def get_client_ip(request):
7+
# 检查 X-Forwarded-For 头部,它通常包含客户端 IP
8+
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
9+
if x_forwarded_for:
10+
# X-Forwarded-For 可能包含多个 IP 地址,第一个为客户端 IP
11+
client_ip = x_forwarded_for.split(',')[0].strip()
12+
else:
13+
# 如果没有 X-Forwarded-For,使用 REMOTE_ADDR
14+
client_ip = request.META.get('REMOTE_ADDR')
15+
return client_ip
16+
517
# Create your views here.
618
def index(request):
719
body_str = request.body.decode('utf-8')
@@ -11,7 +23,7 @@ def index(request):
1123
"query": dict(request.GET),
1224
"path": "",
1325
"data": body_str,
14-
"clientIp": request.META.get('REMOTE_ADDR'),
26+
"clientIp": get_client_ip(request),
1527
},
1628
}
1729
return JsonResponse(response_content)
@@ -25,7 +37,7 @@ def default(request, path):
2537
"query": dict(request.GET),
2638
"path": path,
2739
"data": body_str,
28-
"clientIp": request.META.get('REMOTE_ADDR'),
40+
"clientIp": get_client_ip(request),
2941
},
3042
}
3143
return JsonResponse(response_content)

0 commit comments

Comments
 (0)