python - how to setup custom middleware in django -
i trying create middleware optionally pass kwarg every view meets condition.
the problem cannot find example of how setup middleware. have seen classes override method want to, process_view:
class checkconditionmiddleware(object): def process_view(self, request): return none
but put class? create middleware app , put class inside of , reference in settings.middleware ?
first: path structure
if don't have need create middleware folder within app following structure:
yourproject/yourapp/middleware
the folder middleware should placed in same folder settings.py, urls, templates...
important: don't forget create __init__.py empty file inside middleware folder app recognize folder
second: create middleware
now should create file our custom middleware, in example let's supose want middleware filter users based on ip, create file called filter_ip_middleware.py inside middleware folder code:
class filteripmiddleware(object): # check if client ip allowed def process_request(self, request): allowed_ips = ['192.168.1.1', '123.123.123.123', etc...] # authorized ip's ip = request.meta.get('remote_addr') # client ip if ip not in allowed_ips: raise http403 # if user not allowed raise error # if ip allowed don't return none
third: add middleware in our 'settings.py'
we need for:
middleware_classes
(django < 1.10)middleware
(django >= 1.10)
inside settings.py , there need add our middleware (add in last position). should like:
middleware = ( # before django 1.10 setting name 'middleware_classes' 'django.middleware.common.commonmiddleware', 'django.contrib.sessions.middleware.sessionmiddleware', 'django.middleware.csrf.csrfviewmiddleware', 'django.contrib.auth.middleware.authenticationmiddleware', 'django.contrib.messages.middleware.messagemiddleware', # above django standard middlewares # add here our custom middleware 'yourapp.middleware.filter_ip_middleware.filteripmiddleware' )
done ! every request every client call custom middleware , process custom code !
Comments
Post a Comment