Basic use python DjangoREST

Environment configuration    :     1. Install the DRF         PIP djangorestframework the install      2. Add rest_framework application       the INSTALLED_APPS = [...     'rest_framework' ,] Basic Usage:     1. Create a serializer    




    


    New serializers.py in the application unit for storing a sequence of the application.
    Create a BookInfoSerializer for serialization and de-serialization.

     BookInfoSerializer class (serializers.ModelSerializer): 
      "" "book data serializer" ""    
     class Meta -:
          Model = BookInfo 
          fields =  '__all__ is'
          Model indicate the sequence of processing of generating a data field from the model-based reference BookInfo
         fields specify the sequence model of the field which contains the class, '__ all__' indicates all the fields     2. Writing view
    

    BookInfoViewSet create a view in the application of views.py, this is a collection of views.

    from rest_framework.viewsets import ModelViewSet
    from .serializers import BookInfoSerializer
    from .models import BookInfoclass
   BookInfoViewSet(ModelViewSet):
          queryset = BookInfo.objects.all()
          serializer_class = BookInfoSerialize

  • queryset specified query set the view set used in the query data
  • serializer_class specified sequence of use during serialization or deserialization this view

   
    3. Define the Route

   The routing information in the application is defined in urls.py.

    from  .  Import  views
    from  rest_framework.routers  Import  defaultrouter
    the urlpatterns = [...]
    Router defaultrouter = ()   # can handle the view router
    router.register ( r'books' , views.BookInfoViewSet)   # router registered set of views
    urlpatterns + router.urls =   # so the router routes the information to catch django routing list    4. run the test 


    Run the current program (running as Django)

     python manage.py runserver

    127.0.0.1:8000 enter the URL in your browser, you can see API Web browser page DRF provides:
   <ignore_js_op>
More technical information may concern: gzitcast

Guess you like

Origin www.cnblogs.com/heimaguangzhou/p/11635231.html