您好,登錄后才能下訂單哦!
本篇文章為大家展示了怎么在Python中使用django框架現(xiàn)獲取訪問者ip地址,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
Python是一種跨平臺的、具有解釋性、編譯性、互動性和面向?qū)ο蟮哪_本語言,其最初的設(shè)計是用于編寫自動化腳本,隨著版本的不斷更新和新功能的添加,常用于用于開發(fā)獨立的項目和大型項目。
在django官方文檔中有一段對request.META的解釋:
HttpRequest.META
A standard Python dictionary containing all available HTTP headers. Available headers depend on the client
and server, but here are some examples:
?CONTENT_LENGTH – The length of the request body (as a string).
?CONTENT_TYPE – The MIME type of the request body.
?HTTP_ACCEPT – Acceptable content types for the response.
?HTTP_ACCEPT_ENCODING – Acceptable encodings for the response.
?HTTP_ACCEPT_LANGUAGE – Acceptable languages for the response.
?HTTP_HOST – The HTTP Host header sent by the client.
?HTTP_REFERER – The referring page, if any.
?HTTP_USER_AGENT – The client's user-agent string.
?QUERY_STRING – The query string, as a single (unparsed) string.
?REMOTE_ADDR – The IP address of the client.
?REMOTE_HOST – The hostname of the client.
?REMOTE_USER – The user authenticated by the Web server, if any.
?REQUEST_METHOD – A string such as "GET" or "POST".
?SERVER_NAME – The hostname of the server.
?SERVER_PORT – The port of the server (as a string).
With the exception of CONTENT_LENGTH and CONTENT_TYPE, as given above, any HTTP headers in the
request are converted to META keys by converting all characters to uppercase, replacing any hyphens with
underscores and adding an HTTP_ prefix to the name. So, for example, a header called X-Bender would be
mapped to the META key HTTP_X_BENDER.
Note that runserver strips all headers with underscores in the name, so you won't see them in META. This
prevents header-spoofing based on ambiguity between underscores and dashes both being normalizing to under-
scores in WSGI environment variables. It matches the behavior of Web servers like Nginx and Apache 2.4+.
然后我們來打印一下其中的條目進行驗證:
request_meta = request.META info = [] for k, v in request_meta.items(): info.append(k) print info >>> ['wsgi.version', 'RUN_MAIN', 'HTTP_REFERER', 'HTTP_HOST', 'SERVER_PROTOCOL', 'SERVER_SOFTWARE', 'SCRIPT_NAME', 'LESSOPEN', 'SSH_CLIENT', 'REQUEST_METHOD', 'LOGNAME', 'USER', 'HOME', 'QUERY_STRING', 'PATH', 'MYSQL_DATABASE_URI', 'wsgi.errors', 'TERADATA_JACKAL_URI', 'LANG', 'TERM', 'SHELL', 'TZ', 'HTTP_COOKIE', 'J2REDIR', 'REMOTE_ADDR', 'SHLVL', 'wsgi.url_scheme', 'HTTP_VIA', 'SERVER_PORT', 'wsgi.file_wrapper', 'JAVA_HOME', 'CONTENT_LENGTH', 'HTTP_CONNECTION', 'XDG_RUNTIME_DIR', 'TERADATA_PASSWORD', 'PYTHONPATH', 'COMP_WORDBREAKS', 'VIRTUAL_ENV', u'CSRF_COOKIE', 'J2SDKDIR', 'wsgi.input', 'HTTP_USER_AGENT', 'PS1', 'wsgi.multithread', 'HTTP_UPGRADE_INSECURE_REQUESTS', 'HTTP_CACHE_CONTROL', 'XDG_SESSION_ID', '_', 'HTTP_ACCEPT', 'DERBY_HOME', 'SSH_CONNECTION', 'LESSCLOSE', 'SERVER_NAME', 'GATEWAY_INTERFACE', 'HTTP_X_FORWARDED_FOR', 'SSH_TTY', 'OLDPWD', 'wsgi.multiprocess', 'HTTP_ACCEPT_LANGUAGE', 'wsgi.run_once', 'PWD', 'DJANGO_SETTINGS_MODULE', 'CONTENT_TYPE', 'TERADATA_SIMBA_URI', 'MAIL', 'LS_COLORS', 'REMOTE_HOST', 'HTTP_ACCEPT_ENCODING', 'PATH_INFO']
通常訪問者的ip會包含在上邊的鍵值對中,我們可以通過一下方式獲取ip:
通常訪問者的IP就在其中,所以我們可以用下列方法獲取用戶的真實IP:
#X-Forwarded-For:簡稱XFF頭,它代表客戶端,也就是HTTP的請求端真實的IP,只有在通過了HTTP 代理或者負載均衡服務(wù)器時才會添加該項。 def get_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0]#所以這里是真實的ip else: ip = request.META.get('REMOTE_ADDR')#這里獲得代理ip return ip
結(jié)合上一篇的日志模塊,可以實現(xiàn)記錄登陸用戶的ip信息:
remote_info = '' x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: remote_info = 'HTTP_X_FORWARDED_FOR:' + x_forwarded_for.split(',')[0] remote_addr = request.META.get('REMOTE_ADDR') if remote_addr: remote_info += ' REMOTE_ADDR:' + remote_addr if pass_auth: user.last_login_at = timezone.now() try: user.save() except Exception, msg: return JsonResponse({'result': 'Error', 'message': str(msg)}) request.session['user_id'] = user_id request.session.set_expiry(9000) logger.info('[Success] '+ user_id+' has logged in! '+remote_info) return JsonResponse({'result': 'Success', 'message': 'Login successfully.'}) else: logger.warning('[Failed] '+ user_id + ' failed to login! '+remote_info) return JsonResponse({'result': 'Error', 'message': 'Username or Password is incorrect.'})
上述內(nèi)容就是怎么在Python中使用django框架現(xiàn)獲取訪問者ip地址,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。