Django:不同URL的不同访问类型

问题描述 投票:0回答:1

在我的Django项目中,我在urls.py文件中定义了我的URL,如下所示:

from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^api/', include('page1.urls')),
    url(r'^api/', include('page2.urls')),
    url(r'^remote/', include('registering.urls')),   
]

使用settings.py文件中的ALLOWED_HOSTS定义,/ remote和/ api都具有相同的类型访问权限,因此,如果ALLOWED_HOSTS为

ALLOWED_HOSTS = ['*']

因此/ api和/ remote URL都可以远程访问。

但是如果ALLOWED_HOSTS为:

ALLOWED_HOSTS = ['localhost'] 

因此/ api和/ remote URL都不能远程访问,只能从localhost访问。

但是我需要的是只能远程访问/ remote URL。并且/ api应该只能从localhost访问,而不能从远程访问。我有实现该目标的想法吗?

python django localhost django-urls remote-access
1个回答
0
投票

您可以考虑在视图上创建一个装饰器,该装饰器将根据主机返回403状态:

from django.core.exceptions import PermissionDenied

def host_check():
    def decorator(func):
        def wrapper(request, *args, **kwargs):
            if request.META['HTTP_HOST'] in settings.YOUR_REMOTE_ALLOWED_HOSTS:
                return func(request, *args, **kwargs)
            raise PermissionDenied()
        return wrapper
     return decorator

并且在您看来:

from django.utils.decorators import method_decorator
from . import 

@method_decorator(host_check, name='dispatch')
class SomeAPIView(APIView):

此外,我确实记得有a module用于此目的,但我不确定它是否仍支持最新的Django版本。

© www.soinside.com 2019 - 2024. All rights reserved.