程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Djangorestframework quick start

編輯:Python

Keep creating , Accelerate growth ! This is my participation 「 Nuggets day new plan · 6 Yuegengwen challenge 」 Of the 20 God , Click to see the event details

1、 Preface

Django It's a Python Developed Web frame , Use Django We can quickly develop websites 、 Personal blog, etc . But usually it uses Django We all use the back end to directly html Render to browser . Sometimes we use it to develop pure back-end interfaces . For what purpose , It depends on our view function in China return What happened (return Render perhaps return JsonResponse).

DjangoRestFramework Is based on Django Pure Api development tool , When we want to develop a pure back-end program , When providing data to the front end , We usually choose DjangoRestFramework. And we can use DjangoRestFramework Of ModelViewSet and serializers.ModelSerializer Fast implementation Model Of CURD.

2、 Quick start

2.1、 Create project & install DJ,DRF

pip install django
pip install djangorestframework
​
mkdir django-demo && cd django-demo
django-admin startproject dj0
 Copy code 

2.2、 Synchronize database & Create user

python manage.py migrate
python manage.py createsuperuser
 Copy code 

2.3、 establish App

cd dj0 && python manage.py startapp app0
 Copy code 

2.4、 Configuration items settings.py

register app and drf To project

dj0/settings.py

INSTALLED_APPS = [
  ...
   'rest_framework',
   'app0',
]
 Copy code 

2.5、 Model creation

app0/models.py

from django.db import models
​
# Create your models here.
​
class Person(models.Model):
   name=models.CharField(max_length=50,verbose_name=' full name ',null=False)
   age=models.IntegerField(verbose_name=' Age ')
   sex=models.BooleanField(default=True,verbose_name=' Gender ')
​
   class Meta:
       db_table='users'
       verbose_name=' user '
       verbose_name_plural = verbose_name
 Copy code 

Remember to synchronize the database structure after creating the model .

  1. python manage.py makemigrations
  2. python manage.py migrate

2.6、 Serialization model

app0/serializers.py

from rest_framework import serializers
from app0.models import Person
​
# Create serializer class , Called in an attempt
class PersonModelSerializer(serializers.ModelSerializer):
   class Meta:
       model = Person
       fields = "__all__"
 Copy code 

2.7、 View function development

Here we can return... In the view function html、 character string 、json And so on , But in drf The interface of , We specify the statement to query the data ( object ) And serialization class .

# Create your views here.
from django.http import HttpResponse
import datetime
​
def v1(request):
   now = datetime.datetime.now()
   html = "<html><body>It is now %s.</body></html>" % now
   return HttpResponse(html)
   
def hi(request):
   return HttpResponse('<h1>hi,baby!</h1>')
​
from rest_framework.viewsets import ModelViewSet
from .models import Person
from .serializers import PersonModelSerializer
# Create your views here.
class PersonViewSet(ModelViewSet):
   queryset = Person.objects.all()  # Specify the queried data object , Data set
   serializer_class = PersonModelSerializer # Specifies the serializer
 Copy code 

2.8、url distribution

the app Of urls Install to project Of urls in . Although we can also project Of urls Route directly to app View in , But in order to comply with the specifications of the blueprint , We still need to be different app The route of is project And distribute it in the library .

dj0 Of urls.py

from django.contrib import admin
from django.urls import path,include
from app0 import views
​
urlpatterns = [
   path('admin/', admin.site.urls),
   path('app0/', include('app0.urls')),  # Route to app0/, Automatically forwarded to app0 Inside urls In the middle
   path('',views.hi) # / route , Will be routed to app0 Of hi Go in view
  ]
 Copy code 

app0 Of urls.py

from django.urls import path
​
from . import views
from rest_framework.routers import DefaultRouter
​
# Normal routing
app_name='app0'
urlpatterns = [
   path('', views.v1,name='app0index'),
   path('hi', views.hi,name='hi'),
]
​
# drf The routing
router = DefaultRouter()  # Routers that can handle views
router.register('person', views.PersonViewSet)  # Register the view set with the router
urlpatterns += router.urls
 Copy code 

2.9、 Start the service

python manage.py runserver localhost:8989
 Copy code 

Access link :http://localhost:8989/app0/person/

You can see ,DRF It provides us with a good operation page , We can do it here get、post、options request . namely CR Function has been realized .

2.10、CR

We enter the name 、 Age 、 Click... After sex POST You can create a piece of data .

2.11、UD

We add... After the access link id You can reach the details page of the object .

Access link :http://localhost:8989/app0/person/3

Above , On this detail page, we can update and delete this object .

such ,UD Function realization .

above ,CRUD You can use curl、http Tools to test , It can also provide data support for the front end .

3、 summary

DjangoRestFramework It is an implementation that can be avoided CRUD Code 、 Use only Model、Serializers、ModelViewSet Can be realized quickly CRUD Of Django Tools .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved