我正在使用 Django 构建一个博客,并且我已经实现了一个分析工具,它允许我绘制关于我的访问者的详细信息(国家来源、设备、浏览器......)。
analysis.localhost:8000是localhost的子域,定义为具有自定义 Mixin SuperuserAccessRequired的基于类的视图,如果用户不是员工,则返回401 Unauthorized(我正在使用django-hosts处理子域,这是我第一次使用子域。)。
我的问题:
如果我登录localhost:8000并导航到analysis.localhost:8000我得到401 响应。
You are seeing this as: AnonymousUser # generated by print(You are seeing this as: ', request.user) from SuperuserAccessRequired
Unauthorized: /
[25/Sep/2019 13:14:03] "GET / HTTP/1.1" 401 89
我谦虚的假设说localhost:8000和x.localhost:8000没有共享某些变量。
我该如何解决这个问题,我已经阅读了 5 次 django-hosts 文档,但我似乎找不到我所缺少的
我的代码:
项目/根/settings.py
...
ALLOWED_HOSTS = ['localhost']
ALLOWED_HOSTS += ['analysis.localhost', 'blog.localhost']
SITE_ID = 1
INSTALLED_APPS += [
# Django Apps
'blog',
'analysis',
]
INSTALLED_APPS += [
# Django Dependencies
'sass_processor',
'django_hosts',
]
MIDDLEWARE = [
'django_hosts.middleware.HostsRequestMiddleware',
'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',
'analysis.middleware.TrackVisitorMiddleware',
'django_hosts.middleware.HostsResponseMiddleware',
]
ROOT_URLCONF = 'root.urls'
ROOT_HOSTCONF = 'root.hosts'
BLOG_URLCONF = 'blog.urls'
ANALYSIS_URLCONF = 'analysis.urls'
DEFAULT_HOST = 'www'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'analysis': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'analysis_db.sqlite3'),
}
}
...
项目/根/hosts.py
host_patterns = patterns('',
host(r'localhost:8000', settings.ROOT_URLCONF, name='www'),
host(r'analysis.localhost:8000', settings.ANALYSIS_URLCONF, name='analysis'),
host(r'blog.localhost:8000', settings.BLOG_URLCONF, name='blog'),
)
自定义混音:
class SuperuserAccessRequired(AccessMixin):
"""Verify that the current user is staff."""
def dispatch(self, request, *args, **kwargs):
print('You are seeing this as: ', request.user)
if not request.user.is_staff:
return HttpResponse(status=401, content='You are not authorized to view this page.')
return super().dispatch(request, *args, **kwargs)
更新
如果我从analysis.localhost中删除端口号,我会被重定向到 Apache 默认页面……很奇怪。(只是忽略这个更新,我忘记了 /etc/hosts,伙计,我正在失去它)
更新 2
深入研究这件事,看来我必须重写我的 SessionMiddleware。
任何帮助/指导将不胜感激。