最近想学python,基础知识大体过了一遍之后,想搭个web框架,既可以练练手,也想着搭起来之后以后可以方便用。
django比较简单,大而全,他的ORM做的很棒,但总感觉灵活些差一些,废话不多说,开始上程序。
django rest framework,前后端分离。
先是项目图:
首先是setting文件
"""
Django settings for myDjango project.
Generated by 'django-admin startproject' using Django 2.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/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/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '1r75z1-ws6o=a#mqwml3prdu*+gl379q)^)5r+1q3z$36%z'
# 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',
'web',
'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',
'web.SimpleMiddleware.SimpleMiddleware',
]
ROOT_URLCONF = 'myDjango.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 = 'myDjango.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test',
'HOST': 'localhost',
'PORT': '3306',
'USER': 'root',
'PASSWORD': 'root'
}
}
# Password validation
# https://docs.djangoproject.com/en/2.1/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/2.1/topics/i18n/
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = False
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS=(
os.path.join(BASE_DIR,'static'),
)
修改了数据库,添加了名字为web项目,添加了rest framework,修改了时区,添加了静态文件。
这个倒是没什么,网上有很多,都可以查的到。
然后是models.py
import datetime
from django.db import models
# Create your models here.
class User(models.Model):
username = models.CharField(max_length=120,null=False);
password = models.CharField(max_length=120,null=False);
name = models.CharField(max_length=50,default=username);
class BookInfo(models.Model):
title = models.CharField(max_length=50,null=False);
author = models.CharField(max_length=50);
money = models.CharField(max_length=50);
#在django2.0后,定义外键和一对一关系的时候需要加on_delete选项,此参数为了避免两个表里的数据不一致问题,不然会报错
owner = models.ForeignKey(User,on_delete=models.CASCADE);
def __str__(self):
return 'title:'+self.title+' author:'+self.author + ' money:'+self.money;
class comment(models.Model):
content = models.CharField(max_length=512);
#存在时区问题,将setting中的USE_TZ = True设置为False
time = models.CharField(max_length=512);
他和数据表是有关联的,建完之后,setting之后,记得在命令行python manage.py makemigrations,和python manage.py migrate,在之后修改这个文件也要在进行这两个操作。
关于django rest framework网上有很多的文档,写的也挺容易看懂,根据网上的文档一步一步敲一遍就可以对他大体有个了解,当然,选择怎么使用还是要看个人,并不一定千篇一律。
http://www.comingnext.cn/category/2/ 他的阅读环境蛮好的,前端写的淡雅整洁,让人读者挺舒服,推荐。
下面使用@api_view的view.py
from datashape import json
from django.http import JsonResponse
from django.shortcuts import render, render_to_response
# Create your views here.
from django.views.decorators.csrf import csrf_exempt
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.status import *
from web.models import User, BookInfo, comment
from web.permissions import IsOwnerOrReadOnly
from web.serializer import UserSerializer, BookSerializer, CommentSerializer
"""
配置拦截器,直接跳到信息展示页面
游客在展示界面可以随意评论,评论暂时不与书籍绑定在一起
用户登录,老用户可以展示个人书籍信息,可以增加书的信息,暂时不加更新书的功能
"""
'''
可以用类,也可以用方法
用方法更灵活,用类结构更好一些,个人感觉
功能比较简单所以用方法写,类的写法也会写一个用例并且会完成测试
'''
def toIndex(request,format = None):
return render_to_response('index.html');
@api_view(['GET','POST'])
def AllInfo(request,format = None):
user = User.objects.all();
userSerializer = UserSerializer(user,many=True);
com = comment.objects.all();
comSerializer = CommentSerializer(com,many=True);
result = {"comment":comSerializer.data,"user":userSerializer.data};
return Response(result,status=HTTP_200_OK);
@api_view(['GET','POST'])
def UserLogin(request,format=None):
'''
登录成功将显示登录者的书籍
:param request:
:param format:
:return: JSON
'''
try:
data = request.data;
username = data.get('username');
password = data.get('password');
user = User.objects.get(username__exact=username);
if user.password == password:
books = BookInfo.objects.filter(owner=user).all();
bookSerializer = BookSerializer(books, many=True);
# 用户登录保存
request.session['username'] = username;
return Response(bookSerializer.data, status=HTTP_200_OK);
else:
return Response('password error', status=HTTP_400_BAD_REQUEST);
#
except:
return Response('username is null',status=HTTP_400_BAD_REQUEST);
def toLogin(request):
return render_to_response('login.html');
@api_view(['POST'])
def UserRegister(request):
'''
接受用户信息,检验是否已经注册,然后返回信息,这里不做过多检测
:param request:
:return:
'''
data = request.data;
username = data.get('username');
if User.objects.filter(username__exact=username):
return Response('用户已经存在',HTTP_400_BAD_REQUEST);
serializer = UserSerializer(data=data);
#异常处理
if serializer.is_valid(raise_exception=True):
serializer.save();
return Response(serializer.data,status=HTTP_200_OK);
return Response(serializer.errors,status=HTTP_400_BAD_REQUEST);
@api_view(['GET'],['POST'])
def UserBook(request):
'''
查看自己的信息,返回用户信息和书的信息
:param request:
:return:
'''
permission_classes = (IsOwnerOrReadOnly);
#首先检验用户权限
data = request.data;
username = data.get('username');
if username != request.session.get('username'):
return Response('无权查看',status=HTTP_400_BAD_REQUEST);
books = BookInfo.objects.filter(owner__username__exact=username).all();
serializer = BookSerializer(books,many=True);
return Response(serializer.data,status=HTTP_200_OK);
@api_view(['GET','POST'])
def addBookInfo(request):
'''
验证用户是否登录,然后保存数据信息
:param request:
:return:
'''
data = request.data;
username = request.session.get('username');
if username is not None:
serializer = BookSerializer(data=data);
if serializer.is_valid():
serializer.save(owner=User.objects.get(username__exact=username));
return Response('success',HTTP_200_OK);
#重定向到登录页面
return Response('fail',HTTP_200_OK);
@api_view(['GET','POST'])
def addComment(request):
'''
不需要任何验证可以直接保存
:param request:
:return:
'''
comment_data = request.data;
serializer = CommentSerializer(data=comment_data);
print(serializer);
if serializer.is_valid():
serializer.save();
return Response(serializer.data,HTTP_200_OK);
return Response("faile",HTTP_200_OK);
关于项目中的拦截器和序列化等等的内容就不再一一晒了。
资源地址:
https://download.csdn.net/download/qq_25831381/10641994