Django REST framework后端项目部分代码

项目settings

"""
Django settings for BannerInterview project.

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

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 = 'a3d=!trfv(19uu84a_g39jf64x02(e%j@)%=j3pvtf^_=t2pg5'

# 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',
    'rest_framework',
    'apps.user.apps.UserConfig',
    'apps.questionbanks',
    'apps.exam'
]

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 = 'BannerInterview.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 = 'BannerInterview.wsgi.application'

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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'interview',
        'USER': 'Interview',
        'PASSWORD': 'NzE2NybAFCGdmAmX',
        'HOST': '47.94.80.181',
        'PORT': '3306',
        'CHARSET': 'utf-8',
    }

}

# 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 = 'UTC'

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/'
STATICFILES_DIRS = [os.path.join(BASE_DIR,'static')]

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.163.com'                      #发送邮件的邮箱 的 SMTP服务器,这里用了163邮箱
EMAIL_PORT = 25                                  #发件箱的SMTP服务器端口
EMAIL_HOST_USER = 'carinoliu@163.com'            #发送邮件的邮箱地址
EMAIL_HOST_PASSWORD = 'CETHOIPENJUBQCPI'         #发送邮件的邮箱密码(这里使用的是授权码)
EMAIL_FROM = 'BannerStudio<carinoliu@163.com>'


ESSION_ENGINE = 'django.contrib.sessions.backends.cache'  # 引擎,用于简单的缓存会话存储
SESSION_CACHE_ALIAS = 'default'                            # 使用的缓存别名(默认内存缓存,也可以是memcache),此处别名依赖缓存的设置


SESSION_COOKIE_NAME = "sessionid"                        # Session的cookie保存在浏览器上时的key,即:sessionid=随机字符串
SESSION_COOKIE_PATH = "/"                                # Session的cookie保存的路径
SESSION_COOKIE_DOMAIN = None                              # Session的cookie保存的域名
SESSION_COOKIE_SECURE = False                             # 是否Https传输cookie
SESSION_COOKIE_HTTPONLY = True                            # 是否Session的cookie只支持http传输
SESSION_COOKIE_AGE = 1209600                              # Session的cookie失效日期(2周)
SESSION_EXPIRE_AT_BROWSER_CLOSE = True                   # 是否关闭浏览器使得Session过期
SESSION_SAVE_EVERY_REQUEST = False                        # 是否每次请求都保存Session,默认修改之后才保存


项目urls


from django.conf.urls import url, include

urlpatterns = [
    # url(r'^admin/', admin.site.urls),
    url(r'users/', include('apps.user.urls')),
    url(r'questionbanks/', include('apps.questionbanks.urls')),
    url(r'exam/', include('apps.exam.urls'))

]

题库模块:

models

from django.db import models


class QuestionBanks(models.Model):
    """题库模型类"""
    question_id = models.AutoField(primary_key=True, blank=True)
    question_type = models.CharField(verbose_name='试题类型', max_length=16, blank=True)
    question_title = models.CharField(verbose_name='试题标题', max_length=128, unique=True, blank=True)
    question_content = models.TextField(verbose_name='试题内容', blank=True)
    question_score = models.IntegerField(verbose_name='试题分值', blank=True)
    question_answer = models.TextField(verbose_name='试题答案', blank=True)
    question_insert_time = models.DateTimeField(verbose_name='试题添加时间', blank=True)
    question_update_time = models.DateTimeField(verbose_name='试题修改时间', blank=True)

serlalizer

# 序列化器
from rest_framework import serializers
from .models import QuestionBanks


class QuestionSerializer(serializers.ModelSerializer):
    """试题详细信息序列化器"""

    class Meta:
        model = QuestionBanks
        fields = (
            'question_id', 'question_type', 'question_title', 'question_content', 'question_score', 'question_answer',
            'question_insert_time', 'question_update_time')

urls

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

from apps.questionbanks import views
from rest_framework.views import APIView

urlpatterns = [
    url(r'insert/', views.QuestionSingleAPIView().post),
    url(r'selectall/', views.QuestionAPIView().get),
    url(r'update/(?P<pk>\d+)/', views.QuestionSingleAPIView().put),
    url(r'selectbyid/(?P<pk>\d+)/', views.QuestionSingleAPIView().get_byid),
    url(r'delete/(?P<pk>\d+)/', views.QuestionSingleAPIView().delete),
    url(r'deleteall/', views.QuestionAPIView().delete),
    url(r'selectbytype/(?P<pk>\w+)/', views.QuestionAPIView().get_bytype),
    url(r'selectbyscore/(?P<pk>\d+)/', views.QuestionAPIView().get_byscore),
    url(r'getquestion/', views.QuestionAPIView().get_question)
]

views

import random

from django.views import View

from apps.questionbanks.Serializer import QuestionSerializer
from rest_framework.views import APIView
from rest_framework.viewsets import ViewSet

from .models import QuestionBanks
from django.http import JsonResponse, HttpResponse, QueryDict


class QuestionAPIView(APIView):

    # 查询全部试题
    def get(self, request):
        try:
            questions = QuestionBanks.objects.all()
            if questions.exists() == False :
                return JsonResponse({'msg': '无数据'}, safe=False, status=400)
            ser = QuestionSerializer(questions, many=True)
            print(ser)
            return JsonResponse(ser.data, safe=False, status=200)
        except:
            return JsonResponse({'msg': '查询失败,未找到试题'}, status=401)

        # 查询指定试题类型的试题

    def get_bytype(self, request, pk):
        print(pk)
        try:
            questions = QuestionBanks.objects.filter(question_type__exact=pk)
            if (questions.exists()):
                ser = QuestionSerializer(questions, many=True)
                return JsonResponse(ser.data, safe=False, status=200)
            else:
                return JsonResponse({'msg': '查询失败,您的输入有误'}, status=400)

        except:
            return JsonResponse({'msg': '查询失败,未找到该试题'}, status=401)

    def get_byscore(self, request, pk):
        print(pk)
        try:
            questions = QuestionBanks.objects.filter(question_score__exact=pk)
            if (questions.exists()):
                ser = QuestionSerializer(questions, many=True)
                return JsonResponse(ser.data, safe=False, status=200)
            else:
                return JsonResponse({'msg': '查询失败,您的输入有误'}, status=400)

        except:
            return JsonResponse({'msg': '查询失败,未找到该试题'}, status=401)

    # 删除全部试题
    def delete(self, request):
        try:
            QuestionBanks.objects.all().delete()
            return JsonResponse({'msg': '删除成功'}, status=200)
        except:
            return JsonResponse({'msg': '删除失败,未找到试题'}, status=400)

    # 出题
    def get_question(self, request):
        try:
            questions = []
            sum = 0
            size = QuestionBanks.objects.all().count()
            print(size)
            while sum != 100:
                sum = 0
                questions = []
                index = random.sample(range(1, size + 1), 6)
                print(index)
                for i in index:
                    question = QuestionBanks.objects.get(question_id=i)
                    score = question.question_score
                    sum = sum + score
                    questions.append(question)
            ser = QuestionSerializer(questions, many=True)
            return JsonResponse(ser.data, safe=False, status=200)
        except:
            return JsonResponse({'msg': '题库错误---'}, status=401)


class QuestionSingleAPIView(APIView):
    # 添加试题
    def post(self, request):
        try:
            data = request.GET
            questions = QuestionSerializer(data=data)
            print(questions)
            if questions.is_valid():
                questions.save()
                return JsonResponse({'msg': '添加成功'}, status=200)
            else:
                return JsonResponse({'msg': '添加失败,您的输入不合理'}, status=401)
        except:
            return JsonResponse({'msg': '添加失败,您的输入不合理'}, status=400)

    # 修改指定试题内容
    def put(self, request, pk):
        data = request.GET
        try:
            question = QuestionBanks.objects.get(question_id=pk)
            questions = QuestionSerializer(instance=question, data=data)
            print(questions)
            if questions.is_valid():
                questions.save()
                return JsonResponse({'msg': '修改成功'}, status=200)
            else:
                return JsonResponse({'msg': '修改失败,您的输入不合理'}, status=401)
        except:
            return JsonResponse({'msg': '修改失败,未查询到该试题'}, status=400)

    # 查询指定id试题
    def get_byid(self, request, pk):
        print(pk)
        try:
            questions = QuestionBanks.objects.get(question_id=pk)
            ser = QuestionSerializer(questions)
            print(ser)
            return JsonResponse(ser.data, safe=False, status=200)
        except:
            return JsonResponse({'msg': '查询失败,未找到该试题'}, status=401)

    # 删除指定试题
    def delete(self, request, pk):
        print(pk)
        try:
            QuestionBanks.objects.get(question_id=pk).delete()
            return JsonResponse({'msg': '删除成功'}, status=200)
        except:
            return JsonResponse({'msg': '删除失败,未找到该试题'}, status=400)

考试模块:

models

from django.db import models


# Create your models here.
class Exam(models.Model):
    """考试模型类"""
    user_id = models.IntegerField(primary_key=True, blank=True, verbose_name='用户id')
    written_score = models.IntegerField(verbose_name='笔试成绩', blank=True, null=True)
    resume_score = models.IntegerField(verbose_name='简历成绩', blank=True, null=True)
    interview_score = models.IntegerField(verbose_name='面试成绩', blank=True, null=True)
    summary_score = models.IntegerField(verbose_name='综合成绩', blank=True, null=True)

Serializer

# 序列化器
from rest_framework import serializers

from apps.exam.models import Exam


class ExamSerializer(serializers.ModelSerializer):
    """试题详细信息序列化器"""

    class Meta:
        model = Exam
        fields = ('user_id', 'written_score', 'resume_score', 'interview_score', 'summary_score')

urls

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

from apps.exam import views

urlpatterns = [
    url(r'insert/', views.ExamSingleAPIView().post),
    url(r'selectbyid/(?P<pk>\d+)/', views.ExamSingleAPIView().get_byid),
    url(r'delete/(?P<pk>\d+)/', views.ExamSingleAPIView().delete),
    url(r'update/(?P<pk>\d+)/', views.ExamSingleAPIView().update),
    url(r'selectall/', views.ExamAPIView().get),
    url(r'deleteall/',views.ExamAPIView().delete),
    url(r'selectqualified/', views.ExamAPIView().select)

views

from django.db.models import QuerySet
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from rest_framework.views import APIView

from apps.exam.Serializer import ExamSerializer
from apps.exam.models import Exam


class ExamSingleAPIView(APIView):
    # 添加成绩信息
    def post(self, request):
        try:
            data = request.GET
            exam = ExamSerializer(data=data)
            print(exam)
            if exam.is_valid():
                exam.save()
                return JsonResponse({'msg': '添加成功'}, status=200)
            else:
                return JsonResponse({'msg': '添加失败,您的输入不合理'}, status=401)
        except:
            return JsonResponse({'msg': '添加失败,您的输入不合理'}, status=400)

    # 查询成绩信息
    def get_byid(self, request, pk):
        print(pk)
        try:
            exams = Exam.objects.get(user_id=pk)
            exam = ExamSerializer(exams)
            print(exam)
            return JsonResponse(exam.data, safe=False, status=200)
        except:
            return JsonResponse({'msg': '查询失败,未找到信息'}, status=401)

    # 删除成绩信息
    def delete(self, request, pk):
        print(pk)
        try:
            Exam.objects.get(user_id=pk).delete()
            return JsonResponse({'msg': '删除成功'}, status=200)
        except:
            return JsonResponse({'msg': '删除失败,未找到该试题'}, status=400)

    # 修改成绩信息
    def update(self, request, pk):
        print(pk)
        data = request.GET
        try:
            exams = Exam.objects.get(user_id=pk)
            exam = ExamSerializer(instance=exams, data=data)
            if exam.is_valid():
                exam.save()
                return JsonResponse({'msg': '修改成功'}, status=200)
            else:
                return JsonResponse({'msg': '修改失败,您输入的信息有误'}, status=400)
        except:
            return JsonResponse({'msg': '修改失败,未查询到信息'}, status=401)


class ExamAPIView(APIView):
    # 查询全部试题
    def get(self, request):
        try:
            exam = Exam.objects.all()
            if exam.exists() == False :
                return JsonResponse({'msg': '无数据'}, safe=False, status=400)
            exams = ExamSerializer(exam, many=True)
            print(exams)
            return JsonResponse(exams.data, safe=False, status=200)
        except:
            return JsonResponse({'msg': '查询失败'}, safe=False, status=200)

    # 删除全部试题

    def delete(self, request):
        try:
            Exam.objects.all().delete()
            return JsonResponse({'msg': '删除成功'}, status=200)
        except:
            return JsonResponse({'msg': '删除失败'}, status=401)

    def select(self, request):
        try:
            exams = Exam.objects.filter(summary_score__gte=60)
            if exams.exists():
                exam = ExamSerializer(exams, many=True)
                return JsonResponse(exam.data, safe=False, status=200)
            else:
                return JsonResponse({'msg': '查询失败'}, safe=False, status=400)
        except:
            return JsonResponse({'msg': '查询失败'}, safe=False, status=401)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hyk今天写算法了吗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值