對於想透過DRF來建立RESTfull API的初學者,建立純淨版的項目將有助於了解 DRF 的核心概念,並適合在簡單應用中快速搭建 RESTful API。
相關 settings 設定如下:
INSTALLED_APPS = [
# 'django.contrib.admin',
# 'django.contrib.auth',
# 'django.contrib.contenttypes',
# 'django.contrib.sessions',
# 'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework' # 新增 rest_framework app
]
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',
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
# 'django.contrib.auth.context_processors.auth',
# 'django.contrib.messages.context_processors.messages',],},},]
實際DRF在做頁面展示時,會使用到request.user,而一般請求情況下並不存在此使用者訊息,DRF則會去調用默認匿名使用者,在rest_framework.request.Request內:
def _not_authenticated(self):
self._authenticator = None
if api_settings.UNAUTHENTICATED_USER: # 調用匿名使用者,由於我們剔除了相關app,故讀取會報錯
self.user = api_settings.UNAUTHENTICATED_USER()
else:
self.user = None
if api_settings.UNAUTHENTICATED_TOKEN:
self.auth = api_settings.UNAUTHENTICATED_TOKEN()
else:
self.auth = None
api_settings相當於在settings內調用REST_FRAMEWORK,所以我們僅需要在settings內設定:
REST_FRAMEWORK = {
"UNAUTHENTICATED_USER" : None,
}
即完成純淨版項目設定。