• django session 有login方法控制


    url(r'^$', newview.index),
    url(r'^get_name/$', newview.get_name),
    url(r'^index/$', newview.index),
    
    def index(req):
             return render_to_response('index.html')
    		 
    		 
    <html>
    	<head>		
    <title>Index</title>
    		<link rel='stylesheet' type='text/css' href='/static/news/Css/Index/index.css'/>
    	</head>
    	<body>
    		<h1>泰隆运维管理平台</h1>
    		<!--图片标签-->
    		<img class="img_bk" src="/static/news/scan.jpg"/>
    		<!--表单提交-->
    		<form  class="form1" action="/main/" method="post" >
    			<table cellspacing="0" cellpadding="0">
    				<tr>
    					<td class="td1">用户名:</td>
    					<td><input type="text" name="username"/></td>
    					<td class="td3" ></td>
    					<td class="td4"></td>
    				<tr/>
    				<tr>
    					<td class="td1">密码:</td>
    					<td><input type="password" name="password"/></td>
    					<td class="td3"></td>
    					<td class="td4"></td>
    				<tr/>
    				<!-- <tr> -->
    					<!-- <td class="td1">验证码:</td> -->
    					<!-- <td>   <input type='text' name='code' /></td> -->
    					<!-- <td class="td3"><img src="__APP__/Public/code" onclick='this.src=this.src+"?"+Math.random()'/></td> -->
    					<!-- <td class="td4"></td> -->
    				<!-- </tr> -->
    				<tr>
    					<td class="td1"></td>
    					<td><input type="submit" value="" name="imgLogin" /></td>
    					<td class="td3"></td>
    					<td class="td4"></td>
    				</tr>
    			</table>
    		</form>
    	</body>
    </html>
    
    
    def main(req):
        # Do something for anonymous users.
        from django.contrib.auth import authenticate, login
        print '1111111111111111111111111'
        print req
        print dir(req)
        print req.session
        print dir(req.session)
        print '----session_key--------------'
        print req.session.session_key
        print '----session_key--------------'
        print '1111111111111111111111111'
        username=req.POST['username']
        password = req.POST['password']
        print '-------user-------------'
        user = authenticate(username=username, password=password)
        print user
        print type(user)
        print '22222222222222222222222'
        print req
        print dir(req)
        print req.session
        print dir(req.session)
        print '----session_key--------------'
        print req.session.session_key
        print '----session_key--------------'
        print '22222222222222222222222'
        print '-------user-------------'
        if user is not None:
            print '33333333333333333'
            print req
            print dir(req)
            print req.session
            print dir(req.session)
            print '----session_key--------------'
            print req.session.session_key
            print '----session_key--------------'
            print '33333333333333333333'
            if user.is_active:
                login(req, user)
                print '4444444444444444'
                print req
                print dir(req)
                print req.session
                print dir(req.session)
                print '----session_key--------------'
                print req.session.session_key
                print '----session_key--------------'
                print '444444444444444444444'
                # Redirect to a success page.
                return render_to_response('main.html')
            else:
                print '1111111111111111'
                # Return a 'disabled account' error message
        else:
            # Return an 'invalid login' error message.
            print '2222222222222222'
            return render_to_response('index.html')
    		
    		
    解析1 :
    
    username=req.POST['username']
    password = req.POST['password']
    print '-------user-------------'
    user = authenticate(username=username, password=password)
    print user
    print '-------user-------------'
    
    
    -------user-------------
    None
    <type 'NoneType'>
    -------user-------------
    
    
    如果用户密码没有验证通过,就会返回None
    
    
    
    如果用户密码验证通过:
    
    -------user-------------
    015208
    <class 'django.contrib.auth.models.User'>
    -------user-------------
    
    2.	
    1111111111111111111111111
    <WSGIRequest: POST '/main/'>
    ['COOKIES', 'FILES', 'GET', 'META', 'POST', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_cache_update_cache', '_encoding', '_get_post', '_get_raw_host', '_get_scheme', '_initialize_handlers', '_load_post_and_files', '_mark_post_parse_error', '_messages', '_post_parse_error', '_read_started', '_set_post', '_stream', '_upload_handlers', 'body', 'build_absolute_uri', 'close', 'content_params', 'content_type', 'encoding', 'environ', 'get_full_path', 'get_host', 'get_port', 'get_raw_uri', 'get_signed_cookie', 'is_ajax', 'is_secure', 'method', 'parse_file_upload', 'path', 'path_info', 'read', 'readline', 'readlines', 'resolver_match', 'scheme', 'session', 'upload_handlers', 'user', 'xreadlines']
    <django.contrib.sessions.backends.db.SessionStore object at 0x399ba90>
    ['TEST_COOKIE_NAME', 'TEST_COOKIE_VALUE', '_SessionBase__not_given', '_SessionBase__session_key', '__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_get_new_session_key', '_get_or_create_session_key', '_get_session', '_get_session_key', '_hash', '_session', '_session_key', '_set_session_key', '_validate_session_key', 'accessed', 'clear', 'clear_expired', 'create', 'create_model_instance', 'cycle_key', 'decode', 'delete', 'delete_test_cookie', 'encode', 'exists', 'flush', 'get', 'get_expire_at_browser_close', 'get_expiry_age', 'get_expiry_date', 'get_model_class', 'has_key', 'is_empty', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'load', 'model', 'modified', 'pop', 'save', 'serializer', 'session_key', 'set_expiry', 'set_test_cookie', 'setdefault', 'test_cookie_worked', 'update', 'values']
    ----session_key--------------
    None
    AnonymousUser
    ----session_key--------------
    1111111111111111111111111
    -------user-------------
    015208
    <class 'django.contrib.auth.models.User'>
    22222222222222222222222
    <WSGIRequest: POST '/main/'>
    ['COOKIES', 'FILES', 'GET', 'META', 'POST', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_body', '_cache_update_cache', '_cached_user', '_encoding', '_files', '_get_post', '_get_raw_host', '_get_scheme', '_initialize_handlers', '_load_post_and_files', '_mark_post_parse_error', '_messages', '_post', '_post_parse_error', '_read_started', '_set_post', '_stream', '_upload_handlers', 'body', 'build_absolute_uri', 'close', 'content_params', 'content_type', 'encoding', 'environ', 'get_full_path', 'get_host', 'get_port', 'get_raw_uri', 'get_signed_cookie', 'is_ajax', 'is_secure', 'method', 'parse_file_upload', 'path', 'path_info', 'read', 'readline', 'readlines', 'resolver_match', 'scheme', 'session', 'upload_handlers', 'user', 'xreadlines']
    <django.contrib.sessions.backends.db.SessionStore object at 0x399ba90>
    ['TEST_COOKIE_NAME', 'TEST_COOKIE_VALUE', '_SessionBase__not_given', '_SessionBase__session_key', '__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_get_new_session_key', '_get_or_create_session_key', '_get_session', '_get_session_key', '_hash', '_session', '_session_cache', '_session_key', '_set_session_key', '_validate_session_key', 'accessed', 'clear', 'clear_expired', 'create', 'create_model_instance', 'cycle_key', 'decode', 'delete', 'delete_test_cookie', 'encode', 'exists', 'flush', 'get', 'get_expire_at_browser_close', 'get_expiry_age', 'get_expiry_date', 'get_model_class', 'has_key', 'is_empty', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'load', 'model', 'modified', 'pop', 'save', 'serializer', 'session_key', 'set_expiry', 'set_test_cookie', 'setdefault', 'test_cookie_worked', 'update', 'values']
    ----session_key--------------
    None
    AnonymousUser
    ----session_key--------------
    22222222222222222222222
    -------user-------------
    33333333333333333
    <WSGIRequest: POST '/main/'>
    ['COOKIES', 'FILES', 'GET', 'META', 'POST', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_body', '_cache_update_cache', '_cached_user', '_encoding', '_files', '_get_post', '_get_raw_host', '_get_scheme', '_initialize_handlers', '_load_post_and_files', '_mark_post_parse_error', '_messages', '_post', '_post_parse_error', '_read_started', '_set_post', '_stream', '_upload_handlers', 'body', 'build_absolute_uri', 'close', 'content_params', 'content_type', 'encoding', 'environ', 'get_full_path', 'get_host', 'get_port', 'get_raw_uri', 'get_signed_cookie', 'is_ajax', 'is_secure', 'method', 'parse_file_upload', 'path', 'path_info', 'read', 'readline', 'readlines', 'resolver_match', 'scheme', 'session', 'upload_handlers', 'user', 'xreadlines']
    <django.contrib.sessions.backends.db.SessionStore object at 0x399ba90>
    ['TEST_COOKIE_NAME', 'TEST_COOKIE_VALUE', '_SessionBase__not_given', '_SessionBase__session_key', '__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_get_new_session_key', '_get_or_create_session_key', '_get_session', '_get_session_key', '_hash', '_session', '_session_cache', '_session_key', '_set_session_key', '_validate_session_key', 'accessed', 'clear', 'clear_expired', 'create', 'create_model_instance', 'cycle_key', 'decode', 'delete', 'delete_test_cookie', 'encode', 'exists', 'flush', 'get', 'get_expire_at_browser_close', 'get_expiry_age', 'get_expiry_date', 'get_model_class', 'has_key', 'is_empty', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'load', 'model', 'modified', 'pop', 'save', 'serializer', 'session_key', 'set_expiry', 'set_test_cookie', 'setdefault', 'test_cookie_worked', 'update', 'values']
    ----session_key--------------
    None
    AnonymousUser
    ----session_key--------------
    33333333333333333333
    4444444444444444
    <WSGIRequest: POST '/main/'>
    ['COOKIES', 'FILES', 'GET', 'META', 'POST', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_body', '_cache_update_cache', '_cached_user', '_encoding', '_files', '_get_post', '_get_raw_host', '_get_scheme', '_initialize_handlers', '_load_post_and_files', '_mark_post_parse_error', '_messages', '_post', '_post_parse_error', '_read_started', '_set_post', '_stream', '_upload_handlers', 'body', 'build_absolute_uri', 'close', 'content_params', 'content_type', 'csrf_cookie_needs_reset', 'encoding', 'environ', 'get_full_path', 'get_host', 'get_port', 'get_raw_uri', 'get_signed_cookie', 'is_ajax', 'is_secure', 'method', 'parse_file_upload', 'path', 'path_info', 'read', 'readline', 'readlines', 'resolver_match', 'scheme', 'session', 'upload_handlers', 'user', 'xreadlines']
    <django.contrib.sessions.backends.db.SessionStore object at 0x399ba90>
    ['TEST_COOKIE_NAME', 'TEST_COOKIE_VALUE', '_SessionBase__not_given', '_SessionBase__session_key', '__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_get_new_session_key', '_get_or_create_session_key', '_get_session', '_get_session_key', '_hash', '_session', '_session_cache', '_session_key', '_set_session_key', '_validate_session_key', 'accessed', 'clear', 'clear_expired', 'create', 'create_model_instance', 'cycle_key', 'decode', 'delete', 'delete_test_cookie', 'encode', 'exists', 'flush', 'get', 'get_expire_at_browser_close', 'get_expiry_age', 'get_expiry_date', 'get_model_class', 'has_key', 'is_empty', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'load', 'model', 'modified', 'pop', 'save', 'serializer', 'session_key', 'set_expiry', 'set_test_cookie', 'setdefault', 'test_cookie_worked', 'update', 'values']
    ----session_key--------------
    pd7xt19xas81z7451b8x9dsj0waptpw3
    015208
    ----session_key--------------
    
    
    这个生成session的逻辑在login方法里:
    
    
    
    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.
        """
    	坚持一个用户id 和一个backend 在一个请求里,这样用户不需要每个请求都重新认证
    	
    	注意 当用户登录时,数据设置在匿名会话是被保持的
    	
    	
    	
        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)
  • 相关阅读:
    kafka学习3——单机伪集群(window版)
    (转)在阿里云 CentOS 服务器(ECS)上搭建 nginx + mysql + php-fpm 环境
    渗透测试工具sqlmap基础教程
    编译安装nginx后service nginx start 启动不了
    centos6.5上tomcat的安装
    centos6.5上安装淘宝tfs系统
    解决nagios登录不了的问题
    centos6.5上网络不通解决方法
    redis远程密码连接
    centos7上定时将mysql数据导出并且发送到指定的邮箱
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13349027.html
Copyright © 2020-2023  润新知