1. 程式人生 > 程式設計 >Django 使用者登陸訪問限制例項 @login_required

Django 使用者登陸訪問限制例項 @login_required

在網站開發過程中,經常會遇到這樣的需求:使用者登陸系統才可以訪問某些頁面,如果使用者沒有登陸而直接訪問就會跳轉到登陸介面。

要實現這樣的需求其實很簡單:

1、在相應的 view 方法的前面新增 django 自帶的裝飾器 @login_required

2、在 settings.py 中配置 LOGIN_URL 引數

3、修改 login.html 表單中的 action 引數

# views.py
from djanco.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
@login_required
 
def index(request):
return render_to_response('index.html')
# settings.py
....
LOGIN_URL = '/accounts/login/' # 根據你網站的實際登陸地址來設定
....

如果要使用 django 預設登陸地址,則可以通過在 urls.py 中新增如此配置:

# urls.py
....
url(r'^accounts/login/',views.login),....
# login.html
<div class="container">
<form class="form-signin" action="/accounts/login/" method="post">
{% csrf_token %}
<!--csrf_token:生成令牌-->
<h2 class="form-signin-heading" align="center">登入系統</h2>
<label for="inputUsername" class="sr-only">username</label>
<input type="text" name="username" id="inputUsername" class="form-control" placeholder="username" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" required>
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me"> 記住密碼
</label>
</div>
<br />
<button class="btn btn-lg btn-primary btn-block" type="submit">登入</button>
<br />
<span style="color: red;">{{ login_err }}</span>
</form>
</div>
<!-- /container -->

補充知識:Django 之禁止特定的 IP訪問系統

有時候我們上一些網站,或者用爬蟲技術去爬,使用的次數很頻繁,會被網站記錄加入黑名單,當我們再次訪問的時候會被提示,你不能訪問該網址。

那麼這個技術在 Django 裡面如何實現呢?

我搜索了一些方法,找到的資料不多,有一些可能有效,但是沒有可以直接執行 demo,那麼這裡就提供一種使用中介軟體的 demo,親測有效。

自定義一個 middleware.py 檔案,這個檔案要在 Django 的 settings.py 配置檔案中被引用,所以我放在與 settings.py 同文件夾的目錄下。

middleware.py

from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin # 1.10.x

class TestMiddleware(MiddlewareMixin):
 def process_view(self,request,view_func,*view_args,**view_kwargs):
  EXCLUDE_IPS = ['192.168.1.54']
  if 'HTTP_X_FORWARDED_FOR' in request.META:
   ip = request.META['HTTP_X_FORWARDED_FOR']
  else:
   ip = request.META['REMOTE_ADDR']
  if ip in EXCLUDE_IPS:
   return HttpResponse('<h1>您的ip被禁止</h1>')

其中,關於自定義中介軟體的函式名稱例如 process_view() ,還有其它的例如 _init_ 之類在文件中有具體解釋,這裡只用到這個。

然後在 settings.py 中引入這個中介軟體:

settings.py

[
 'hunter.middleware.TestMiddleware',]

其中 hunter 是我的系統的名稱,在末尾新增即可。

然後重啟我們的 Django 系統,就可以實現禁止特定 IP 訪問的功能。

注意

這個 EXCLUDE_IPS 是我手動新增的一個列表,如果想對這個 IP 進行可持續發展的管理,可以在使用者訪問系統的時候記錄下他們的 IP ,然後記錄在 MySQL 資料庫中,對其中的異常資料進行禁止的處理。

對於訪問使用者頻繁訪問、新增黑名單有很好的療效,這裡值得推薦。

以上這篇Django 使用者登陸訪問限制例項 @login_required就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。