其他分享
首页 > 其他分享> > 练习01

练习01

作者:互联网

作业

# 1. 配置文件中注册跨域和api
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # 先第三方,再自定义
    'corsheaders',  # 第三方
    'api',  # 自定义
]

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_HEADERS = [  # 允许通过的请求头部
    "accept",
    "accept-encoding",
    "authorization",
    "content-type",
    "dnt",
    "origin",
    "user-agent",
    "x-csrftoken",
    "x-requested-with",

    "token",
    "owen",
]



# 2. 总路由中********************************
# 使用路由分发

from django.conf.urls import url, include
from django.contrib import admin

# from app import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    # 路由分发
    url(r'^api/', include('api.urls')),
]


# 3. api文件夹的urls文件中********************************

from django.conf.urls import url

from . import views
urlpatterns = [
    # http://127.0.0.1:8000/api/books/ 
    # http://127.0.0.1:8000/api/books/(pk)/  
    url(r'^books/$', views.BookView.as_view()),
    url(r'^books/(?P<pk>\d+)/$', views.BookView.as_view())
]



# 4. views文件中****************************

from django.http import JsonResponse
from django.views import View

# 一个视图类可以包括常规五个请求方法:get|post|put|patch|delete
# 五个请求方法处理十个资源操作的逻辑:单群查|单群增|单群整体改|单群局部改|单群删
class BookView(View):
    def get(self, request, *args, **kwargs):
        return JsonResponse({
            'status': 0,
            'msg': 'get ok'
        })

    def post(self, request, *args, **kwargs):
        return JsonResponse({
            'status': 0,
            'msg': 'post ok'
        })

    def put(self, request, *args, **kwargs):
        return JsonResponse({
            'status': 0,
            'msg': 'put ok'
        })

    def patch(self, request, *args, **kwargs):
        return JsonResponse({
            'status': 0,
            'msg': 'patch ok'
        })

    def delete(self, request, *args, **kwargs):
        return JsonResponse({
            'status': 0,
            'msg': 'delete ok'
        })

标签:01,views,练习,django,api,JsonResponse,contrib,import
来源: https://www.cnblogs.com/Mcoming/p/12103843.html