python---django的模組簡便使用

來源:互聯網
上載者:User

標籤:hash   boa   簡單   oar   exist   --   AC   login   getattr   

一:登入操作
from django.contrib.auth import authenticate,login,logout  #可以用來做登入驗證
from django.contrib.auth.decorators import login_required  #裝飾器,用於對使用者是否登入進行驗證
1.簡單使用:
def acc_login(request):    error_msg = ‘‘    if request.method == "POST":        username = request.POST.get("username")        password = request.POST.get("password")        user = authenticate(username=username,password=password)    #進行使用者驗證        if user:            login(request,user) #登入狀態,添加入session, request.user = user            return redirect(request.GET.get("next","/"))        else:            error_msg = "Wrong Username Or Password"    return render(request,"login.html",{"error_msg":error_msg})def acc_logout(request):    logout(request) #清除session資料    return redirect("/login.html")from django.contrib.auth.decorators import login_required@login_requireddef dashboard(request):    return render(request,"Sale/dashboard.html")

 

2.方法瞭解(1)authenticate方法
    def authenticate(self, request, username=None, password=None, **kwargs):
        if username is None:            username = kwargs.get(UserModel.USERNAME_FIELD)        try:            user = UserModel._default_manager.get_by_natural_key(username)  #根據使用者名稱擷取使用者物件        except UserModel.DoesNotExist:            # Run the default password hasher once to reduce the timing            # difference between an existing and a non-existing user (#20760).            UserModel().set_password(password)        else:            if user.check_password(password) and self.user_can_authenticate(user):  #根據密碼進行登入驗證,以及擷取使用者的操作許可權                return user
UserModel = get_user_model()
def get_user_model():  #返回使用者表對象,對象由AUTH_USER_MODEL指定,預設是auth.User預設資料表,我們可以在自己的setting檔案中進行覆蓋    """    Returns the User model that is active in this project.    """    return django_apps.get_model(settings.AUTH_USER_MODEL, require_ready=False)
(2)login方法
def login(request, user, backend=None):
def login(request, user, backend=None):    """    Persist a user id and a backend in the request. This way a user doesn‘t    have to reauthenticate on every request. Note that data set during    the anonymous session is retained when the user logs in.    """    session_auth_hash = ‘‘    if user is None:        user = request.user    if hasattr(user, ‘get_session_auth_hash‘):        session_auth_hash = user.get_session_auth_hash()    if SESSION_KEY in request.session:        if _get_user_session_key(request) != user.pk or (                session_auth_hash and                not constant_time_compare(request.session.get(HASH_SESSION_KEY, ‘‘), session_auth_hash)):            # To avoid reusing another user‘s session, create a new, empty            # session if the existing session corresponds to a different            # authenticated user.            request.session.flush()    else:        request.session.cycle_key()    try:        backend = backend or user.backend    except AttributeError:        backends = _get_backends(return_tuples=True)        if len(backends) == 1:            _, backend = backends[0]        else:            raise ValueError(                ‘You have multiple authentication backends configured and ‘                ‘therefore must provide the `backend` argument or set the ‘                ‘`backend` attribute on the user.‘            )    request.session[SESSION_KEY] = user._meta.pk.value_to_string(user)    request.session[BACKEND_SESSION_KEY] = backend    request.session[HASH_SESSION_KEY] = session_auth_hash    if hasattr(request, ‘user‘):        request.user = user    rotate_token(request)    user_logged_in.send(sender=user.__class__, request=request, user=user)
設定session,向request中添加user屬性,可以直接使用request.user擷取User表對象(3)logout方法
def logout(request):
def logout(request):    """    Removes the authenticated user‘s ID from the request and flushes their    session data.    """    # Dispatch the signal before the user is logged out so the receivers have a    # chance to find out *who* logged out.    user = getattr(request, ‘user‘, None)    if hasattr(user, ‘is_authenticated‘) and not user.is_authenticated:        user = None    user_logged_out.send(sender=user.__class__, request=request, user=user)    # remember language choice saved to session    language = request.session.get(LANGUAGE_SESSION_KEY)    request.session.flush()    if language is not None:        request.session[LANGUAGE_SESSION_KEY] = language    if hasattr(request, ‘user‘):        from django.contrib.auth.models import AnonymousUser        request.user = AnonymousUser()
清空session,刪除request.user(4)login_required方法
def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):#function是我們裝飾的函數名,redirect_field_name是跳轉時所帶的參數,預設next
    """    Decorator for views that checks that the user is logged in, redirecting    to the log-in page if necessary.    """    actual_decorator = user_passes_test(        lambda u: u.is_authenticated,        login_url=login_url,        redirect_field_name=redirect_field_name    )    if function:        return actual_decorator(function)    return actual_decorator
函數體
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):    """    Decorator for views that checks that the user passes the given test,    redirecting to the log-in page if necessary. The test should be a callable    that takes the user object and returns True if the user passes.    """    def decorator(view_func):        @wraps(view_func, assigned=available_attrs(view_func))        def _wrapped_view(request, *args, **kwargs):            if test_func(request.user):                return view_func(request, *args, **kwargs)            path = request.build_absolute_uri()            resolved_login_url = resolve_url(login_url or settings.LOGIN_URL)            # If the login url is the same scheme and net location then just            # use the path as the "next" url.            login_scheme, login_netloc = urlparse(resolved_login_url)[:2]            current_scheme, current_netloc = urlparse(path)[:2]            if ((not login_scheme or login_scheme == current_scheme) and                    (not login_netloc or login_netloc == current_netloc)):                path = request.get_full_path()            from django.contrib.auth.views import redirect_to_login            return redirect_to_login(                path, resolved_login_url, redirect_field_name)        return _wrapped_view    return decorator
裝飾器方法

 

python---django的模組簡便使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.