配置django-cors-headers实现跨域请求支持
INSTALLED_APPS = 'corsheaders'
CORS_ORIGIN_ALLOW_ALL = True
# CORS_ORIGIN_WHITELIS = ('www.abc.com')
# get只读
CORS_ORIGIN_METHODS = ('GET','POST','PUT')
ROOT_URLCONF = 'carsearch2.urls'
RESTful
RESTful架构到底解决了什么问题?(URL具有自描述性、资源表述与视图的解耦和、互操作性利用构建微服务以及集成第三方系统、无状态性提高水平扩展能力)
安装djangorestfrmework
pip install djangorestframework
创建 api/
配置drf settings。
INSTALLED_APPS = [
'rest_framework',
]
REST_FRAMEWORK = {
# 配置默认页面大小
'PAGE_SIZE': 10,
# 配置默认的分页类
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
}
编写序列化器
from django.http import JsonResponse
from rest_framework import serializers
from record.models import Car, Record
class CarSerializer(serializers.ModelSerializer):
"""汽车序列化器"""
class Meta:
model = Car
fields = '__all__'
class CarSimpleSerializer(serializers.ModelSerializer):
class Meta:
model = Car
fields = ('carno', 'owner')
class RecordSerializer(serializers.ModelSerializer):
"""违章记录序列化器"""
makedate = serializers.SerializerMethodField()
car = serializers.SerializerMethodField()
@staticmethod
def get_makedate(record):
return record.makedate.strftime('%Y-%m-%d %H:%M')
@staticmethod
def get_car(record):
return CarSimpleSerializer(record.car).data
class Meta:
model = Record
fields = '__all__'
在record/views 中编写主页视图函数
from django.shortcuts import render
def index(request):
"""首页"""
return render(request, 'index.html')
api/views 编写视图函数视图集合
from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from rest_framework.generics import CreateAPIView, ListAPIView, ListCreateAPIView, RetrieveAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.viewsets import ModelViewSet,ReadOnlyModelViewSet
from record.models import Car, Record
from api.serializers import CarSerializer, RecordSerializer
def normalize(carno):
"""规范化车牌号"""
return carno.replace(' ', '').upper()
class DestroryAPIView(object):
pass
自定义视图集合继承APIVIEW类,灵活查多个 GET POST
class CarView(RetrieveAPIView,ListCreateAPIView):
"""汽车视图集合"""
# 获取car所有对象
queryset = Car.objects.all()
# 使用汽车序列化器
serializer_class = CarSerializer
# 分页类
pagination_class = None
定义get查询方法
def get(self, request, *args, **kwargs):
查单个pk参数
if 'pk' in kwargs:
return RetrieveAPIView.get(self, request, *args, **kwargs)
return ListCreateAPIView.get(self, request, *args, **kwargs)
查多个
使用装饰器,修改和查多个record记录
@method_decorator(decorator=cache_page(timeout=300, cache='default'),name='retrieve')
@method_decorator(decorator=cache_page(timeout=300, cache='default'),name='list')
class RecordViewSet(ModelViewSet):
"""违章记录视图集合"""
queryset = Record.objects.all().select_related('car')
serializer_class = RecordSerializer
url中创建router对象,并注册视图集
from django.urls import path
from rest_framework.routers import DefaultRouter
from api.views import CarView, RecordViewSet
car单独映射,int查单个传入pk参数
urlpatterns = [
path('cars/',CarView.as_view()),
path('cars/<int:pk>/',CarView.as_view())
]
注册视图集
router = DefaultRouter()
router.register('records', RecordViewSet)
urlpatterns += router.urls
在carsearch2/urls中映射api/包含api里的urls
映射主页
from django.contrib import admin
from django.urls import path, include
from record import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index),
path('api/',include('api.urls'))
]
编辑工具api/utils 分页器和规范化车牌工具
from rest_framework.pagination import PageNumberPagination
class CustomPagination(PageNumberPagination):
page_size = 5
page_size_query_param = 'size'
max_page_size = 5
def normalize(carno):
"""规范化车牌号"""
return carno.replace(' ', '').upper()
将模型移入api/
通过redis配置缓存
1.打开服务器6379端口
CACHES = {
# 通过django-redis的RedisCache对接Redis提供缓存服务
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
# 缓存服务器的URl
'LOCATION': [
'redis://139.196.79.238:6379/0',
],
'KEY_PREFIX': 'carsearch2',
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
'CONNECTION_POOL_KWARGS': {
'max_connections': 512,
},
'PASSWORD': '1qaz2wsx',
}
},
'session': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': [
'redis://139.196.79.238:6379/1',
],
'KEY_PREFIX': 'carsearch2',
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
'CONNECTION_POOL_KWARGS': {
'max_connections': 512,
},
'PASSWORD': '1qaz2wsx',
}
}
}
# 配置会话的存储引擎(默认是数据库此处将其修改为缓存服务)
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
# 指定使用哪一组缓存服务来保存会话
SESSION_CACHE_ALIAS = 'session'
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
可以通过配置在服务器上的redis 管理缓存