我需要开发Django中间件并创建类似这样的类:
import re
from django.conf import settings
from django.shortcuts import redirect
from django.contrib.auth import logout
class LoginRequiredMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
return response
def process_view(self, request, view_func, view_args, view_kwargs):
assert hasattr(request, 'user')
path = request.path_info
print(path)
p = path.lstrip('/')
compiled_login_url = re.compile(settings.LOGIN_URL)
print(compiled_login_url.match(p))
if not request.user.is_authenticated:
if path == '/':
print("==============> INDEX PAGE")
现在,在这里,我想比较网址的路径。我必须确定路径是否与 settings.LOGIN_URL 匹配。我曾尝试使用正则表达式,但它们没有帮助。
这是我的网址
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name='index'),
path('<slug:slug>/', include('app.urls')),
path('<slug:slug>/accounts/login/', views.login, name='login'),
path('<slug:slug>/accounts/logout/', views.logout, name='logout'),
path('<slug:slug>/dashboard/', 'views.dashboard', name='dashboard'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
我想免除登录和注销并在中间件中进行检查,我也需要子弹。
views.py
def user_login(request, slug):
"""
Login user using email and password
:param request: WSGI Request
:param slug: to verify the facility
:return: login page or redirect
"""
context = {}
try:
facility = models.Facility.objects.get(slug=slug)
context['facility'] = facility
except models.Facility.DoesNotExist:
return redirect('index')
if request.method == "POST":
email = request.POST['email']
password = request.POST['password']
user = authenticate(request, username=email, password=password)
if user is not None:
if user.profile.facility.slug == slug:
login(request, user)
return redirect('dashboard', slug=slug)
else:
context['error'] = "You don't belong to this facility"
else:
context['error'] = "Invalid email or password"
return render(request, 'app/user/login.html', context)
@login_required
def dashboard(request, slug):
"""
Display the dashboard of facility and list down bird
view for the daily, weekly, monthly and yearly progress
:param request:
:return:
"""
context = {}
try:
facility = models.Facility.objects.get(slug=slug)
context['facility'] = facility
except models.Facility.DoesNotExist:
return render(request, 'app/404.html', status=404)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<ul>
{% for f in facilities %}
<li><a href="{% url 'login' f.slug %}">{{ f.name }}</a></li>
{% empty %}
<li>No Facility</li>
{% endfor %}
</ul>
</body>
</html>
答案 0 :(得分:0)
您可以将Django的身份验证视图一个一个地添加到您的urlpatterns
中,并用login_exempt
装饰每个。
如果您希望将检查移入中间件,则可以尝试以下操作:
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("myapp.urls")),
path('accounts/', include('django.contrib.auth.urls', namespace="accounts"))
]
middleware.py
class LoginRequiredMiddleware: # <-- Custom Middleware
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
return self.get_response(request)
def process_view(self, request, view_func, view_args, view_kwargs):
if getattr(view_func, 'login_exempt', False):
return
if 'accounts' in request.resolver_match.namespaces:
return
其他可能性可能是检查中间件中的url或视图名称,但也许最干净的方法是使用装饰器并逐个添加必要的视图。
您可以为此使用django-decorator-include。
$ pip install django-decorator-include
在你project/url.py
from decorator_include import decorator_include
from project/custom_middleware import login_exempt
urlpatterns = [
path('admin/', admin.site.urls),
path('', include("myapp.urls")),
# do this
path('accounts/', decorator_include(login_exempt, 'django.contrib.auth.urls'))
]
不要忘记将软件包添加到requirements.txt