django接收json
时间: 2023-11-08 15:06:58 浏览: 35
在Django中接收JSON数据,可以使用以下步骤:
1. 安装`django-cors-headers`模块。
```python
pip install django-cors-headers
```
2. 在`settings.py`中添加`corsheaders`应用。
```python
INSTALLED_APPS = [
...
'corsheaders',
...
]
```
3. 在`settings.py`中添加中间件。
```python
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
```
4. 在`settings.py`中添加允许跨域访问的域名。
```python
CORS_ORIGIN_WHITELIST = [
'http://localhost:8080',
'http://127.0.0.1:8080',
]
```
5. 在视图函数中使用`json.loads()`方法将JSON数据转换为Python字典。
```python
import json
from django.http import JsonResponse, HttpResponseBadRequest
def my_view(request):
if request.method == 'POST':
try:
data = json.loads(request.body)
except json.JSONDecodeError:
return HttpResponseBadRequest('Invalid JSON data')
# 处理 data
return JsonResponse({'message': 'success'})
else:
return HttpResponseBadRequest('Invalid request method')
```
在以上代码中,`request.body`包含POST请求中的JSON数据。`json.loads()`方法将JSON数据转换为Python字典。如果JSON数据不合法,将返回`HttpResponseBadRequest`错误。处理数据后,使用`JsonResponse`方法返回JSON响应。