练习04

Posted mcoming

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了练习04相关的知识,希望对你有一定的参考价值。

  • 要求

    1. 完成汽车系统表模型的建立(表关系自己设计)
      汽车表、汽车商家表、赞助商表、赞助商详情表

    2. 完成汽车系统的接口编写
      汽车表:八大接口(不需要写put方法)
      汽车商家表:八大接口(不需要写put方法)

# urls文件

from django.conf.urls import url
from api import views


urlpatterns = [

    url(r'^books/',views.Books.as_view() ),
    url(r'^books/(?P<pk>)d+/',views.Books.as_view() ),

]




# settings文件

"""
Django settings for DrfProj02 project.

Generated by 'django-admin startproject' using Django 1.11.1.

For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'wdc+_*dbw#5@wt%3c$%c-2wi2$3*jyb7go^)=vbr1))06*ja9m'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'api.apps.ApiConfig',
    'rest_framework'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'DrfProj02.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'DrfProj02.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'drf_test02',
        'USER':'root',
        'PASSWORD':'123',
    }
}

import pymysql

pymysql.install_as_MySQLdb()


# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, javascript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'

MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR,'media')


BASE_URL = 'http://127.0.0.1:8000'

REST_FRAMEWORK = {

    'EXCEPTION_HANDLER':'api.exception.exception_handler'
}



# 自定义的异常模块

from rest_framework.views import exception_handler as Myexception_handler
from rest_framework.response import Response
from rest_framework import status

def exception_handler(exc,context):

    response = Myexception_handler(exc,context)

    detail = f'{context.get("view")}-----{context.get("request")}-----{exc}'

    if not response:

        response = Response(
            data={ 'detail':detail,},
            status = status.HTTP_500_INTERNAL_SERVER_ERROR
        )

    else:
        # 将前端的异常信息也保存在detail中,
        response.data = {'detail':detail}

    # 这里最后将所有异常信息记录到日志中 (代码暂无)


    # 将响应返回给前端
    return response




# models文件

from django.db import models

# Create your models here.

# *************************************************
class Base(models.Model):

    is_delete = models.BooleanField(default=False)
    create_time = models.DateTimeField(auto_now_add=True)

    # 将Base类变成基类
    class Meta:
        abstract = True


class Book(Base):

    name = models.CharField(max_length=64)
    price = models.CharField(max_length=64)
    publish = models.ForeignKey(to='Publish',db_constraint=False,related_name='BookToPublish',on_delete= models.DO_NOTHING)
    authors = models.ManyToManyField(to='Author',related_name='AuthorToBook',through='AuthorBook',through_fields=('books','author'))

    @property
    def publish_info(self):

        publish_name = self.publish.name
        publish_addr = self.publish.addr


        return {'name':publish_name,'addr':publish_addr}

    @property
    def author_list(self):
        author_list_tmp = []

        authors = self.authors.all()

        for author in authors:

            author_dic = {
                'name':author.name
            }

            try:  # 有作者详情才展示详情

                author_dic['phone'] = author.AuthorToDetail.phone

            except:
                author_dic['phone'] = '无'

            author_list_tmp.append(author_dic)

        return author_list_tmp




class Publish(Base):

    name = models.CharField(max_length=64)
    addr = models.CharField(max_length=64)

class Author(Base):

    name = models.CharField(max_length=64)


class AuthorBook(models.Model):

    books = models.ForeignKey(to="Books",db_constraint=False)
    author = models.ForeignKey(to='Author',db_constraint=False)

class AuthorDetail(models.Model):

    phone = models.IntegerField(max_length=64)
    email = models.EmailField()
    author = models.OneToOneField(to='Author',db_constraint=False,related_name='AuthorToDetail',on_delete=models.CASCADE)

    
    
# 自定义的序列化模块



from rest_framework import serializers
from api import models

class BookListSer(serializers.ListSerializer):

    # 重写群改方法
    def update(self, instance_list, validated_data_list):


        return [self.child.update(instance_list[index],instance ) for index,instance in enumerate(validated_data_list)]



class BookModelSer(serializers.ModelSerializer):


    class Meta:

        list_serializer_class = BookListSer
        model = models.Book
        fields = ('name','price','publish','authors','publis_info','author_list')

        extra_kwargs = {
            'publish': {'write_only':True},
            'authors': {'write_only':True}
        }


    def validate(self, attrs):
        print('这全局钩子')
        return attrs
    
    
    
    
    
# views文件


from django.shortcuts import render
from rest_framework import views
from rest_framework.response import Response
from api import Myserializers
# Create your views here.

class Books(views.APIView):

    def get(self,request,*args,**kwargs):

        return Response(
            data={'msg':'get_ok'}
        )


    def post(self,request,*args,**kwargs):
        return Response(
            data={'msg': 'post_ok'}
        )

    def put(self,request,*args,**kwargs):
        return Response(
            data={'msg': 'update_put_ok'}
        )

    def patch(self,request,*args,**kwargs):
        return Response(
            data={'msg': 'update_patch_ok'}
        )

    def delete(self,request,*args,**kwargs):


        return Response(
            data={'msg': 'delete_ok'}
        )

以上是关于练习04的主要内容,如果未能解决你的问题,请参考以下文章

spring练习,在Eclipse搭建的Spring开发环境中,使用set注入方式,实现对象的依赖关系,通过ClassPathXmlApplicationContext实体类获取Bean对象(代码片段

Python练习册 第 0013 题: 用 Python 写一个爬图片的程序,爬 这个链接里的日本妹子图片 :-),(http://tieba.baidu.com/p/2166231880)(代码片段

csharp Epicor标准练习片段

golang 去练习片段

片段着色器中的OpenGL点精灵旋转

从 ListView 开始活动,然后是下一个活动