70.django 중간부품

8035 단어
django 중간부품
"""
django    django   
1.                     django  
2.                      

django       
"""
django         

  django       
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

class SessionMiddleware(MiddlewareMixin):
    def process_request(self, request):
        session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME)
        request.session = self.SessionStore(session_key)
    def process_response(self, request, response):
        return response
      
class CsrfViewMiddleware(MiddlewareMixin):
  	def process_request(self, request):
        csrf_token = self._get_token(request)
        if csrf_token is not None:
            # Use same token next time.
            request.META['CSRF_COOKIE'] = csrf_token
    def process_view(self, request, callback, callback_args, callback_kwargs):
        return self._accept(request)

    def process_response(self, request, response):
        return response
      
class AuthenticationMiddleware(MiddlewareMixin):
    def process_request(self, request):
        request.user = SimpleLazyObject(lambda: get_user(request))
"""
django                             
	1.    
		process_request
		
		process_response
	2.    
		process_view
			
		process_template_response
		
		process_exception
"""

어떻게 중간부품을 사용자 정의합니까
"""
1.                      
2.               py  
3.  py        (       MiddlewareMixin)
	                   
	(               ,      )
4.                          
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    '           1',
    '           2',
    '           3',
]

"""
"""
1.    
		process_request 
			1.                   process_request  
			                              
			2.              ,              
			3.        HttpResponse  ,             
			        (         ...)
			process_request                  
			
		process_response
			1.                   process_response  
			           request,response
			2.         HttpResponse  
				1.         response
				2.           
			3.                         
				                   
		
		        process_request        HttpResponse  ,                    process_response       
		     
			          process_reponse  
		
		flask               
			                       process_reponse  
			
			
2.    
		process_view
			                ,              
			                           
			
		process_template_response
			   HttpResponse   render         
			                         
			
		process_exception
			                
			                         
"""
	

csrf 크로스 사이트 위조 요청
"""
    
	                 (    )
	              ,        
	                     ,            
	                                    

       
	               

    
	                            name     input 
	               name value input 

        
	csrf        
		                                    
		          post                  ,            (403 forbbiden)         	
"""

어떻게 검사에 부합합니까
# form        
{% csrf_token %}

username:

target_user:

money:

# ajax // {#data:{"username":'jason','csrfmiddlewaretoken':$('[name=csrfmiddlewaretoken]').val()},#} // {#data:{"username":'jason','csrfmiddlewaretoken':'{{ csrf_token }}'},#} // js html data:{"username":'jason'}
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');


function csrfSafeMethod(method) {
  // these HTTP methods do not require CSRF protection
  return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

$.ajaxSetup({
  beforeSend: function (xhr, settings) {
    if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
      xhr.setRequestHeader("X-CSRFToken", csrftoken);
    }
  }
});

csrf 관련 장식기
"""
1.        csrf,             
2.       csrf,            
"""
from django.views.decorators.csrf import csrf_protect,csrf_exempt
from django.utils.decorators import method_decorator
"""
csrf_protect      
      csrf_protect                 
csrf_exempt       
      csrf_exempt   dispatch      
"""
# @csrf_exempt
# @csrf_protect
def transfer(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        target_user = request.POST.get('target_user')
        money = request.POST.get('money')
        print('%s %s  %s '%(username,target_user,money))
    return render(request,'transfer.html')



from django.views import View

# @method_decorator(csrf_protect,name='post')  #   csrf_protect        
# @method_decorator(csrf_exempt,name='post')  #   csrf_exempt         
@method_decorator(csrf_exempt,name='dispatch')
class MyCsrfToken(View):
    # @method_decorator(csrf_protect)  #   csrf_protect        
    # @method_decorator(csrf_exempt)  #   csrf_exempt        
    def dispatch(self, request, *args, **kwargs):
        return super(MyCsrfToken, self).dispatch(request,*args,**kwargs)

    def get(self,request):
        return HttpResponse('get')

    # @method_decorator(csrf_protect)  #   csrf_protect        
    # @method_decorator(csrf_exempt)  #   csrf_exempt         
    def post(self,request):
        return HttpResponse('post')


보충 지식
#   :importlib
import importlib
res = 'myfile.b'
ret = importlib.import_module(res)  # from myfile import b
#         py   
print(ret)

중요 사상
import settings
import importlib


def send_all(content):
    for path_str in settings.NOTIFY_LIST:  #'notify.email.Email'
        module_path,class_name = path_str.rsplit('.',maxsplit=1)
        # module_path = 'notify.email'  class_name = 'Email'
        # 1          
        module = importlib.import_module(module_path)  # from notify import email
        # 2         
        cls = getattr(module,class_name)  # Email、QQ、Wechat
        # 3       
        obj = cls()
        # 4           send  
        obj.send(content)

좋은 웹페이지 즐겨찾기