Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand Django REST Framework

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Today, I will talk to you about how to understand Django REST Framework. Many people may not know much about it. In order to let you know more, Xiaobian summarized the following contents for you. I hope you can gain something according to this article.

1. Django REST framework

The Django REST framework is a powerful and flexible toolkit for building Web APIs, and the Django Rest Framework is a Django dependent extension Restful Api framework, similar to Django usage style, its official website is https://www.django-rest-framework.org/

2. Design API

Let's first select an APP, for example, I choose schools APP. How to design an API interface in this APP, and return detailed information of all schools in the database when the front-end request is made?

Step 1: First, you need to add a secondary route to the urls.py file (root route) of your project.

url(r'^school/', include('schools.urls', namespace='schools'))

Step 2: Add a route to the urls.py file in the schools APP, specify the access path, and import the AllSchoolsView class. The AllSchoolsView class is written in the view.py file,(remember to perform the makmigration and migrate operations)

url(r'^all/$', AllSchoolsView.as_view(), name='all')

Step 3: Write the AllSchoolsView class in the views.py file in the schools APP;

from django.views.generic.base import Viewimport jsonfrom django.core.serializers import serializefrom django.http import HttpResponse, JsonResponsefrom .models import Schoolclass AllSchoolsView(View): def get(self, request): schools = School.objects.all() #Directly convert QuerySet objects in the database to json data format goods_json = serialize('json', schools) print(type(goods_json)) print('serialize: --------{}'.format(goods_json)) return HttpResponse(content=goods_json, content_type='application/json')

Step 4: In the models.py file in the schools APP, create the schools_school table according to the requirements;

from django.db import modelsfrom datetime import datetimeclass School(models.Model): name = models.CharField(max_length=50, verbose_name ='school name') desc = models.CharField(max_length=100, verbose_name ='school description') location = models.CharField(max_length=100, verbose_name ='school location') create_time = models.DateTimeField(default=datetime.now, verbose_name ='add time') course_numbers = models. IntegrField (default=0, verbose_name="Number of courses")

Create database table The previous article also said, here will not talk about, after the database table is created, we can add data to it, you can use the command line to add, but this is more troublesome, so here we database management and design tools Navicat (introduced at the end of the article), using this tool we can manually add and modify the data in the database table, especially convenient;

First you need to select a database to be used, I use MySql, and then create a connection, and then fill in the options:

Step 5: Create the data in the schools_school table in the database. You can operate the database through Navicat. Finally, our database represents this:

Step 6: Run the project and get the json data we want. The access path is http://127.0.0.1:8000/schools/all/;

3. Customizing the Restful API with the Django REST framework

Step 1: First install the packages you need.

pip install djangorestframeworkpip install markdown # Markdown support for the browsable API.pip install django-filter # Filtering support

Step 2: Then add rest_framewor to INSTALLED_APPS in the project's settings file;

INSTALLED_APPS = ( 'rest_framework',)

Step 3: Add a route to the root route urls.py to support browser access to api authentication;

url(r'^api-auth/', include('rest_framework.urls'))

Step 4: Create an administrator for Django, select Tool->Run manage.py Task, then execute create supervisor user, edit your username, email and password.

Step 5: Create serializer.py file in schools APP, import serializers module into this file, and then create a serialization class (named by yourself), so that this class inherits Serializer class under serializers module;

from rest_framework import serializersclass SchoolSerializer(serializers.Serializer): name = serializers.CharField() course_numbers = serializers.IntegerField()

Step 6: Rewrite the AllSchoolsView class in the views.py file in the schools APP, restart the server and you will get the data returned by the Django REST framework;

from .models import Schoolfrom rest_framework.views import APIViewfrom rest_framework.response import Responsefrom .serializer import SchoolSerializerclass AllSchoolsView(APIView): def get(self, request): schools = School.objects.all() # many means return a list, if not set, return a list schools_serializer = SchoolSerializer(schools, many=True) return Response(schools_serializer.data)

4.Navicat

Navicat is a set of database management tools that can create multiple connections to facilitate the management of MySQL, Oracle, PostgreSQL, SQLite, SQL Server, MariaDB and/or MongoDB and other different types of databases, and support the management of certain cloud databases, such as Alibaba Cloud, Tencent Cloud (Cloud);

Navicat provides three platform versions Windows, macOS, Linux, allowing users to connect to local or remote servers, and provides some practical database tools to help users manage data, including Navicat Cloud collaboration, data modeling, data transfer, data synchronization, structure synchronization, import, export, backup, restore and automatic operation;

Having read all this, do you have any idea what the Django REST Framework should be? If you still want to know more knowledge or related content, please pay attention to the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report