是否可以設置Django API,以便它只響應JSON格式?我在下面的例子中故意犯了一個錯誤來解釋我的意思。我正在嘗試根據REST的假設來創建API。所以我的API只能以JSON響應並返回狀態,或者有時只是返回沒有主體的狀態。或者,也許我錯了?我不想爲HTML等是否可以設置Django API,以便它只響應JSON格式?
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Page not found at /logi3</title>
<meta name="robots" content="NONE,NOARCHIVE">
<style type="text/css">
html * { padding:0; margin:0; }
body * { padding:10px 20px; }
body * * { padding:0; }
body { font:small sans-serif; background:#eee; }
body>div { border-bottom:1px solid #ddd; }
h1 { font-weight:normal; margin-bottom:.4em; }
h1 span { font-size:60%; color:#666; font-weight:normal; }
table { border:none; border-collapse: collapse; width:100%; }
td, th { vertical-align:top; padding:2px 3px; }
th { width:12em; text-align:right; color:#666; padding-right:.5em; }
#info { background:#f6f6f6; }
#info ol { margin: 0.5em 4em; }
#info ol li { font-family: monospace; }
#summary { background: #ffc; }
#explanation { background:#eee; border-bottom: 0px none; }
</style>
</head>
<body>
<div id="summary">
<h1>Page not found
<span>(404)</span>
</h1>
<table class="meta">
<tr>
<th>Request Method:</th>
<td>GET</td>
</tr>
<tr>
<th>Request URL:</th>
<td>http://localhost:8000/logi3</td>
</tr>
</table>
</div>
<div id="info">
<p>
Using the URLconf defined in
<code>myapp.urls</code>,
Django tried these URL patterns, in this order:
</p>
<ol>
<li>
...
views.py
from rest_framework.views import exception_handler
def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)
# Now craft the JSON response
if response is not None:
response.data['status_code'] = response.status_code
response.data['error'] = exc.detail
return response
settings.py:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer'
),
'EXCEPTION_HANDLER': 'DockerProject.project.utils.custom_exception_handler',
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.FormParser',
'rest_framework.parsers.MultiPartParser',
'rest_framework.parsers.JSONParser',
]
}
項目樹:
DockerProject
├── Dockerfile
├── Procfile
├── init.sql
├── requirements.txt
├── docker-compose.yml
└── PROJECT
├── frontend
└── all frontend files
└── backend
└── project
├── prices
├── manage.py
└── project
└── all backend files
發佈您的api視圖 –
我使用裝飾器而不是APIView類定義。 – wahtdbogh