Service: use django to build: use react's front-end and back-end separation

 清晰的看见,前后端分离时, 后端api 与 前端react如何结合。

4.1 Global environment creation

Initialize the backend environment. If you need to operate in the newly created backend virtualization environment, reinstall django, otherwise django-admin is invalid

 pip install install django~=3.1.0
 django-admin startproject config .

 python manage.py startapp todos
 python manage.py migrate

Register to global configuration

 config/setting.py
 	# Local
	INSTALLED_APPS = ['todos', # new]

创建models,todos/models.py from django.db import models class Todo(models.Model): title = models.CharField(max_length=200) body = models.TextField() def str(self): return self.title

Update the library, create migrations.

The resulting single migration file will contain data on both applications. This just makes debugging harder. Minimize migration

python manage.py makemigrations todos
python manage.py makemigrations  # 不指定app时,将迁移所有有改动的app
python manage.py migrate  

If we go into the admin it doesn't immediately show our Todos app. We need to change the todos/admin.py file to create 3 todos as follows, and then create web pages for them, which requires new urls, views, templates

register application

INSTALLED_APPS = [ # 3rd party
				'rest_framework',
				'todos', 
					]
  • Set permissions to allow all

Implicit is designed by default so that developers can drop in and start working quickly on their local development environment. However, the default settings are not suitable for production.

So usually, we make some changes to them during the project

REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [
			'rest_framework.permissions.AllowAny', ] }

AllowAny is one of them, which means that when we explicitly set it, as above, the effect is exactly the same as without DEFAULT_PERMISSION_CLASSES configuration.

The backend api service requires three parts urls.py, views.py, and serializers.py, no template required

4.2 urls, views, serializers

global urls

# config/urls.py
	from django.contrib import admin
	from django.urls import include, path # new
		urlpatterns = [
			path('admin/', admin.site.urls),
			path('api/', include('todos.urls')), # new
			]

App routing configuration

# todos/urls.py
	from django.urls import path
	from .views import ListTodo, DetailTodo
	urlpatterns = [
			path('<int:pk>/', DetailTodo.as_view()),
			path('', ListTodo.as_view()),
	]

We're also referencing two views that haven't been created yet: ListTodo and DetailTodo.

但是,路由已完成。空字符串''处将有所有待办事项的列表,其他api/上的单词。每个待办事项都将在其主键上可用,这是一个值Django会在每个数据库表中自动设置。第一个条目是1,第二个条目是2,依此类推。

因此,我们的第一个待办事项最终将位于API端点api/1/

现在,我们需要将模型中的数据转换为JSON,在URL上输出。

因此,我们需要一个序列化器restful框架有强大的内建序列化类 serializers

# todos/serializers.py
	from rest_framework import serializers
	from .models import Todo
	class TodoSerializer(serializers.ModelSerializer):
		class Meta:
			model = Todo
			fields = ('id', 'title', 'body',)

我们正在指定要使用的模型以及具体的我们要公开的字段。请记住,id是由Django自动创建的。

因此我们没有必须在我们的Todo模型中定义它,但是我们将在细节视图中使用它。

  • Views

views.py 在 django中 是将数据发送到 templates,在rest框架中 其值将被发送到序列化操作类中。

Django REST Framework视图的语法故意与常规Django视图非常相似就像常规Django一样,Django REST Framework附带了通用视图以供通用案件。这就是我们在这里使用的。

我们将使用两个视图来展示数据 ListAPIView 显示所有的 todos ,
RetrieveAPIView显示单个实例

这里有重复每个视图的queryset和serializer_class的代码,即使扩展的通用视图是不同的。 在 后面,我们将学习解决该问题的视图集和路由器,并允许我们使用更少的代码来创建相同的API视图和URL

下一节解决,跨域调用api的资源共享。

4.3 跨域资源共享 CORS Cross-Origin Resource Sharing

当用户从不同站点或 同一个站点的不同位置访问时,需要配置此项。否则造成访问错误。 比如mysite.com vs yousite.cn, 或者 localhost:2000 vs localhost:3000

启用配置: 使用django-rest-framwork 中间件 django-cors-headers 1.在全局配置文件中添加相关配置即可。

config/settings.py

添加corsheaders 到 INSTALLED_APPS

在MIDDLEWARE的CommonMiddleWare上方添加CorsMiddleware 这个位置很重要,因为加载是从上到下加载

2,创建白名单:

CORS_ORIGIN_WHITELIST = ( 
    'http://192.168.3.12:3000',
    'http://localhost:8000',)

4.4 小结

从传统Django需要的唯一组件是models.py文件,urls.py路由。 views.py和serializers.py文件完全是Django REST Framework

重要的是 通过配置 CORS headers 白名单只允许两个域访问我们的api,这是新手最简单重要的方式。 然后添加一点Django REST Framework的序列化器和视图提供的魔力。

Guess you like

Origin juejin.im/post/7240458275271065658