技術源於生活,服務生活python
線上地址:api.imibi.cnnginx
1.使用Redis的0號數據庫,數據格式是hash.redis
import redis
con = redis.Redis(host='localhost', port=6379, decode_responses=True, db=0)
複製代碼
2.hash的鍵值對分別是key=ip,value=訪問次數 數據庫
數據統計函數vim
def set_len_data(ip):
"""訪問次數統計"""
ip_lens = con.hmget('ip', ip)[0]
if ip_lens == None:
'未記錄IP'
ip_dict = {ip: 1, 'is_active':0}
lens_lens = 1
else:
ip_lens= int(ip_lens)+1
ip_dict = {ip: ip_lens}
con.hmset('ip', ip_dict)
return ip_lens
複製代碼
經過resquest對象獲取訪問IPapi
ip = request.remote_addr # 獲取IP
ip_lens = set_len_data(ip) # 存儲到redis中
複製代碼
給URL路由添加訪問次數統計方法 函數
若是使用nginx反向代理,會致使用戶訪問的IP所有爲127.0.0.1。
能夠從$ proxy_add_x_forwarded_for中獲取到用戶的真實IP,這裏須要修改nginx的 x_forwarded_for
複製代碼
nginx配置spa
location / {
proxy_set_header Host $host;
proxy_set_header X-real-ip $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
複製代碼
名詞解釋:代理
$remote_addr 獲取到上一級代理的IP
$proxy_add_x_forwarded_for
獲取到結果例如:(61.151.178.76, 10.10.10.89),第一個是用戶的真實IP,第二個是一級代理的IP,依此類推。
複製代碼