原创|使用教程|编辑:status|2020-02-11 16:03:41.240|阅读 588 次
概述:在本教程中,我们将使用React和Django构建一个CRUD应用程序用来做图书管理。CRUD代表创建,读取,更新和删除,本篇将讲到后端部分。
# 慧都年终大促·界面/图表报表/文档/IDE等千款热门软控件火热促销中 >>
相关链接:
在上一篇我们讲到了#如何在myeclipse中用React和Django创建一个CRUD应用程序#的前端搭建部分,本篇将继续讲解如何利用使用Django构建Books API。
一、使用Django构建Books API
我们将使用Django创建books API,创建一个新的虚拟项目:
如果尚未安装pipenv ,则需要在终端中运行以下命令来安装它:pip install pipenv
使用集成终端,激活pipenv shell以创建Django项目:pipenv shell
完成后,运行以下命令来安装Django和Django REST Framework:
pipenv install django pipenv install django-rest-framework接下来,我们创建一个Django项目并创建一个Django应用。
django-admin startproject booksApi cd booksApi/ django-admin startapp books这将在books-api文件夹中创建新文件夹。更新INSTALLLED_APPS在settings.py包括书籍和Django的REST的框架。
# books-api/booksApi/booksApi/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'books', ]我们的数据库模型将仅包含Book模型。将以下内容添加到models.py
# books-api/booksApi/books/model.py. from django.db import models # Create your models here. class Book(models.Model): title = models.CharField(max_length=200) description = models.TextField() author = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s by %s' % (self.title, self.author)我们的图书模型包含4个字段:标题,描述,作者和created_at。
python manage.py makemigrations python manage.py migrate接下来,我们将创建一个序列化器。序列化程序用于将我们的数据转换为JSON,当我们访问端点时将返回这些数据。
# books-api/booksApi/books/serializers.py. from rest_framework import serializers from .models import Book class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ('id', 'title', 'author', 'description', 'created_at')接下来,我们更新views.py以添加我们的API视图。
# books-api/booksApi/books/views.py. from .models import Book from .serializers import BookSerializer from rest_framework import generics class BookList(generics.ListCreateAPIView): queryset = Book.objects.all() serializer_class = BookSerializer class BookDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Book.objects.all() serializer_class = BookSerializer最后,我们需要添加端点。在books-api / booksApi / books中创建urls.py
# books-api/booksApi/books/urls.py. from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from books import views urlpatterns = [ path('books/', views.BookList.as_view()), path('books//', views.BookDetail.as_view()), ]然后将books-api / booksApi / booksApi / urls.py更新为:
# books-api/booksApi/booksApi/urls.py. """booksApi URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: //docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('books.urls')), ]通过在Terminal +中运行以下代码段来启动Django服务器:
python manage.py runserver可以在http:// localhost:8000 / api / books /上查看端点。在我们在React应用中使用API之前,我们需要解决一个可能会出现的问题-CORS。运行以下命令以安装软件包以帮助CORS:
pipenv install django-cors-headers完成此操作后,像我们之前所做的那样,将以下内容添加到settings.py中的INSTALLED_APPS列表中。我们还需要添加一些新的中间件。
# books-api/booksApi/booksApi/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'books', 'corsheaders', ] 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', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ]最后,添加以下行以允许所有来源访问API:
# books-api/booksApi/booksApi/settings.py CORS_ORIGIN_ALLOW_ALL = True使用集成终端运行服务器:
python manage.py runserver
二、通过React使用API
我们将使用访存来使用books API。将以下内容添加到index.js:
class BookDashboard extends React.Component { state = { books: [] } componentDidMount() { fetch('//localhost:8000/api/books/') .then(response => response.json()) .then(data => { this.setState({books: data}); }); } ... }如上所示,我们删除了books数组的初始内容,仅使用一个空数组对其进行了初始化。
createNewBook = (book) => { fetch('//localhost:8000/api/books/', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(book), }) .then(response => response.json()) .then(book => { this.setState({books: this.state.books.concat([book])}); }); }createNewBook将POST请求与从表单获取的书籍数据一起发送到书籍api。API以新创建的书作为响应,其中包含一些其他数据,例如id和created_at。
updateBook = (newBook) => { fetch(`//localhost:8000/api/books/${newBook.id}/`, { method: 'PUT', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(newBook), }).then(response => response.json()) .then(newBook => { const newBooks = this.state.books.map(book => { if(book.id === newBook.id) { return Object.assign({}, newBook) } else { return book; } }); this.setState({books: newBooks}); });如上所示,我们正在将放置请求发送到url /。这显示了我们要更新的书。如果更新成功,我们将更新状态。
deleteBook = (bookId) => { fetch(`//localhost:8000/api/books/${bookId}/`, { method: 'DELETE', headers: { 'Content-Type': 'application/json', }, }) .then(() => { this.setState({books: this.state.books.filter(book => book.id !== bookId)}) }); }删除操作可能是最简单的。我们将DELETE请求发送到与更新相同的URL,delete操作不返回任何数据,因此我们可以更新状态。
本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,如果存在内容上的异议请邮件反馈至chenjj@capbkgr.cn
文章转载自: