创建django项目
(my_django) XXX:~ XXX$ django-admin startproject book_manage
数据库创建和连接
mysql> CREATE DATABASE databaseName CHARACTER SET utf8;
Query OK, 1 row affected (0.01 sec)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'databaseName',
'USER': '...',
'PASSWORD': '...',
'HOST': '127.0.0.1',
}
}
(my_django) XXX:book_manage$ python manage.py migrate
可通过在mysql中查看数据库情况来判断是否已迁移成功。
创建 Django APP
创建django APP用于定义各个模块类
(my_django) XXX:~ XXX$ cd book_manage
(my_django) XXX:book_manage$ python manage.py startapp backend
并把backend加入到./book_manage/settings.py文件中的installed_apps列表里:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'backend'
]
后端搭建
在django APP文件夹下主要会使用到的文件有 model.py 和 view.py。这两个文件分别作为模型层和视图层。
模型层model.py
该文件主要用于定义各个类,也就是用于创建数据表格的structure
视图层view.py
该文件主要用于定义一些接口,也就是对数据表格的操作。 e.g. 定义一个根据id号删除该id的书本接口
@require_http_methods(["GET"])
def delete_book(request):
response = {}
try:
book = Book.objects.filter(id=request.GET.get('id'))
book.delete()
response['msg'] = 'success'
response['error_num'] = 0
except Exception as e:
response['msg'] = str(e)
response['error_num'] = 1
return JsonResponse(response)
路由配置
- 首先在backend下新建一个urls.py用于配制当前APP下的所有路由信息。
from django.urls import path, include
from .views import *
urlpatterns = [
path(r"delete_book/", delete_book, ),
]
- 接着在主Django项目下的urls.py进行接口路由配置
from django.contrib import admin
from django.urls import path,include
import backend.urls
urlpatterns = [
path('admin/', admin.site.urls),
path('backend/',include(backend.urls))
]
数据迁移
(my_django) XXX:book_manage XXX$ python manage.py makemigrations backend
Migrations for 'backend':
backend/migrations/0001_initial.py
- Create model Book
(my_django) XXX:book_manage XXX$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, backend, contenttypes, sessions
Running migrations:
Applying backend.0001_initial... OK
执行该段代码后,可在mysql中看到表格Book被成功创建
至此后端成功搭建,在没有前端连接基础上,可以直接启动Django服务,通过http调用接口在浏览器上测试
(my_django) XXX:book_manage XXX$ python manage.py runserver
http://127.0.0.1:8000/backend/delete_book?id=1
参考文章
https://sitin.blog.csdn.net/article/details/103607472?spm=1001.2101.3001.6650.12&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-12.pc_relevant_paycolumn_v3&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-12.pc_relevant_paycolumn_v3&utm_relevant_index=19
|