DRF环境搭建及入门
程序员文章站
2022-07-12 11:18:49
...
环境搭建
环境安装
- pip install djangorestframework
- pip install markdown // 用于支持生成浏览器可显示的API文档
- pip install django-filter // 用于支持rest中的过滤器
- pip install django-rest-swagger //swagger接口测试界面
- pip install django-cors-headers //跨域
- pip install djangorestframework-jwt //jwttoken认证
项目搭建
一、创建项目
创建项目名为InterfaceDevelop,创建app叫做DemoApp
django-admin startproject InterfaceDevelop
cd .\InterfaceDevelop\
InterfaceDevelop> python manage.py startapp DemoApp
InterfaceDevelop>
二、同步数据库
- makemigration
- migrate
- createsuperuser
三、配置
settings.py
# 1
ALLOWED_HOSTS = ['*']
# 2
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
# 3
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 3
'rest_framework',
'rest_framework_swagger',
'django_filters',
'corsheaders',
'rest_framework.authtoken',
# 3!
# 10
'DemoApp'
# 10!
]
# 4
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
# 4
'corsheaders.middleware.CorsMiddleware',
# 4!
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
# 5
REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': (
'rest_framework.parsers.JSONParser',
'rest_framework.parsers.MultiPartParser',
),
'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',),
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 20,
# 'GLOBAL_CSRF_CHECK':False
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
),
# 新版的restframework需要指定默认schema
'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema'
}
# 5!
# 6
SWAGGER_SETTINGS = {
'SECURITY_DEFINITIONS': {
'basic': {
'type': 'basic'
}
},
'JSON_EDITOR' : False,
'LOGIN_URL' : 'rest_framework:login',
'LOGOUT_URL': 'rest_framework:logout',
'SHOW_REQUEST_HEADERS':True,
# 'OPERATIONS_SORTER':'alpah',
# 'APIS_SORTER':'alpah',
'VALIDATOR_URL':None,
}
# 6!
# 7
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
)
CORS_ALLOW_HEADERS = (
'XMLHttpRequest',
'X_FILENAME',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
'Pragma',
)
# 7!
# 8
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
# 8!
# 9
import sys
sys.path.insert(0,os.path.join(BASE_DIR, 'apps'))
# 9!
urls.py(demoapp模块)
# 11
from django.conf.urls import url,include
from . import views
app_name = 'demo_app'
urlpatterns = [
url(r'^index/', views.index, name='index'),
# 17
url(r'^index_class/', views.IndexClass.as_view(), name='index_class'),
# 17!
]
# 11!
views.py
# 12
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import authentication, permissions
from django.contrib.auth.models import User
from django.http import HttpResponse
from rest_framework.decorators import api_view,schema
from rest_framework.response import Response
from rest_framework import status
from rest_framework import mixins
from rest_framework import generics
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from rest_framework.parsers import MultiPartParser
from django.shortcuts import get_object_or_404
from django.contrib.auth.models import Group,Permission
# 12!
# 13
def index(request):
return HttpResponse('test index api')
# 13!
# 16
class IndexClass(APIView):
def post(self, *args, **kwargs):
return Response(data={'code':'200'},status=status.HTTP_200_OK)
# 16!
urls.py(总)
# 14
#from django.conf.urls import url
from django.conf.urls import url,include
from django.contrib import admin
import rest_framework.authtoken.views
from rest_framework.documentation import include_docs_urls
from rest_framework_jwt.views import obtain_jwt_token
from django.conf.urls.static import static
from django.conf import settings
from rest_framework_swagger.views import get_swagger_view
schema_view = get_swagger_view(title='InterfaceDevelop API')
# 14!
urlpatterns = [
url(r'^admin/', admin.site.urls),
# 15
url(r'^api_auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^api_token_auth/', obtain_jwt_token),
url(r'^api/', schema_view),
url(r'^demo_app/', include('DemoApp.urls', namespace='demo_app')),
# 15!
]
四、编写视图
在goods目录下views.py,写入一下内容:
from django.shortcuts import render
from django.views.generic.base import View
from django.views.generic import ListView
from .models import *
from django.http import HttpResponse
import json
# Create your views here.
def get(self,request):
# goods = GoodsType.objects.values()
goods = Goods.objects.values()
for good in goods:
good['created_time'] = str(good['created_time'])
print(list(goods))
# return HttpResponse(json.dumps(list(goods)),content_type='application/json')
return JsonResponse(list(goods),safe=False)
五、配置路由
在goods下的urls.py当中
from django.urls import path
from .views import *
app_name = '[goods_app]'
urlpatterns = [
path(r'list/', GoodsListView.as_view(), name='list'),
]
项目层级划分
- 序列化
- 请求和响应
- 基于类的视图
- 身份验证和权限控制
- 关联和超链接
- 视图集和路由
- schema参数和表单