1、新建项目
django-admin startproject HelloWorld
2、新建数据库runoob
create database runoob default charset=utf8;
3、修改HelloWorld/HelloWorld/settings.py: 文件代码:
DATABASES = {
'default':
{
'ENGINE': 'django.db.backends.mysql', # 数据库引擎
'NAME': 'runoob', # 数据库名称
'HOST': '127.0.0.1', # 数据库地址,本机 ip 地址 127.0.0.1
'PORT': 3306, # 端口
'USER': 'root', # 数据库用户名
'PASSWORD': '123456', # 数据库密码
}
}
4、在与 settings.py 同级目录下的 __init__.py 中引入模块和进行配置(安装第三方库:pymysql和mysqlclient)
import pymysql
pymysql.install_as_MySQLdb()
5、创建一个 app。我们使用以下命令创建一个 TestModel 的 app:
django-admin startapp TestModel
6、修改 TestModel/models.py 文件
from django.db import models
# Create your models here.
# 书籍表
class BookInfo(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50)
btitle = models.CharField(max_length=50)
bpub_date = models.DateTimeField(auto_now=True)#自动填充当前时间
bread = models.CharField(max_length=50)
bcomment = models.CharField(max_length=50)
?7、在 settings.py 中找到INSTALLED_APPS这一项添加TestModel
?8、创建表结构,插入数据
按正常顺序需要数据迁移,用命令来自动创建表。
python manage.py migrate # 创建表结构
python manage.py makemigrations TestModel # 让 Django 知道我们在我们的模型有一些变更
python manage.py migrate TestModel
?如果数据库中没有自动生成表,就手动创建:
create table testmodel_bookinfo
(
id int primary key,
name varchar(50),
btitle varchar(50),
bpub_date DATETIME,
bread varchar(50),
bcomment varchar(50)
);
?9、修改HelloWorld/HelloWorld/urls.py: 文件代码
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('a/', include('TestModel.urls')),
]
10、修改HelloWorld/TestModel/views.py文件
import json
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
# Create your views here.
from datetime import datetime
from django.views import View
from TestModel.models import BookInfo
class BooksAPIVIew(View):
"""
查询所有图书、增加图书
"""
def get(self, request):
"""
查询所有图书
路由:GET /books/
"""
print(BookInfo.objects.all())
queryset = BookInfo.objects.all()
book_list = []
for book in queryset:
print(book)
book_list.append({
'id': book.id,
'name' : book.name,
'btitle': book.btitle,
'bpub_date': book.bpub_date,
'bread': book.bread,
'bcomment': book.bcomment,
# 'image': book.image.url if book.image else ''
})
return JsonResponse(book_list, safe=False)
def post(self, request):
"""
新增图书
路由:POST /books/
"""
json_bytes = request.body
json_str = json_bytes.decode()
book_dict = json.loads(json_str)
# 此处详细的校验参数省略
book = BookInfo.objects.create(
btitle=book_dict.get('btitle'),
bpub_date=datetime.strptime(book_dict.get('bpub_date'), '%Y-%m-%d').date()
)
return JsonResponse({
'id': book.id,
'name' : book.name,
'btitle': book.btitle,
'bpub_date': book.bpub_date,
'bread': book.bread,
'bcomment': book.bcomment,
'image': book.image.url if book.image else ''
}, status=201)
class BookAPIView(View):
def get(self, request, pk):
"""
获取单个图书信息
路由: GET /books/<pk>/
"""
try:
book = BookInfo.objects.get(pk=pk)
except BookInfo.DoesNotExist:
return HttpResponse(status=404)
return JsonResponse({
'id': book.id,
'name' : book.name,
'btitle': book.btitle,
'bpub_date': book.bpub_date,
'bread': book.bread,
'bcomment': book.bcomment,
'image': book.image.url if book.image else ''
})
def put(self, request, pk):
"""
修改图书信息
路由: PUT /books/<pk>
"""
try:
book = BookInfo.objects.get(pk=pk)
except BookInfo.DoesNotExist:
return HttpResponse(status=404)
json_bytes = request.body
json_str = json_bytes.decode()
book_dict = json.loads(json_str)
# 此处详细的校验参数省略
book.btitle = book_dict.get('btitle')
book.bpub_date = datetime.strptime(book_dict.get('bpub_date'), '%Y-%m-%d').date()
book.save()
return JsonResponse({
'id': book.id,
'name' : book.name,
'btitle': book.btitle,
'bpub_date': book.bpub_date,
'bread': book.bread,
'bcomment': book.bcomment,
'image': book.image.url if book.image else ''
})
def delete(self, request, pk):
"""
删除图书
路由: DELETE /books/<pk>/
"""
try:
book = BookInfo.objects.get(pk=pk)
except BookInfo.DoesNotExist:
return HttpResponse(status=404)
book.delete()
return HttpResponse(status=204)
11、修改HelloWorld/TestModel/urls.py文件
from . import views
from django.urls import re_path
urlpatterns = [
re_path(r'^books/$', views.BooksAPIVIew.as_view()),
re_path(r'^books/(?P<pk>\d+)/$', views.BookAPIView.as_view())
]
12、启动服务
python manage.py runserver 0.0.0.0:8000
13、输入网址:127.0.0.1:8000/a/books/
|